From 4e1b9943a4ed65a37073cc2bfaa8639bac598e04 Mon Sep 17 00:00:00 2001 From: Ilya Laktyushin Date: Tue, 26 Aug 2025 15:44:41 +0400 Subject: [PATCH] Various improvements --- .../Telegram-iOS/en.lproj/Localizable.strings | 8 + .../Sources/AccountContext.swift | 2 +- submodules/Svg/PublicHeaders/Svg/Svg.h | 20 + submodules/Svg/Sources/Svg.m | 1346 ++++++++++------- .../Sources/State/Serialization.swift | 2 +- .../SyncCore/SyncCore_TelegramWallpaper.swift | 31 + .../Sources/MakePresentationTheme.swift | 25 +- .../Sources/PresentationTheme.swift | 1 + .../Sources/ServiceMessageStrings.swift | 21 +- .../Sources/ChatMessageBubbleItemNode.swift | 2 + .../ChatMessageGiftBubbleContentNode/BUILD | 1 + .../ChatMessageGiftBubbleContentNode.swift | 53 +- .../ChatMessageInteractiveMediaNode.swift | 2 +- ...hatMessageWallpaperBubbleContentNode.swift | 2 +- .../Sources/GiftViewScreen.swift | 21 +- .../Sources/SettingsThemeWallpaperNode.swift | 6 +- .../Chat/ChatControllerThemeManagement.swift | 2 +- .../TelegramUI/Sources/ChatController.swift | 38 +- .../Sources/ChatControllerNode.swift | 2 +- .../TelegramUI/Sources/ChatThemeScreen.swift | 29 +- .../TelegramUI/Sources/OpenResolvedUrl.swift | 2 +- .../Sources/SharedAccountContext.swift | 4 +- .../MetalWallpaperBackgroundNode.swift | 1 - .../Sources/WallpaperBackgroundNode.swift | 203 ++- .../Sources/WallpaperResources.swift | 56 +- 25 files changed, 1286 insertions(+), 594 deletions(-) delete mode 100644 submodules/WallpaperBackgroundNode/Sources/MetalWallpaperBackgroundNode.swift diff --git a/Telegram/Telegram-iOS/en.lproj/Localizable.strings b/Telegram/Telegram-iOS/en.lproj/Localizable.strings index 763900807a..e3cf59f815 100644 --- a/Telegram/Telegram-iOS/en.lproj/Localizable.strings +++ b/Telegram/Telegram-iOS/en.lproj/Localizable.strings @@ -14924,3 +14924,11 @@ Sorry for the inconvenience."; "Gift.Upgrade.GiftUpgrade" = "Pay %@ for Upgrade"; "Gift.View.GiftUpgrade" = "Gift an Upgrade"; + +"Gift.View.OpenChatTheme" = "This gift is the chat's theme. [Change Theme >]()"; + +"Notification.ChatTheme.Text" = "%1$@ set **%2$@** as a new theme for this chat."; +"Notification.ChatTheme.TextYou" = "You set **%@** as a new theme for this chat."; + +"Notification.ChangedThemeGift" = "%1$@ changed chat theme to %2$@"; +"Notification.YouChangedThemeGift" = "You changed chat theme to %@"; diff --git a/submodules/AccountContext/Sources/AccountContext.swift b/submodules/AccountContext/Sources/AccountContext.swift index e186981260..6a36eb689d 100644 --- a/submodules/AccountContext/Sources/AccountContext.swift +++ b/submodules/AccountContext/Sources/AccountContext.swift @@ -1326,7 +1326,7 @@ public protocol SharedAccountContext: AnyObject { func makeStarsGiveawayBoostScreen(context: AccountContext, peerId: EnginePeer.Id, boost: ChannelBoostersContext.State.Boost) -> ViewController func makeStarsIntroScreen(context: AccountContext) -> ViewController func makeGiftViewScreen(context: AccountContext, message: EngineMessage, shareStory: ((StarGift.UniqueGift) -> Void)?) -> ViewController - func makeGiftViewScreen(context: AccountContext, gift: StarGift.UniqueGift, shareStory: ((StarGift.UniqueGift) -> Void)?, dismissed: (() -> Void)?) -> ViewController + func makeGiftViewScreen(context: AccountContext, gift: StarGift.UniqueGift, shareStory: ((StarGift.UniqueGift) -> Void)?, openChatTheme: (() -> Void)?, dismissed: (() -> Void)?) -> ViewController func makeGiftWearPreviewScreen(context: AccountContext, gift: StarGift.UniqueGift) -> ViewController func makeStorySharingScreen(context: AccountContext, subject: StorySharingSubject, parentController: ViewController) -> ViewController diff --git a/submodules/Svg/PublicHeaders/Svg/Svg.h b/submodules/Svg/PublicHeaders/Svg/Svg.h index ec08bd75f8..bfbc5c3e9a 100755 --- a/submodules/Svg/PublicHeaders/Svg/Svg.h +++ b/submodules/Svg/PublicHeaders/Svg/Svg.h @@ -4,8 +4,28 @@ #import #import +@interface GiftPatternRect : NSObject + +@property (nonatomic) CGPoint center; +@property (nonatomic) CGFloat side; +@property (nonatomic) CGFloat scale; +@property (nonatomic) CGFloat rotation; + +@end + +@interface GiftPatternData : NSObject + +@property (nonatomic) CGSize size; +@property (nonatomic, strong) NSArray * _Nonnull rects; + +@end + NSData * _Nullable prepareSvgImage(NSData * _Nonnull data, bool pattern); + +GiftPatternData * _Nullable getGiftPatternData(NSData * _Nonnull data); + UIImage * _Nullable renderPreparedImage(NSData * _Nonnull data, CGSize size, UIColor * _Nonnull backgroundColor, CGFloat scale, bool fit); +UIImage * _Nullable renderPreparedImageWithSymbol(NSData * _Nonnull data, CGSize size, UIColor * _Nonnull backgroundColor, CGFloat scale, bool fit, UIImage * _Nullable symbolImage, int32_t modelRectIndex); UIImage * _Nullable drawSvgImage(NSData * _Nonnull data, CGSize size, UIColor * _Nullable backgroundColor, UIColor * _Nullable foregroundColor, CGFloat scale, bool opaque); diff --git a/submodules/Svg/Sources/Svg.m b/submodules/Svg/Sources/Svg.m index f425c9c968..1e9424f4cb 100755 --- a/submodules/Svg/Sources/Svg.m +++ b/submodules/Svg/Sources/Svg.m @@ -1,255 +1,433 @@ #import - #import "nanosvg.h" #define UIColorRGBA(rgb,a) ([[UIColor alloc] initWithRed:(((rgb >> 16) & 0xff) / 255.0f) green:(((rgb >> 8) & 0xff) / 255.0f) blue:(((rgb) & 0xff) / 255.0f) alpha:a]) - -CGSize aspectFillSize(CGSize size, CGSize bounds) { - CGFloat scale = MAX(bounds.width / MAX(1.0, size.width), bounds.height / MAX(1.0, size.height)); +#define CLAMP(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x))) + +static inline CGSize aspectFillSize(CGSize size, CGSize bounds) { + if (size.width <= 0 || size.height <= 0) return CGSizeZero; + CGFloat scale = MAX(bounds.width / size.width, bounds.height / size.height); return CGSizeMake(floor(size.width * scale), floor(size.height * scale)); } -CGSize aspectFitSize(CGSize size, CGSize bounds) { - CGFloat scale = MIN(bounds.width / MAX(1.0, size.width), bounds.height / MAX(1.0, size.height)); +static inline CGSize aspectFitSize(CGSize size, CGSize bounds) { + if (size.width <= 0 || size.height <= 0) return CGSizeZero; + CGFloat scale = MIN(bounds.width / size.width, bounds.height / size.height); return CGSizeMake(floor(size.width * scale), floor(size.height * scale)); } -@interface SvgXMLParsingDelegate : NSObject { - NSString *_elementName; - NSString *_currentStyleString; +static inline CGFloat deg2rad(CGFloat deg) { return (deg * (CGFloat)M_PI) / 180.0; } + +static CGAffineTransform SVGParseOneTransform(NSString *one) { + NSString *s = [one stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; + if (s.length == 0) return CGAffineTransformIdentity; + + NSRange paren = [s rangeOfString:@"("]; + if (paren.location == NSNotFound) return CGAffineTransformIdentity; + + NSString *name = [[s substringToIndex:paren.location] lowercaseString]; + NSString *argsStr = [s substringWithRange:NSMakeRange(paren.location + 1, s.length - paren.location - 2)]; + + NSMutableArray *nums = [NSMutableArray array]; + { + NSScanner *sc = [NSScanner scannerWithString:argsStr]; + while (!sc.isAtEnd) { + double v; + if ([sc scanDouble:&v]) { + [nums addObject:@(v)]; + } else { + sc.scanLocation += 1; + } + } + } + + if ([name isEqualToString:@"translate"]) { + CGFloat tx = nums.count > 0 ? nums[0].doubleValue : 0; + CGFloat ty = nums.count > 1 ? nums[1].doubleValue : 0; + return CGAffineTransformMakeTranslation(tx, ty); + } else if ([name isEqualToString:@"scale"]) { + CGFloat sx = nums.count > 0 ? nums[0].doubleValue : 1; + CGFloat sy = nums.count > 1 ? nums[1].doubleValue : sx; + return CGAffineTransformMakeScale(sx, sy); + } else if ([name isEqualToString:@"rotate"]) { + CGFloat a = nums.count > 0 ? deg2rad(nums[0].doubleValue) : 0; + if (nums.count >= 3) { + CGFloat cx = nums[1].doubleValue, cy = nums[2].doubleValue; + CGAffineTransform t = CGAffineTransformIdentity; + t = CGAffineTransformTranslate(t, cx, cy); + t = CGAffineTransformRotate(t, a); + t = CGAffineTransformTranslate(t, -cx, -cy); + return t; + } else { + return CGAffineTransformMakeRotation(a); + } + } else if ([name isEqualToString:@"matrix"] && nums.count >= 6) { + CGFloat a = nums[0].doubleValue, b = nums[1].doubleValue; + CGFloat c = nums[2].doubleValue, d = nums[3].doubleValue; + CGFloat e = nums[4].doubleValue, f = nums[5].doubleValue; + return CGAffineTransformMake(a, b, c, d, e, f); + } + return CGAffineTransformIdentity; } -@property (nonatomic, strong, readonly) NSMutableDictionary *styles; +static CGAffineTransform SVGParseTransformList(NSString *list) { + if (list.length == 0) { + return CGAffineTransformIdentity; + } + + NSMutableArray *chunks = [NSMutableArray array]; + { + NSMutableString *cur = [NSMutableString string]; + NSInteger depth = 0; + for (NSUInteger i = 0; i < list.length; i++) { + unichar ch = [list characterAtIndex:i]; + [cur appendFormat:@"%C", ch]; + if (ch == '(') depth++; + if (ch == ')') { + depth--; + if (depth == 0) { + [chunks addObject:[cur copy]]; + [cur setString:@""]; + } + } + } + } + CGAffineTransform t = CGAffineTransformIdentity; + for (NSString *part in chunks) { + t = CGAffineTransformConcat(t, SVGParseOneTransform(part)); + } + return t; +} + +static inline CGPoint CGPointApplyAffineToPoint(CGPoint p, CGAffineTransform t) { + return CGPointMake(p.x * t.a + p.y * t.c + t.tx, + p.x * t.b + p.y * t.d + t.ty); +} + +static inline void DecomposeScaleRotation(CGAffineTransform t, CGFloat *outScale, CGFloat *outRotation) { + CGFloat scaleX = hypot(t.a, t.b); + CGFloat scaleY = hypot(t.c, t.d); + if (outScale) *outScale = (scaleX + scaleY) * 0.5; + if (outRotation) *outRotation = atan2(t.b, t.a); +} + +@implementation GiftPatternData @end -@implementation SvgXMLParsingDelegate +@implementation GiftPatternRect + +@end + + +@interface SvgXMLParsingDelegate : NSObject +@property (nonatomic, strong, readonly) NSMutableDictionary *styles; +@property (nonatomic, strong) NSMutableArray *giftRects; +@end + +@implementation SvgXMLParsingDelegate { + NSString *_elementName; + NSMutableString *_currentStyleString; + + bool _inGiftPatterns; + CGAffineTransform _giftGroupTransform; +} - (instancetype)init { self = [super init]; - if (self != nil) { + if (self) { _styles = [[NSMutableDictionary alloc] init]; + _currentStyleString = [[NSMutableString alloc] init]; + _giftRects = [NSMutableArray array]; + _giftGroupTransform = CGAffineTransformIdentity; + _inGiftPatterns = false; } return self; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { - _elementName = elementName; + _elementName = [elementName copy]; + + if ([_elementName isEqualToString:@"g"]) { + NSString *gid = attributeDict[@"id"]; + if ([[gid lowercaseString] isEqualToString:@"giftpatterns"]) { + _inGiftPatterns = true; + NSString *t = attributeDict[@"transform"]; + _giftGroupTransform = t.length ? SVGParseTransformList(t) : CGAffineTransformIdentity; + } + } else if (_inGiftPatterns && [_elementName isEqualToString:@"rect"]) { + CGFloat x = attributeDict[@"x"] ? attributeDict[@"x"].doubleValue : 0; + CGFloat y = attributeDict[@"y"] ? attributeDict[@"y"].doubleValue : 0; + CGFloat w = attributeDict[@"width"] ? attributeDict[@"width"].doubleValue : 0; + CGFloat h = attributeDict[@"height"] ? attributeDict[@"height"].doubleValue : 0; + + CGFloat side = w > 0 ? w : h; + + CGAffineTransform rectT = CGAffineTransformIdentity; + NSString *rt = attributeDict[@"transform"]; + if (rt.length) { + rectT = SVGParseTransformList(rt); + } + + CGAffineTransform total = CGAffineTransformConcat(_giftGroupTransform, rectT); + + CGPoint localCenter = CGPointMake(x + w * 0.5, y + h * 0.5); + CGPoint center = CGPointApplyAffineToPoint(localCenter, total); + + CGFloat scale = 1.0, rotation = 0.0; + DecomposeScaleRotation(total, &scale, &rotation); + + GiftPatternRect *rec = [[GiftPatternRect alloc] init]; + rec.center = center; + rec.side = side; + rec.scale = scale; + rec.rotation = rotation; + [_giftRects addObject:rec]; + } } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { - if ([_elementName isEqualToString:@"style"]) { - int currentClassNameStartIndex = -1; - int currentClassContentsStartIndex = -1; - - NSString *currentClassName = nil; - - NSCharacterSet *alphanumeric = [NSCharacterSet alphanumericCharacterSet]; - - for (int i = 0; i < _currentStyleString.length; i++) { - unichar c = [_currentStyleString characterAtIndex:i]; - if (currentClassNameStartIndex != -1) { - if (![alphanumeric characterIsMember:c]) { - currentClassName = [_currentStyleString substringWithRange:NSMakeRange(currentClassNameStartIndex, i - currentClassNameStartIndex)]; - currentClassNameStartIndex = -1; - } - } else if (currentClassContentsStartIndex != -1) { - if (c == '}') { - NSString *classContents = [_currentStyleString substringWithRange:NSMakeRange(currentClassContentsStartIndex, i - currentClassContentsStartIndex)]; - if (currentClassName != nil && classContents != nil) { - _styles[currentClassName] = classContents; - currentClassName = nil; - } - currentClassContentsStartIndex = -1; - } - } - - if (currentClassNameStartIndex == -1 && currentClassContentsStartIndex == -1) { - if (c == '.') { - currentClassNameStartIndex = i + 1; - } else if (c == '{') { - currentClassContentsStartIndex = i + 1; - } - } - } + if ([_elementName isEqualToString:@"style"] && _currentStyleString.length > 0) { + [self parseStyleString:_currentStyleString]; + [_currentStyleString setString:@""]; + } + if ([_elementName isEqualToString:@"g"] && _inGiftPatterns) { + _inGiftPatterns = false; + _giftGroupTransform = CGAffineTransformIdentity; } _elementName = nil; } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { if ([_elementName isEqualToString:@"style"]) { - if (_currentStyleString == nil) { - _currentStyleString = string; - } else { - _currentStyleString = [_currentStyleString stringByAppendingString:string]; + [_currentStyleString appendString:string]; + } +} + +- (void)parseStyleString:(NSString *)styleString { + NSError *error = nil; + NSRegularExpression *regex = [NSRegularExpression + regularExpressionWithPattern:@"\\.([a-zA-Z0-9_-]+)\\s*\\{([^}]+)\\}" + options:0 error:&error]; + + if (error) { + [self parseStyleStringLegacy:styleString]; + return; + } + + [regex enumerateMatchesInString:styleString options:0 range:NSMakeRange(0, styleString.length) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) { + if (match.numberOfRanges >= 3) { + NSString *className = [styleString substringWithRange:[match rangeAtIndex:1]]; + NSString *classContents = [styleString substringWithRange:[match rangeAtIndex:2]]; + self.styles[className] = [classContents stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; + } + }]; +} + +- (void)parseStyleStringLegacy:(NSString *)styleString { + NSInteger currentClassNameStartIndex = -1; + NSInteger currentClassContentsStartIndex = -1; + NSString *currentClassName = nil; + NSCharacterSet *classNameChars = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-"]; + + for (NSInteger i = 0; i < styleString.length; i++) { + unichar c = [styleString characterAtIndex:i]; + + if (currentClassNameStartIndex != -1) { + if (![classNameChars characterIsMember:c]) { + currentClassName = [styleString substringWithRange:NSMakeRange(currentClassNameStartIndex, i - currentClassNameStartIndex)]; + currentClassNameStartIndex = -1; + } + } else if (currentClassContentsStartIndex != -1) { + if (c == '}') { + NSString *classContents = [styleString substringWithRange:NSMakeRange(currentClassContentsStartIndex, i - currentClassContentsStartIndex)]; + if (currentClassName.length > 0 && classContents.length > 0) { + self.styles[currentClassName] = [classContents stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + } + currentClassName = nil; + currentClassContentsStartIndex = -1; + } + } + + if (currentClassNameStartIndex == -1 && currentClassContentsStartIndex == -1) { + if (c == '.') { + currentClassNameStartIndex = i + 1; + } else if (c == '{') { + currentClassContentsStartIndex = i + 1; + } } } } @end +void renderShape(NSVGshape *shape, CGContextRef context, UIColor *foregroundColor) { + if (shape->fill.type != NSVG_PAINT_NONE) { + CGContextSetFillColorWithColor(context, [foregroundColor colorWithAlphaComponent:shape->opacity].CGColor); + + CGContextBeginPath(context); + bool isFirstPath = true; + + for (NSVGpath *path = shape->paths; path; path = path->next) { + if (!isFirstPath && path->closed) { + CGContextBeginPath(context); + } + + CGContextMoveToPoint(context, path->pts[0], path->pts[1]); + + for (int i = 0; i < path->npts - 1; i += 3) { + float *p = &path->pts[i * 2]; + CGContextAddCurveToPoint(context, p[2], p[3], p[4], p[5], p[6], p[7]); + } + + if (path->closed) { + CGContextClosePath(context); + } + + isFirstPath = NO; + } + + switch (shape->fillRule) { + case NSVG_FILLRULE_EVENODD: + CGContextEOFillPath(context); + break; + default: + CGContextFillPath(context); + break; + } + } + + if (shape->stroke.type != NSVG_PAINT_NONE && shape->strokeWidth > 0) { + CGContextSetStrokeColorWithColor(context, [foregroundColor colorWithAlphaComponent:shape->opacity].CGColor); + CGContextSetLineWidth(context, shape->strokeWidth); + CGContextSetMiterLimit(context, shape->miterLimit); + + switch (shape->strokeLineCap) { + case NSVG_CAP_ROUND: CGContextSetLineCap(context, kCGLineCapRound); break; + case NSVG_CAP_SQUARE: CGContextSetLineCap(context, kCGLineCapSquare); break; + default: CGContextSetLineCap(context, kCGLineCapButt); break; + } + + switch (shape->strokeLineJoin) { + case NSVG_JOIN_BEVEL: CGContextSetLineJoin(context, kCGLineJoinBevel); break; + case NSVG_JOIN_ROUND: CGContextSetLineJoin(context, kCGLineJoinRound); break; + default: CGContextSetLineJoin(context, kCGLineJoinMiter); break; + } + + for (NSVGpath *path = shape->paths; path; path = path->next) { + CGContextBeginPath(context); + CGContextMoveToPoint(context, path->pts[0], path->pts[1]); + + for (int i = 0; i < path->npts - 1; i += 3) { + float *p = &path->pts[i * 2]; + CGContextAddCurveToPoint(context, p[2], p[3], p[4], p[5], p[6], p[7]); + } + + if (path->closed) { + CGContextClosePath(context); + } + CGContextStrokePath(context); + } + } +} + UIImage * _Nullable drawSvgImage(NSData * _Nonnull data, CGSize size, UIColor *backgroundColor, UIColor *foregroundColor, CGFloat canvasScale, bool opaque) { + if (!data || data.length == 0) return nil; NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; - if (parser == nil) { - return nil; - } + if (!parser) return nil; + SvgXMLParsingDelegate *delegate = [[SvgXMLParsingDelegate alloc] init]; parser.delegate = delegate; - [parser parse]; + if (![parser parse]) return nil; NSMutableString *xmlString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - if (xmlString == nil) { - return nil; - } + if (!xmlString) return nil; for (NSString *styleName in delegate.styles) { NSString *styleValue = delegate.styles[styleName]; - [xmlString replaceOccurrencesOfString:[NSString stringWithFormat:@"class=\"%@\"", styleName] withString:[NSString stringWithFormat:@"style=\"%@\"", styleValue] options:0 range:NSMakeRange(0, xmlString.length)]; + NSString *searchPattern = [NSString stringWithFormat:@"class=\"%@\"", styleName]; + NSString *replacement = [NSString stringWithFormat:@"style=\"%@\"", styleValue]; + [xmlString replaceOccurrencesOfString:searchPattern withString:replacement + options:NSLiteralSearch range:NSMakeRange(0, xmlString.length)]; } - const char *zeroTerminatedData = xmlString.UTF8String; - - NSVGimage *image = nsvgParse((char *)zeroTerminatedData, "px", 96); - if (image == nil || image->width < 1.0f || image->height < 1.0f) { + const char *svgString = xmlString.UTF8String; + NSVGimage *image = nsvgParse((char *)svgString, "px", 96); + if (!image || image->width < 1.0f || image->height < 1.0f) { + if (image) nsvgDelete(image); return nil; } + CGSize originalSize = CGSizeMake(image->width, image->height); if (CGSizeEqualToSize(size, CGSizeZero)) { - size = CGSizeMake(image->width, image->height); + size = originalSize; } - + UIGraphicsBeginImageContextWithOptions(size, opaque, canvasScale); CGContextRef context = UIGraphicsGetCurrentContext(); - if (backgroundColor != nil) { - CGContextSetFillColorWithColor(context, backgroundColor.CGColor); - CGContextFillRect(context, CGRectMake(0.0f, 0.0f, size.width, size.height)); + if (!context) { + nsvgDelete(image); + return nil; } - CGSize svgSize = CGSizeMake(image->width, image->height); - CGSize drawingSize = aspectFillSize(svgSize, size); + if (backgroundColor) { + CGContextSetFillColorWithColor(context, backgroundColor.CGColor); + CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)); + } - CGFloat scale = MAX(size.width / MAX(1.0, svgSize.width), size.height / MAX(1.0, svgSize.height)); + CGSize drawingSize = aspectFillSize(originalSize, size); + CGFloat scale = MAX(size.width / originalSize.width, size.height / originalSize.height); + CGFloat offsetX = (size.width - drawingSize.width) / (2.0 * scale); + CGFloat offsetY = (size.height - drawingSize.height) / (2.0 * scale); CGContextScaleCTM(context, scale, scale); - CGContextTranslateCTM(context, (size.width - drawingSize.width) / 2.0, (size.height - drawingSize.height) / 2.0); + CGContextTranslateCTM(context, offsetX, offsetY); - for (NSVGshape *shape = image->shapes; shape != NULL; shape = shape->next) { - if (!(shape->flags & NSVG_FLAGS_VISIBLE)) { - continue; - } + for (NSVGshape *shape = image->shapes; shape; shape = shape->next) { + if (!(shape->flags & NSVG_FLAGS_VISIBLE) || shape->opacity <= 0) continue; - if (shape->fill.type != NSVG_PAINT_NONE) { - CGContextSetFillColorWithColor(context, [foregroundColor colorWithAlphaComponent:shape->opacity].CGColor); - - bool isFirst = true; - bool hasStartPoint = false; - CGPoint startPoint; - for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { - if (isFirst) { - CGContextBeginPath(context); - isFirst = false; - hasStartPoint = true; - startPoint.x = path->pts[0]; - startPoint.y = path->pts[1]; - } - CGContextMoveToPoint(context, path->pts[0], path->pts[1]); - for (int i = 0; i < path->npts - 1; i += 3) { - float *p = &path->pts[i * 2]; - CGContextAddCurveToPoint(context, p[2], p[3], p[4], p[5], p[6], p[7]); - } - - if (path->closed) { - if (hasStartPoint) { - hasStartPoint = false; - CGContextAddLineToPoint(context, startPoint.x, startPoint.y); - } - } - } - switch (shape->fillRule) { - case NSVG_FILLRULE_EVENODD: - CGContextEOFillPath(context); - break; - default: - CGContextFillPath(context); - break; - } - } - - if (shape->stroke.type != NSVG_PAINT_NONE) { - CGContextSetStrokeColorWithColor(context, [foregroundColor colorWithAlphaComponent:shape->opacity].CGColor); - CGContextSetMiterLimit(context, shape->miterLimit); - - CGContextSetLineWidth(context, shape->strokeWidth); - switch (shape->strokeLineCap) { - case NSVG_CAP_BUTT: - CGContextSetLineCap(context, kCGLineCapButt); - break; - case NSVG_CAP_ROUND: - CGContextSetLineCap(context, kCGLineCapRound); - break; - case NSVG_CAP_SQUARE: - CGContextSetLineCap(context, kCGLineCapSquare); - break; - default: - break; - } - switch (shape->strokeLineJoin) { - case NSVG_JOIN_BEVEL: - CGContextSetLineJoin(context, kCGLineJoinBevel); - break; - case NSVG_JOIN_MITER: - CGContextSetLineJoin(context, kCGLineJoinMiter); - break; - case NSVG_JOIN_ROUND: - CGContextSetLineJoin(context, kCGLineJoinRound); - break; - default: - break; - } - - for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { - CGContextBeginPath(context); - CGContextMoveToPoint(context, path->pts[0], path->pts[1]); - for (int i = 0; i < path->npts - 1; i += 3) { - float *p = &path->pts[i * 2]; - CGContextAddCurveToPoint(context, p[2], p[3], p[4], p[5], p[6], p[7]); - } - - if (path->closed) { - CGContextClosePath(context); - } - CGContextStrokePath(context); - } - } + renderShape(shape, context, foregroundColor); } UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); - nsvgDelete(image); return resultImage; } +typedef NS_ENUM(uint8_t, SvgRenderCommand) { + SvgRenderCommandSetFillColorWithOpacity = 1, + SvgRenderCommandSetupStroke = 2, + SvgRenderCommandBeginPath = 3, + SvgRenderCommandMoveTo = 4, + SvgRenderCommandLineTo = 5, + SvgRenderCommandCurveTo = 6, + SvgRenderCommandClosePath = 7, + SvgRenderCommandEOFillPath = 8, + SvgRenderCommandFillPath = 9, + SvgRenderCommandStrokePath = 10, + SvgRenderCommandSetFillColorRGBA = 11, + SvgRenderCommandRectsHeader = 100, + SvgRenderCommandRectsItem = 101 +}; -@interface CGContextCoder : NSObject { +@interface CGContextCoder : NSObject +@property (nonatomic, readonly) NSData *data; +@end + +@implementation CGContextCoder { NSMutableData *_data; } -@property (nonatomic, readonly) NSData *data; - -@end - -@implementation CGContextCoder - - (instancetype)initWithSize:(CGSize)size { self = [super init]; - if (self != nil) { + if (self) { _data = [[NSMutableData alloc] init]; - int32_t intWidth = size.width; - int32_t intHeight = size.height; + int32_t intWidth = (int32_t)size.width; + int32_t intHeight = (int32_t)size.height; [_data appendBytes:&intWidth length:sizeof(intWidth)]; [_data appendBytes:&intHeight length:sizeof(intHeight)]; } @@ -257,451 +435,587 @@ UIImage * _Nullable drawSvgImage(NSData * _Nonnull data, CGSize size, UIColor *b } - (void)setFillColorWithOpacity:(CGFloat)opacity { - uint8_t command = 1; - [_data appendBytes:&command length:sizeof(command)]; + uint8_t command = SvgRenderCommandSetFillColorWithOpacity; + uint8_t intOpacity = (uint8_t)(CLAMP(opacity, 0.0, 1.0) * 255.0); - uint8_t intOpacity = opacity * 255.0; + [_data appendBytes:&command length:sizeof(command)]; [_data appendBytes:&intOpacity length:sizeof(intOpacity)]; } -- (void)setupStrokeOpacity:(CGFloat)opacity mitterLimit:(CGFloat)mitterLimit lineWidth:(CGFloat)lineWidth lineCap:(CGLineCap)lineCap lineJoin:(CGLineJoin)lineJoin { - uint8_t command = 2; +- (void)setupStrokeOpacity:(CGFloat)opacity miterLimit:(CGFloat)miterLimit lineWidth:(CGFloat)lineWidth lineCap:(CGLineCap)lineCap lineJoin:(CGLineJoin)lineJoin { + uint8_t command = SvgRenderCommandSetupStroke; + uint8_t intOpacity = (uint8_t)(CLAMP(opacity, 0.0, 1.0) * 255.0); + float floatMiterLimit = (float)miterLimit; + float floatLineWidth = (float)lineWidth; + uint8_t intLineCap = (uint8_t)lineCap; + uint8_t intLineJoin = (uint8_t)lineJoin; + [_data appendBytes:&command length:sizeof(command)]; - - uint8_t intOpacity = opacity * 255.0; [_data appendBytes:&intOpacity length:sizeof(intOpacity)]; - - float floatMitterLimit = mitterLimit; - [_data appendBytes:&floatMitterLimit length:sizeof(floatMitterLimit)]; - - float floatLineWidth = lineWidth; + [_data appendBytes:&floatMiterLimit length:sizeof(floatMiterLimit)]; [_data appendBytes:&floatLineWidth length:sizeof(floatLineWidth)]; - - uint8_t intLineCap = lineCap; [_data appendBytes:&intLineCap length:sizeof(intLineCap)]; - - uint8_t intLineJoin = lineJoin; [_data appendBytes:&intLineJoin length:sizeof(intLineJoin)]; } - (void)beginPath { - uint8_t command = 3; + uint8_t command = SvgRenderCommandBeginPath; [_data appendBytes:&command length:sizeof(command)]; } - (void)moveToPoint:(CGPoint)point { - uint8_t command = 4; - [_data appendBytes:&command length:sizeof(command)]; + uint8_t command = SvgRenderCommandMoveTo; + float x = (float)point.x, y = (float)point.y; - float floatX = point.x; - [_data appendBytes:&floatX length:sizeof(floatX)]; - - float floatY = point.y; - [_data appendBytes:&floatY length:sizeof(floatY)]; + [_data appendBytes:&command length:sizeof(command)]; + [_data appendBytes:&x length:sizeof(x)]; + [_data appendBytes:&y length:sizeof(y)]; } - (void)addLineToPoint:(CGPoint)point { - uint8_t command = 5; - [_data appendBytes:&command length:sizeof(command)]; + uint8_t command = SvgRenderCommandLineTo; + float x = (float)point.x, y = (float)point.y; - float floatX = point.x; - [_data appendBytes:&floatX length:sizeof(floatX)]; - - float floatY = point.y; - [_data appendBytes:&floatY length:sizeof(floatY)]; + [_data appendBytes:&command length:sizeof(command)]; + [_data appendBytes:&x length:sizeof(x)]; + [_data appendBytes:&y length:sizeof(y)]; } - (void)addCurveToPoint:(CGPoint)p1 p2:(CGPoint)p2 p3:(CGPoint)p3 { - uint8_t command = 6; + uint8_t command = SvgRenderCommandCurveTo; + float coords[6] = {(float)p1.x, (float)p1.y, (float)p2.x, (float)p2.y, (float)p3.x, (float)p3.y}; + [_data appendBytes:&command length:sizeof(command)]; - - float floatX1 = p1.x; - [_data appendBytes:&floatX1 length:sizeof(floatX1)]; - - float floatY1 = p1.y; - [_data appendBytes:&floatY1 length:sizeof(floatY1)]; - - float floatX2 = p2.x; - [_data appendBytes:&floatX2 length:sizeof(floatX2)]; - - float floatY2 = p2.y; - [_data appendBytes:&floatY2 length:sizeof(floatY2)]; - - float floatX3 = p3.x; - [_data appendBytes:&floatX3 length:sizeof(floatX3)]; - - float floatY3 = p3.y; - [_data appendBytes:&floatY3 length:sizeof(floatY3)]; + [_data appendBytes:coords length:sizeof(coords)]; } - (void)closePath { - uint8_t command = 7; + uint8_t command = SvgRenderCommandClosePath; [_data appendBytes:&command length:sizeof(command)]; } - (void)eoFillPath { - uint8_t command = 8; + uint8_t command = SvgRenderCommandEOFillPath; [_data appendBytes:&command length:sizeof(command)]; } - (void)fillPath { - uint8_t command = 9; + uint8_t command = SvgRenderCommandFillPath; [_data appendBytes:&command length:sizeof(command)]; } - (void)strokePath { - uint8_t command = 10; + uint8_t command = SvgRenderCommandStrokePath; [_data appendBytes:&command length:sizeof(command)]; } - (void)setFillColor:(uint32_t)color opacity:(CGFloat)opacity { - uint8_t command = 11; + uint8_t command = SvgRenderCommandSetFillColorRGBA; + uint32_t colorWithAlpha = ((uint32_t)(CLAMP(opacity, 0.0, 1.0) * 255.0) << 24) | color; + + [_data appendBytes:&command length:sizeof(command)]; + [_data appendBytes:&colorWithAlpha length:sizeof(colorWithAlpha)]; +} + +- (void)storeGiftPatternRects:(NSArray *)rects { + uint8_t command = SvgRenderCommandRectsHeader; [_data appendBytes:&command length:sizeof(command)]; - color = ((uint32_t)(opacity * 255.0) << 24) | color; - [_data appendBytes:&color length:sizeof(color)]; + uint32_t count = (uint32_t)rects.count; + [_data appendBytes:&count length:sizeof(count)]; + + for (GiftPatternRect *rect in rects) { + uint8_t item = SvgRenderCommandRectsItem; + [_data appendBytes:&item length:sizeof(item)]; + + float payload[5] = { + (float)rect.center.x, + (float)rect.center.y, + (float)rect.side, + (float)rect.scale, + (float)rect.rotation + }; + [_data appendBytes:payload length:sizeof(payload)]; + } } @end -UIColor *colorWithBGRA(uint32_t bgra) -{ - return [[UIColor alloc] initWithRed:(((bgra) & 0xff) / 255.0f) green:(((bgra >> 8) & 0xff) / 255.0f) blue:(((bgra >> 16) & 0xff) / 255.0f) alpha:(((bgra >> 24) & 0xff) / 255.0f)]; +static inline UIColor *colorWithBGRA(uint32_t bgra) { + return [[UIColor alloc] initWithRed:(((bgra) & 0xff) / 255.0f) + green:(((bgra >> 8) & 0xff) / 255.0f) + blue:(((bgra >> 16) & 0xff) / 255.0f) + alpha:(((bgra >> 24) & 0xff) / 255.0f)]; } -UIImage * _Nullable renderPreparedImage(NSData * _Nonnull data, CGSize size, UIColor *backgroundColor, CGFloat scale, bool fit) { - NSDate *startTime = [NSDate date]; - - UIColor *foregroundColor = [UIColor whiteColor]; - - int32_t ptr = 0; - int32_t width; - int32_t height; - - if (data.length < 4 * 2) { +bool processRenderCommand(uint8_t cmd, NSData *data, NSUInteger *ptr, CGContextRef *context, UIColor *foregroundColor) { + switch (cmd) { + case SvgRenderCommandSetFillColorWithOpacity: { + if (*ptr + 1 > data.length) return NO; + uint8_t opacity; + [data getBytes:&opacity range:NSMakeRange(*ptr, sizeof(opacity))]; + *ptr += sizeof(opacity); + if (context != nil) { + CGContextSetFillColorWithColor(*context, [foregroundColor colorWithAlphaComponent:opacity / 255.0].CGColor); + } + break; + } + + case SvgRenderCommandSetupStroke: { + if (*ptr + 10 > data.length) return NO; + uint8_t opacity; + float miterLimit, lineWidth; + uint8_t lineCap, lineJoin; + + [data getBytes:&opacity range:NSMakeRange(*ptr, sizeof(opacity))]; + *ptr += sizeof(opacity); + [data getBytes:&miterLimit range:NSMakeRange(*ptr, sizeof(miterLimit))]; + *ptr += sizeof(miterLimit); + [data getBytes:&lineWidth range:NSMakeRange(*ptr, sizeof(lineWidth))]; + *ptr += sizeof(lineWidth); + [data getBytes:&lineCap range:NSMakeRange(*ptr, sizeof(lineCap))]; + *ptr += sizeof(lineCap); + [data getBytes:&lineJoin range:NSMakeRange(*ptr, sizeof(lineJoin))]; + *ptr += sizeof(lineJoin); + + if (context != nil) { + CGContextSetStrokeColorWithColor(*context, [foregroundColor colorWithAlphaComponent:opacity / 255.0].CGColor); + CGContextSetMiterLimit(*context, miterLimit); + CGContextSetLineWidth(*context, lineWidth); + CGContextSetLineCap(*context, (CGLineCap)lineCap); + CGContextSetLineJoin(*context, (CGLineJoin)lineJoin); + } + break; + } + + case SvgRenderCommandBeginPath: + if (context != nil) { + CGContextBeginPath(*context); + } + break; + + case SvgRenderCommandMoveTo: { + if (*ptr + 8 > data.length) return NO; + float x, y; + [data getBytes:&x range:NSMakeRange(*ptr, sizeof(x))]; + *ptr += sizeof(x); + [data getBytes:&y range:NSMakeRange(*ptr, sizeof(y))]; + *ptr += sizeof(y); + if (context != nil) { + CGContextMoveToPoint(*context, x, y); + } + break; + } + + case SvgRenderCommandLineTo: { + if (*ptr + 8 > data.length) return NO; + float x, y; + [data getBytes:&x range:NSMakeRange(*ptr, sizeof(x))]; + *ptr += sizeof(x); + [data getBytes:&y range:NSMakeRange(*ptr, sizeof(y))]; + *ptr += sizeof(y); + if (context != nil) { + CGContextAddLineToPoint(*context, x, y); + } + break; + } + + case SvgRenderCommandCurveTo: { + if (*ptr + 24 > data.length) return NO; + float coords[6]; + [data getBytes:coords range:NSMakeRange(*ptr, sizeof(coords))]; + *ptr += sizeof(coords); + if (context != nil) { + CGContextAddCurveToPoint(*context, coords[0], coords[1], coords[2], coords[3], coords[4], coords[5]); + } + break; + } + + case SvgRenderCommandClosePath: + if (context != nil) { + CGContextClosePath(*context); + } + break; + + case SvgRenderCommandEOFillPath: + if (context != nil) { + CGContextEOFillPath(*context); + } + break; + + case SvgRenderCommandFillPath: + if (context != nil) { + CGContextFillPath(*context); + } + break; + + case SvgRenderCommandStrokePath: + if (context != nil) { + CGContextStrokePath(*context); + } + break; + + case SvgRenderCommandSetFillColorRGBA: { + if (*ptr + 4 > data.length) return NO; + uint32_t bgra; + [data getBytes:&bgra range:NSMakeRange(*ptr, sizeof(bgra))]; + *ptr += sizeof(bgra); + if (context != nil) { + CGContextSetFillColorWithColor(*context, colorWithBGRA(bgra).CGColor); + } + break; + } + case SvgRenderCommandRectsHeader: + break; + case SvgRenderCommandRectsItem: + break; + default: + return false; + } + return true; +} + +GiftPatternData *getGiftPatternData(NSData * _Nonnull data) { + if (!data || data.length < 8) { return nil; } - + + NSUInteger ptr = 0; + int32_t width, height; [data getBytes:&width range:NSMakeRange(ptr, sizeof(width))]; ptr += sizeof(width); [data getBytes:&height range:NSMakeRange(ptr, sizeof(height))]; ptr += sizeof(height); - if (CGSizeEqualToSize(size, CGSizeZero)) { - size = CGSizeMake(width, height); - } - - bool isTransparent = [backgroundColor isEqual:[UIColor clearColor]]; - - CGSize svgSize = CGSizeMake(width, height); - CGSize drawingSize; - if (fit) { - drawingSize = aspectFitSize(svgSize, size); - size = drawingSize; - } else { - drawingSize = aspectFillSize(svgSize, size); - } - - UIGraphicsBeginImageContextWithOptions(size, !isTransparent, scale); - CGContextRef context = UIGraphicsGetCurrentContext(); - if (isTransparent) { - CGContextClearRect(context, CGRectMake(0.0f, 0.0f, size.width, size.height)); - } else { - CGContextSetFillColorWithColor(context, backgroundColor.CGColor); - CGContextFillRect(context, CGRectMake(0.0f, 0.0f, size.width, size.height)); - } - - - - CGFloat renderScale = MAX(size.width / MAX(1.0, svgSize.width), size.height / MAX(1.0, svgSize.height)); - - CGContextScaleCTM(context, renderScale, renderScale); - CGContextTranslateCTM(context, (size.width - drawingSize.width) / 2.0, (size.height - drawingSize.height) / 2.0); + NSMutableArray *rects = [[NSMutableArray alloc] init]; while (ptr < data.length) { + if (ptr + 1 > data.length) break; + uint8_t cmd; [data getBytes:&cmd range:NSMakeRange(ptr, sizeof(cmd))]; ptr += sizeof(cmd); - switch (cmd) { - case 1: - { - uint8_t opacity; - [data getBytes:&opacity range:NSMakeRange(ptr, sizeof(opacity))]; - ptr += sizeof(opacity); - CGContextSetFillColorWithColor(context, [foregroundColor colorWithAlphaComponent:opacity / 255.0].CGColor); - } - break; - - case 2: - { - uint8_t opacity; - [data getBytes:&opacity range:NSMakeRange(ptr, sizeof(opacity))]; - ptr += sizeof(opacity); - CGContextSetStrokeColorWithColor(context, [foregroundColor colorWithAlphaComponent:opacity / 255.0].CGColor); - - float mitterLimit; - [data getBytes:&mitterLimit range:NSMakeRange(ptr, sizeof(mitterLimit))]; - ptr += sizeof(mitterLimit); - CGContextSetMiterLimit(context, mitterLimit); - - float lineWidth; - [data getBytes:&lineWidth range:NSMakeRange(ptr, sizeof(lineWidth))]; - ptr += sizeof(lineWidth); - CGContextSetLineWidth(context, lineWidth); - - uint8_t lineCap; - [data getBytes:&lineCap range:NSMakeRange(ptr, sizeof(lineCap))]; - ptr += sizeof(lineCap); - CGContextSetLineCap(context, lineCap); - - uint8_t lineJoin; - [data getBytes:&lineJoin range:NSMakeRange(ptr, sizeof(lineJoin))]; - ptr += sizeof(lineJoin); - CGContextSetLineCap(context, lineJoin); - } - break; - - case 3: - { - CGContextBeginPath(context); - } - break; - - case 4: - { - float x; - [data getBytes:&x range:NSMakeRange(ptr, sizeof(x))]; - ptr += sizeof(x); - - float y; - [data getBytes:&y range:NSMakeRange(ptr, sizeof(y))]; - ptr += sizeof(y); - - CGContextMoveToPoint(context, x, y); - } - break; - - case 5: - { - float x; - [data getBytes:&x range:NSMakeRange(ptr, sizeof(x))]; - ptr += sizeof(x); - - float y; - [data getBytes:&y range:NSMakeRange(ptr, sizeof(y))]; - ptr += sizeof(y); - - CGContextAddLineToPoint(context, x, y); - } - break; - - case 6: - { - float x1; - [data getBytes:&x1 range:NSMakeRange(ptr, sizeof(x1))]; - ptr += sizeof(x1); - - float y1; - [data getBytes:&y1 range:NSMakeRange(ptr, sizeof(y1))]; - ptr += sizeof(y1); - - float x2; - [data getBytes:&x2 range:NSMakeRange(ptr, sizeof(x2))]; - ptr += sizeof(x2); - - float y2; - [data getBytes:&y2 range:NSMakeRange(ptr, sizeof(y2))]; - ptr += sizeof(y2); - - float x3; - [data getBytes:&x3 range:NSMakeRange(ptr, sizeof(x3))]; - ptr += sizeof(x3); - - float y3; - [data getBytes:&y3 range:NSMakeRange(ptr, sizeof(y3))]; - ptr += sizeof(y3); - - CGContextAddCurveToPoint(context, x1, y1, x2, y2, x3, y3); - } - break; - - case 7: - { - CGContextClosePath(context); - } - break; - - case 8: - { - CGContextEOFillPath(context); - } - break; + if (cmd == SvgRenderCommandRectsHeader) { + if (ptr + sizeof(uint32_t) > data.length) break; + uint32_t count = 0; + [data getBytes:&count range:NSMakeRange(ptr, sizeof(count))]; + ptr += sizeof(count); - case 9: - { - CGContextFillPath(context); - } - break; + for (uint32_t i = 0; i < count; i++) { + if (ptr + 1 > data.length) { ptr = data.length; break; } + uint8_t itemCmd = 0; + [data getBytes:&itemCmd range:NSMakeRange(ptr, sizeof(itemCmd))]; + ptr += sizeof(itemCmd); + if (itemCmd != SvgRenderCommandRectsItem) { + ptr = data.length; + break; + } - case 10: - { - CGContextStrokePath(context); - } - break; - case 11: - { - uint32_t bgra; - [data getBytes:&bgra range:NSMakeRange(ptr, sizeof(bgra))]; - ptr += sizeof(bgra); + if (ptr + sizeof(float) * 5 > data.length) { + ptr = data.length; + break; + } + float payload[5]; + [data getBytes:payload range:NSMakeRange(ptr, sizeof(payload))]; + ptr += sizeof(payload); - CGContextSetFillColorWithColor(context, colorWithBGRA(bgra).CGColor); - CGContextStrokePath(context); + if (rects) { + GiftPatternRect *rect = [GiftPatternRect new]; + rect.center = CGPointMake(payload[0], payload[1]); + rect.side = payload[2]; + rect.scale = payload[3]; + rect.rotation = payload[4]; + [rects addObject:rect]; + } } - default: - break; + continue; + } + + if (!processRenderCommand(cmd, data, &ptr, nil, [UIColor whiteColor])) { + break; } } + + GiftPatternData *patternData = [[GiftPatternData alloc] init]; + patternData.size = CGSizeMake(width, height); + patternData.rects = rects; + return patternData; +} + +UIImage * _Nullable renderPreparedImage(NSData * _Nonnull data, CGSize size, UIColor *backgroundColor, CGFloat scale, bool fit) { + return renderPreparedImageWithSymbol(data, size, backgroundColor, scale, fit, nil, -1); +} + +UIImage * _Nullable renderPreparedImageWithSymbol(NSData * _Nonnull data, CGSize size, UIColor *backgroundColor, CGFloat scale, bool fit, UIImage * _Nullable symbolImage, int32_t modelRectIndex) { + if (!data || data.length < 8) { + return nil; + } + + CFTimeInterval startTime = CACurrentMediaTime(); + UIColor *foregroundColor = [UIColor whiteColor]; + + NSUInteger ptr = 0; + int32_t width, height; + [data getBytes:&width range:NSMakeRange(ptr, sizeof(width))]; + ptr += sizeof(width); + [data getBytes:&height range:NSMakeRange(ptr, sizeof(height))]; + ptr += sizeof(height); + + if (width <= 0 || height <= 0) return nil; + + CGSize svgSize = CGSizeMake(width, height); + if (CGSizeEqualToSize(size, CGSizeZero)) { + size = svgSize; + } + + bool isTransparent = [backgroundColor isEqual:[UIColor clearColor]]; + CGSize drawingSize = fit ? aspectFitSize(svgSize, size) : aspectFillSize(svgSize, size); + + if (fit) size = drawingSize; + + UIGraphicsBeginImageContextWithOptions(size, !isTransparent, scale); + CGContextRef context = UIGraphicsGetCurrentContext(); + if (!context) { + UIGraphicsEndImageContext(); + return nil; + } + + if (isTransparent) { + CGContextClearRect(context, CGRectMake(0, 0, size.width, size.height)); + } else { + CGContextSetFillColorWithColor(context, backgroundColor.CGColor); + CGContextFillRect(context, CGRectMake(0, 0, size.width, size.height)); + } + + CGFloat renderScale = fit ? MIN(size.width / svgSize.width, size.height / svgSize.height) : MAX(size.width / svgSize.width, size.height / svgSize.height); + + CGContextScaleCTM(context, renderScale, renderScale); + CGContextTranslateCTM(context, (size.width - drawingSize.width) / (2.0 * renderScale), (size.height - drawingSize.height) / (2.0 * renderScale)); + + NSMutableArray *rects = symbolImage ? [[NSMutableArray alloc] init] : nil; + + while (ptr < data.length) { + if (ptr + 1 > data.length) break; + + uint8_t cmd; + [data getBytes:&cmd range:NSMakeRange(ptr, sizeof(cmd))]; + ptr += sizeof(cmd); + + if (cmd == SvgRenderCommandRectsHeader) { + if (ptr + sizeof(uint32_t) > data.length) break; + uint32_t count = 0; + [data getBytes:&count range:NSMakeRange(ptr, sizeof(count))]; + ptr += sizeof(count); + for (uint32_t i = 0; i < count; i++) { + if (ptr + 1 > data.length) { ptr = data.length; break; } + uint8_t itemCmd = 0; + [data getBytes:&itemCmd range:NSMakeRange(ptr, sizeof(itemCmd))]; + ptr += sizeof(itemCmd); + if (itemCmd != SvgRenderCommandRectsItem) { ptr = data.length; break; } + + if (ptr + sizeof(float) * 5 > data.length) { ptr = data.length; break; } + float payload[5]; + [data getBytes:payload range:NSMakeRange(ptr, sizeof(payload))]; + ptr += sizeof(payload); + + if (rects) { + GiftPatternRect *rect = [GiftPatternRect new]; + rect.center = CGPointMake(payload[0], payload[1]); + rect.side = payload[2]; + rect.scale = payload[3]; + rect.rotation = payload[4]; + [rects addObject:rect]; + } + } + continue; + } + + if (!processRenderCommand(cmd, data, &ptr, &context, foregroundColor)) { + break; + } + } + + if (symbolImage && rects.count > 0) { + CGFloat symbolWidth = symbolImage.size.width; + CGFloat symbolHeight = symbolImage.size.height; + CGFloat symbolAspectRatio = (symbolHeight > 0.0 ? (symbolWidth / symbolHeight) : 1.0); + + int32_t index = 0; + for (GiftPatternRect *rect in rects) { + if (index == modelRectIndex) { + } else { + CGContextSaveGState(context); + CGContextTranslateCTM(context, rect.center.x, rect.center.y); + CGContextRotateCTM(context, rect.rotation); + + CGFloat side = rect.side * rect.scale; + CGFloat dw = side, dh = side; + if (symbolAspectRatio > 1.0) { + dh = dw / symbolAspectRatio; + } else { + dw = dh * symbolAspectRatio; + } + + CGRect dst = CGRectMake(-dw * 0.5, -dh * 0.5, dw, dh); + [symbolImage drawInRect:dst blendMode:kCGBlendModeNormal alpha:1.0]; + + CGContextRestoreGState(context); + } + index += 1; + } + } + UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); - double deltaTime = -1.0f * [startTime timeIntervalSinceNow]; - printf("drawingTime %fx%f = %f\n", size.width, size.height, deltaTime); + CFTimeInterval deltaTime = CACurrentMediaTime() - startTime; + NSLog(@"Render time %.0fx%.0f = %.4f seconds", size.width, size.height, deltaTime); return resultImage; } -NSData * _Nullable prepareSvgImage(NSData * _Nonnull data, bool template) { - NSDate *startTime = [NSDate date]; +void processShape(NSVGshape *shape, CGContextCoder *context, bool template) { + if (shape->fill.type != NSVG_PAINT_NONE) { + if (template) { + [context setFillColorWithOpacity:shape->opacity]; + } else { + [context setFillColor:shape->fill.color opacity:shape->opacity]; + } + + [context beginPath]; + BOOL hasStartPoint = false; + CGPoint startPoint = CGPointZero; + + for (NSVGpath *path = shape->paths; path; path = path->next) { + if (!hasStartPoint) { + hasStartPoint = true; + startPoint = CGPointMake(path->pts[0], path->pts[1]); + } + + [context moveToPoint:CGPointMake(path->pts[0], path->pts[1])]; + + for (int i = 0; i < path->npts - 1; i += 3) { + float *p = &path->pts[i * 2]; + [context addCurveToPoint:CGPointMake(p[2], p[3]) + p2:CGPointMake(p[4], p[5]) + p3:CGPointMake(p[6], p[7])]; + } + + if (path->closed && hasStartPoint) { + [context addLineToPoint:startPoint]; + hasStartPoint = NO; + } + } + + switch (shape->fillRule) { + case NSVG_FILLRULE_EVENODD: + [context eoFillPath]; + break; + default: + [context fillPath]; + break; + } + } + + if (shape->stroke.type != NSVG_PAINT_NONE && shape->strokeWidth > 0) { + CGLineCap lineCap = kCGLineCapButt; + CGLineJoin lineJoin = kCGLineJoinMiter; + + switch (shape->strokeLineCap) { + case NSVG_CAP_ROUND: lineCap = kCGLineCapRound; break; + case NSVG_CAP_SQUARE: lineCap = kCGLineCapSquare; break; + default: break; + } + + switch (shape->strokeLineJoin) { + case NSVG_JOIN_BEVEL: lineJoin = kCGLineJoinBevel; break; + case NSVG_JOIN_ROUND: lineJoin = kCGLineJoinRound; break; + default: break; + } + + [context setupStrokeOpacity:shape->opacity + miterLimit:shape->miterLimit + lineWidth:shape->strokeWidth + lineCap:lineCap + lineJoin:lineJoin]; + + for (NSVGpath *path = shape->paths; path; path = path->next) { + [context beginPath]; + [context moveToPoint:CGPointMake(path->pts[0], path->pts[1])]; + + for (int i = 0; i < path->npts - 1; i += 3) { + float *p = &path->pts[i * 2]; + [context addCurveToPoint:CGPointMake(p[2], p[3]) + p2:CGPointMake(p[4], p[5]) + p3:CGPointMake(p[6], p[7])]; + } + + if (path->closed) { + [context closePath]; + } + [context strokePath]; + } + } +} + +NSData * _Nullable prepareSvgImage(NSData * _Nonnull data, BOOL template) { + if (!data || data.length == 0) return nil; + + CFTimeInterval startTime = CACurrentMediaTime(); NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data]; - if (parser == nil) { - return nil; - } + if (!parser) return nil; + SvgXMLParsingDelegate *delegate = [[SvgXMLParsingDelegate alloc] init]; parser.delegate = delegate; - [parser parse]; + if (![parser parse]) return nil; NSMutableString *xmlString = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - if (xmlString == nil) { - return nil; - } + if (!xmlString) return nil; for (NSString *styleName in delegate.styles) { NSString *styleValue = delegate.styles[styleName]; - [xmlString replaceOccurrencesOfString:[NSString stringWithFormat:@"class=\"%@\"", styleName] withString:[NSString stringWithFormat:@"style=\"%@\"", styleValue] options:0 range:NSMakeRange(0, xmlString.length)]; + NSString *searchPattern = [NSString stringWithFormat:@"class=\"%@\"", styleName]; + NSString *replacement = [NSString stringWithFormat:@"style=\"%@\"", styleValue]; + [xmlString replaceOccurrencesOfString:searchPattern withString:replacement + options:NSLiteralSearch range:NSMakeRange(0, xmlString.length)]; } - const char *zeroTerminatedData = xmlString.UTF8String; + { + NSError *err = nil; + NSRegularExpression *gx = [NSRegularExpression regularExpressionWithPattern:@"]*\\bid\\s*=\\s*[\"']GiftPatterns[\"'][^>]*>[\\s\\S]*?" options:NSRegularExpressionCaseInsensitive error:&err]; + if (gx) { + xmlString = [[gx stringByReplacingMatchesInString:xmlString options:0 range:NSMakeRange(0, xmlString.length) withTemplate:@""] mutableCopy]; + } + } - NSVGimage *image = nsvgParse((char *)zeroTerminatedData, "px", 96); - if (image == nil || image->width < 1.0f || image->height < 1.0f) { + const char *svgString = xmlString.UTF8String; + NSVGimage *image = nsvgParse((char *)svgString, "px", 96); + if (!image || image->width < 1.0f || image->height < 1.0f) { + if (image) nsvgDelete(image); return nil; } - double deltaTime = -1.0f * [startTime timeIntervalSinceNow]; - printf("parseTime = %f\n", deltaTime); + CFTimeInterval parseTime = CACurrentMediaTime() - startTime; + NSLog(@"Parse time: %.4f seconds", parseTime); - startTime = [NSDate date]; - + startTime = CACurrentMediaTime(); CGContextCoder *context = [[CGContextCoder alloc] initWithSize:CGSizeMake(image->width, image->height)]; - - for (NSVGshape *shape = image->shapes; shape != NULL; shape = shape->next) { - if (!(shape->flags & NSVG_FLAGS_VISIBLE)) { - continue; - } + + for (NSVGshape *shape = image->shapes; shape; shape = shape->next) { + if (!(shape->flags & NSVG_FLAGS_VISIBLE) || shape->opacity <= 0) continue; - if (shape->fill.type != NSVG_PAINT_NONE) { - if (template) { - [context setFillColorWithOpacity:shape->opacity]; - } else { - [context setFillColor:shape->fill.color opacity:shape->opacity]; - } - - bool isFirst = true; - bool hasStartPoint = false; - CGPoint startPoint; - for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { - if (isFirst) { - [context beginPath]; - - isFirst = false; - hasStartPoint = true; - startPoint.x = path->pts[0]; - startPoint.y = path->pts[1]; - } - [context moveToPoint:CGPointMake(path->pts[0], path->pts[1])]; - for (int i = 0; i < path->npts - 1; i += 3) { - float *p = &path->pts[i * 2]; - [context addCurveToPoint:CGPointMake(p[2], p[3]) p2:CGPointMake(p[4], p[5]) p3:CGPointMake(p[6], p[7])]; - } - - if (path->closed) { - if (hasStartPoint) { - hasStartPoint = false; - [context addLineToPoint:startPoint]; - } - } - } - switch (shape->fillRule) { - case NSVG_FILLRULE_EVENODD: - [context eoFillPath]; - break; - default: - [context fillPath]; - break; - } - } - - if (shape->stroke.type != NSVG_PAINT_NONE) { - CGLineCap lineCap = kCGLineCapButt; - CGLineJoin lineJoin = kCGLineJoinMiter; - switch (shape->strokeLineCap) { - case NSVG_CAP_BUTT: - lineCap = kCGLineCapButt; - break; - case NSVG_CAP_ROUND: - lineCap = kCGLineCapRound; - break; - case NSVG_CAP_SQUARE: - lineCap = kCGLineCapSquare; - break; - default: - break; - } - switch (shape->strokeLineJoin) { - case NSVG_JOIN_BEVEL: - lineJoin = kCGLineJoinBevel; - break; - case NSVG_JOIN_MITER: - lineJoin = kCGLineJoinMiter; - break; - case NSVG_JOIN_ROUND: - lineJoin = kCGLineJoinRound; - break; - default: - break; - } - - [context setupStrokeOpacity:shape->opacity mitterLimit:shape->miterLimit lineWidth:shape->strokeWidth lineCap:lineCap lineJoin:lineJoin]; - - for (NSVGpath *path = shape->paths; path != NULL; path = path->next) { - [context beginPath]; - [context moveToPoint:CGPointMake(path->pts[0], path->pts[1])]; - for (int i = 0; i < path->npts - 1; i += 3) { - float *p = &path->pts[i * 2]; - [context addCurveToPoint:CGPointMake(p[2], p[3]) p2:CGPointMake(p[4], p[5]) p3:CGPointMake(p[6], p[7])]; - } - - if (path->closed) { - [context closePath]; - } - [context strokePath]; - } - } + processShape(shape, context, template); } nsvgDelete(image); + + [context storeGiftPatternRects:delegate.giftRects]; + + CFTimeInterval prepTime = CACurrentMediaTime() - startTime; + NSLog(@"Preparation time: %.4f seconds", prepTime); + return context.data; } diff --git a/submodules/TelegramCore/Sources/State/Serialization.swift b/submodules/TelegramCore/Sources/State/Serialization.swift index 51d3094bf3..1de180df61 100644 --- a/submodules/TelegramCore/Sources/State/Serialization.swift +++ b/submodules/TelegramCore/Sources/State/Serialization.swift @@ -210,7 +210,7 @@ public class BoxedMessage: NSObject { public class Serialization: NSObject, MTSerialization { public func currentLayer() -> UInt { - return 213 + return 214 } public func parseMessage(_ data: Data!) -> Any! { diff --git a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramWallpaper.swift b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramWallpaper.swift index 0872978f07..b96ac65480 100644 --- a/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramWallpaper.swift +++ b/submodules/TelegramCore/Sources/SyncCore/SyncCore_TelegramWallpaper.swift @@ -230,6 +230,37 @@ public enum TelegramWallpaper: Equatable { self.file = file self.settings = settings } + + public static func ==(lhs: File, rhs: File) -> Bool { + if lhs.id != rhs.id { + return false + } + if lhs.accessHash != rhs.accessHash { + return false + } + if lhs.isCreator != rhs.isCreator { + return false + } + if lhs.isDefault != rhs.isDefault { + return false + } + if lhs.isPattern != rhs.isPattern { + return false + } + if lhs.isDark != rhs.isDark { + return false + } + if lhs.slug != rhs.slug { + return false + } + if lhs.file.fileId != rhs.file.fileId { + return false + } + if lhs.settings != rhs.settings { + return false + } + return true + } } case builtin(WallpaperSettings) diff --git a/submodules/TelegramPresentationData/Sources/MakePresentationTheme.swift b/submodules/TelegramPresentationData/Sources/MakePresentationTheme.swift index 0698eab825..360bbd44b3 100644 --- a/submodules/TelegramPresentationData/Sources/MakePresentationTheme.swift +++ b/submodules/TelegramPresentationData/Sources/MakePresentationTheme.swift @@ -47,13 +47,36 @@ public func makePresentationTheme(cloudTheme: TelegramTheme, dark: Bool = false) } else { settings = nil } - guard let settings = settings else { + guard let settings else { return nil } let defaultTheme = makeDefaultPresentationTheme(reference: PresentationBuiltinThemeReference(baseTheme: settings.baseTheme), extendingThemeReference: .cloud(PresentationCloudTheme(theme: cloudTheme, resolvedWallpaper: nil, creatorAccountId: nil)), serviceBackgroundColor: nil, preview: false) return customizePresentationTheme(defaultTheme, editing: true, accentColor: UIColor(argb: settings.accentColor), outgoingAccentColor: settings.outgoingAccentColor.flatMap { UIColor(argb: $0) }, backgroundColors: [], bubbleColors: settings.messageColors, animateBubbleColors: settings.animateMessageColors, wallpaper: settings.wallpaper) } +public func makePresentationTheme(chatTheme: ChatTheme, dark: Bool = false) -> PresentationTheme? { + guard case let .gift(_, themeSettings) = chatTheme else { + return nil + } + let settings: TelegramThemeSettings? + if let exactSettings = themeSettings.first(where: { dark ? ($0.baseTheme == .night || $0.baseTheme == .tinted) : ($0.baseTheme == .classic || $0.baseTheme == .day) }) { + settings = exactSettings + } else if let firstSettings = themeSettings.first { + settings = firstSettings + } else { + settings = nil + } + guard let settings else { + return nil + } + let defaultTheme = makeDefaultPresentationTheme(reference: PresentationBuiltinThemeReference(baseTheme: settings.baseTheme), serviceBackgroundColor: nil, preview: false) + let theme = customizePresentationTheme(defaultTheme, editing: true, accentColor: UIColor(rgb: settings.accentColor), outgoingAccentColor: settings.outgoingAccentColor.flatMap { UIColor(rgb: $0) }, backgroundColors: [], bubbleColors: settings.messageColors, animateBubbleColors: settings.animateMessageColors, wallpaper: settings.wallpaper) + if case let .gift(starGiftValue, _) = chatTheme { + theme.starGift = starGiftValue + } + return theme +} + public func makePresentationTheme(cloudTheme: TelegramTheme, baseTheme: TelegramBaseTheme? = nil) -> PresentationTheme? { let settings: TelegramThemeSettings? if let exactSettings = cloudTheme.settings?.first(where: { $0.baseTheme == baseTheme }) { diff --git a/submodules/TelegramPresentationData/Sources/PresentationTheme.swift b/submodules/TelegramPresentationData/Sources/PresentationTheme.swift index 2f71522c77..f7cdcc3d64 100644 --- a/submodules/TelegramPresentationData/Sources/PresentationTheme.swift +++ b/submodules/TelegramPresentationData/Sources/PresentationTheme.swift @@ -1574,6 +1574,7 @@ public final class PresentationTheme: Equatable { public let chart: PresentationThemeChart public let preview: Bool public var forceSync: Bool = false + public var starGift: StarGift? public let resourceCache: PresentationsResourceCache = PresentationsResourceCache() diff --git a/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift b/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift index 32f5110a72..2e3f36e6dc 100644 --- a/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift +++ b/submodules/TelegramStringFormatting/Sources/ServiceMessageStrings.swift @@ -781,12 +781,15 @@ public func universalServiceMessageString(presentationData: (PresentationTheme, } else { var emoji = "" var additionalAttributes: [String: Any] = [:] + var giftTitle: String? switch chatTheme { case let .emoticon(emoticon): emoji = emoticon case let .gift(starGift, _): var file: TelegramMediaFile? + if case let .unique(uniqueGift) = starGift { + giftTitle = "\(uniqueGift.title) #\(formatCollectibleNumber(uniqueGift.number, dateTimeFormat: dateTimeFormat))" for attribute in uniqueGift.attributes { if case let .model(_, fileValue, _) = attribute { file = fileValue @@ -802,11 +805,21 @@ public func universalServiceMessageString(presentationData: (PresentationTheme, if message.author?.id.namespace == Namespaces.Peer.CloudChannel { attributedString = NSAttributedString(string: strings.Notification_ChannelChangedTheme(emoji).string, font: titleFont, textColor: primaryTextColor) } else if message.author?.id == accountPeerId { - let resultTitleString = strings.Notification_YouChangedTheme(emoji) - attributedString = addAttributesToStringWithRanges(resultTitleString._tuple, body: bodyAttributes, argumentAttributes: [0: emojiAttributes]) + if let giftTitle { + let resultTitleString = strings.Notification_YouChangedThemeGift(giftTitle) + attributedString = addAttributesToStringWithRanges(resultTitleString._tuple, body: bodyAttributes, argumentAttributes: [:]) + } else { + let resultTitleString = strings.Notification_YouChangedTheme(emoji) + attributedString = addAttributesToStringWithRanges(resultTitleString._tuple, body: bodyAttributes, argumentAttributes: [0: emojiAttributes]) + } } else { - let resultTitleString = strings.Notification_ChangedTheme(compactAuthorName, emoji) - attributedString = addAttributesToStringWithRanges(resultTitleString._tuple, body: bodyAttributes, argumentAttributes: [0: boldAttributes, 1: emojiAttributes]) + if let giftTitle { + let resultTitleString = strings.Notification_ChangedThemeGift(compactAuthorName, giftTitle) + attributedString = addAttributesToStringWithRanges(resultTitleString._tuple, body: bodyAttributes, argumentAttributes: [0: boldAttributes, 1: boldAttributes]) + } else { + let resultTitleString = strings.Notification_ChangedTheme(compactAuthorName, emoji) + attributedString = addAttributesToStringWithRanges(resultTitleString._tuple, body: bodyAttributes, argumentAttributes: [0: boldAttributes, 1: emojiAttributes]) + } } } case let .webViewData(text): diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift index 482cc2b1a3..57dcfda475 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageBubbleItemNode/Sources/ChatMessageBubbleItemNode.swift @@ -241,6 +241,8 @@ private func contentNodeMessagesAndClassesForItem(_ item: ChatMessageItem) -> ([ } else if case .joinedChannel = action.action { result.append((message, ChatMessageJoinedChannelBubbleContentNode.self, itemAttributes, BubbleItemAttributes(isAttachment: false, neighborType: .text, neighborSpacing: .default))) needReactions = false + } else if case let .setChatTheme(chatTheme) = action.action, case .gift = chatTheme { + result.append((message, ChatMessageGiftBubbleContentNode.self, itemAttributes, BubbleItemAttributes(isAttachment: false, neighborType: .text, neighborSpacing: .default))) } else { if !canAddMessageReactions(message: message) { needReactions = false diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/BUILD b/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/BUILD index b5039cdd81..81bce800e8 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/BUILD +++ b/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/BUILD @@ -33,6 +33,7 @@ swift_library( "//submodules/TelegramUI/Components/TextNodeWithEntities", "//submodules/InvisibleInkDustNode", "//submodules/TelegramUI/Components/PeerInfo/PeerInfoCoverComponent", + "//submodules/TelegramUI/Components/Gifts/GiftItemComponent", ], visibility = [ "//visibility:public", diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift index 228acde43e..728d37a4be 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageGiftBubbleContentNode/Sources/ChatMessageGiftBubbleContentNode.swift @@ -24,6 +24,7 @@ import ChatMessageItemCommon import TextNodeWithEntities import InvisibleInkDustNode import PeerInfoCoverComponent +import GiftItemComponent private func attributedServiceMessageString(theme: ChatPresentationThemeData, strings: PresentationStrings, nameDisplayOrder: PresentationPersonNameOrder, dateTimeFormat: PresentationDateTimeFormat, message: EngineMessage, accountPeerId: EnginePeer.Id) -> NSAttributedString? { return universalServiceMessageString(presentationData: (theme.theme, theme.wallpaper), strings: strings, nameDisplayOrder: nameDisplayOrder, dateTimeFormat: dateTimeFormat, message: message, accountPeerId: accountPeerId, forChatList: false, forForumOverview: false, forAdditionalServiceMessage: true) @@ -45,6 +46,7 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { private var dustNode: InvisibleInkDustNode? private let placeholderNode: StickerShimmerEffectNode private let animationNode: AnimatedStickerNode + private let giftIcon = ComponentView() private let modelTitleTextNode: TextNode private let modelValueTextNode: TextNode @@ -416,6 +418,7 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { var months: Int32 = 3 var animationName: String = "" var animationFile: TelegramMediaFile? + var uniqueGift: StarGift.UniqueGift? var title = item.presentationData.strings.Notification_PremiumGift_Title var text = "" var subtitleColor = primaryTextColor @@ -708,6 +711,20 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { text = item.presentationData.strings.Notification_StarGift_Subtitle_Refunded animationFile = gift.file } + case let .setChatTheme(chatTheme): + title = "" + var giftTitle = "" + if case let .gift(gift, _) = chatTheme, case let .unique(uniqueGiftValue) = gift { + giftTitle = "\(uniqueGiftValue.title) #\(formatCollectibleNumber(uniqueGiftValue.number, dateTimeFormat: item.presentationData.dateTimeFormat))" + uniqueGift = uniqueGiftValue + } + if incoming { + let authorName = item.message.author.flatMap { EnginePeer($0) }?.compactDisplayTitle ?? "" + text = item.presentationData.strings.Notification_ChatTheme_Text(authorName, giftTitle).string + } else { + text = item.presentationData.strings.Notification_ChatTheme_TextYou(giftTitle).string + } + hasServiceMessage = false default: break } @@ -866,6 +883,10 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { giftSize.height += 12.0 } + if let _ = uniqueGift { + giftSize.height -= 31.0 + } + var labelRects = labelLayout.linesRects() if labelRects.count > 1 { let sortedIndices = (0 ..< labelRects.count).sorted(by: { labelRects[$0].width > labelRects[$1].width }) @@ -944,7 +965,7 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { strongSelf.creatorButtonNode.isUserInteractionEnabled = !item.presentationData.isPreview strongSelf.creatorButtonTitleNode.isHidden = creatorButtonTitle.isEmpty - if strongSelf.item == nil && !isStoryEntity { + if strongSelf.item == nil && !isStoryEntity && uniqueGift == nil { strongSelf.animationNode.started = { [weak self] in if let strongSelf = self { let current = CACurrentMediaTime() @@ -1009,7 +1030,10 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { let titleFrame = CGRect(origin: CGPoint(x: mediaBackgroundFrame.minX + floorToScreenPixels((mediaBackgroundFrame.width - titleLayout.size.width) / 2.0) , y: mediaBackgroundFrame.minY + 151.0), size: titleLayout.size) strongSelf.titleNode.frame = titleFrame - let clippingTextFrame = CGRect(origin: CGPoint(x: mediaBackgroundFrame.minX + floorToScreenPixels((mediaBackgroundFrame.width - subtitleLayout.size.width) / 2.0), y: titleFrame.maxY + textSpacing), size: CGSize(width: subtitleLayout.size.width, height: clippedTextHeight)) + var clippingTextFrame = CGRect(origin: CGPoint(x: mediaBackgroundFrame.minX + floorToScreenPixels((mediaBackgroundFrame.width - subtitleLayout.size.width) / 2.0), y: titleFrame.maxY + textSpacing), size: CGSize(width: subtitleLayout.size.width, height: clippedTextHeight)) + if let _ = uniqueGift { + clippingTextFrame.origin.y -= 23.0 + } var attributesOffsetY: CGFloat = 0.0 @@ -1315,6 +1339,31 @@ public class ChatMessageGiftBubbleContentNode: ChatMessageBubbleContentNode { } } + if let uniqueGift { + let iconSize = CGSize(width: 94.0, height: 94.0) + let _ = strongSelf.giftIcon.update( + transition: .immediate, + component: AnyComponent(GiftItemComponent( + context: item.context, + theme: item.presentationData.theme.theme, + strings: item.presentationData.strings, + peer: nil, + subject: .uniqueGift(gift: uniqueGift, price: nil), + mode: .thumbnail + )), + environment: {}, + containerSize: iconSize + ) + if let giftIconView = strongSelf.giftIcon.view { + if giftIconView.superview == nil { + // backgroundView.layer.cornerRadius = 20.0 + //backgroundView.clipsToBounds = true + strongSelf.view.addSubview(giftIconView) + } + giftIconView.frame = CGRect(origin: CGPoint(x: mediaBackgroundFrame.minX + floorToScreenPixels((mediaBackgroundFrame.width - iconSize.width) / 2.0), y: mediaBackgroundFrame.minY + 17.0), size: iconSize) + } + } + let baseBackgroundFrame = labelFrame.offsetBy(dx: 0.0, dy: -11.0) if let (offset, image) = backgroundMaskImage { if strongSelf.backgroundNode == nil { diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift index ef67f9f5ec..37ae63c442 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageInteractiveMediaNode/Sources/ChatMessageInteractiveMediaNode.swift @@ -1656,7 +1656,7 @@ public final class ChatMessageInteractiveMediaNode: ASDisplayNode, GalleryItemTr return patternWallpaperImage(account: context.account, accountManager: context.sharedContext.accountManager, representations: representations, mode: .screen) |> mapToSignal { value -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> in if let value = value { - return .single(value) + return .single(value.generator) } else { return .complete() } diff --git a/submodules/TelegramUI/Components/Chat/ChatMessageWallpaperBubbleContentNode/Sources/ChatMessageWallpaperBubbleContentNode.swift b/submodules/TelegramUI/Components/Chat/ChatMessageWallpaperBubbleContentNode/Sources/ChatMessageWallpaperBubbleContentNode.swift index 290a9c7f39..ec9e6380ea 100644 --- a/submodules/TelegramUI/Components/Chat/ChatMessageWallpaperBubbleContentNode/Sources/ChatMessageWallpaperBubbleContentNode.swift +++ b/submodules/TelegramUI/Components/Chat/ChatMessageWallpaperBubbleContentNode/Sources/ChatMessageWallpaperBubbleContentNode.swift @@ -387,7 +387,7 @@ public class ChatMessageWallpaperBubbleContentNode: ChatMessageBubbleContentNode updateImageSignal = patternWallpaperImage(account: item.context.account, accountManager: item.context.sharedContext.accountManager, representations: representations, mode: .thumbnail) |> mapToSignal { value -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> in if let value { - return .single(value) + return .single(value.generator) } else { return .complete() } diff --git a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift index 80e9d9241e..422cb574c2 100644 --- a/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift +++ b/submodules/TelegramUI/Components/Gifts/GiftViewScreen/Sources/GiftViewScreen.swift @@ -3658,7 +3658,12 @@ private final class GiftViewSheetContent: CombinedComponent { } } - if ((incoming && !converted && !upgraded) || exported || selling) && (!showUpgradePreview && !showWearPreview) { + + var isChatTheme = false + if let controller = controller() as? GiftViewScreen, controller.openChatTheme != nil { + isChatTheme = true + } + if ((incoming && !converted && !upgraded) || exported || selling || isChatTheme) && (!showUpgradePreview && !showWearPreview) { let textFont = Font.regular(13.0) let textColor = theme.list.itemSecondaryTextColor let linkColor = theme.actionSheet.controlAccentColor @@ -3672,7 +3677,9 @@ private final class GiftViewSheetContent: CombinedComponent { var addressToOpen: String? var descriptionText: String - if let uniqueGift, selling { + if isChatTheme { + descriptionText = strings.Gift_View_OpenChatTheme + } else if let uniqueGift, selling { let ownerName: String if case let .peerId(peerId) = uniqueGift.owner { ownerName = state.peerMap[peerId]?.compactDisplayTitle ?? "" @@ -3731,7 +3738,10 @@ private final class GiftViewSheetContent: CombinedComponent { }, tapAction: { [weak state] attributes, _ in if let _ = attributes[NSAttributedString.Key(rawValue: TelegramTextAttributes.URL)] as? String { - if let addressToOpen { + if isChatTheme, let controller = controller() as? GiftViewScreen { + state?.dismiss(animated: true) + controller.openChatTheme?() + } else if let addressToOpen { state?.openAddress(addressToOpen) } else { state?.updateSavedToProfile(!savedToProfile) @@ -4381,6 +4391,7 @@ public class GiftViewScreen: ViewControllerComponentContainer { fileprivate let updateResellStars: ((CurrencyAmount?) -> Signal)? fileprivate let togglePinnedToTop: ((Bool) -> Bool)? fileprivate let shareStory: ((StarGift.UniqueGift) -> Void)? + fileprivate let openChatTheme: (() -> Void)? public var disposed: () -> Void = {} @@ -4397,7 +4408,8 @@ public class GiftViewScreen: ViewControllerComponentContainer { buyGift: ((String, EnginePeer.Id, CurrencyAmount?) -> Signal)? = nil, updateResellStars: ((CurrencyAmount?) -> Signal)? = nil, togglePinnedToTop: ((Bool) -> Bool)? = nil, - shareStory: ((StarGift.UniqueGift) -> Void)? = nil + shareStory: ((StarGift.UniqueGift) -> Void)? = nil, + openChatTheme: (() -> Void)? = nil ) { self.context = context self.subject = subject @@ -4410,6 +4422,7 @@ public class GiftViewScreen: ViewControllerComponentContainer { self.updateResellStars = updateResellStars self.togglePinnedToTop = togglePinnedToTop self.shareStory = shareStory + self.openChatTheme = openChatTheme if case let .unique(gift) = subject.arguments?.gift, gift.resellForTonOnly { self.balanceCurrency = .ton diff --git a/submodules/TelegramUI/Components/Settings/SettingsThemeWallpaperNode/Sources/SettingsThemeWallpaperNode.swift b/submodules/TelegramUI/Components/Settings/SettingsThemeWallpaperNode/Sources/SettingsThemeWallpaperNode.swift index 3e9a18b768..6af509eee1 100644 --- a/submodules/TelegramUI/Components/Settings/SettingsThemeWallpaperNode/Sources/SettingsThemeWallpaperNode.swift +++ b/submodules/TelegramUI/Components/Settings/SettingsThemeWallpaperNode/Sources/SettingsThemeWallpaperNode.swift @@ -273,9 +273,9 @@ public final class SettingsThemeWallpaperNode: ASDisplayNode { self.arguments = PatternWallpaperArguments(colors: [.clear], rotation: nil, customPatternColor: isLight ? .black : .white) } imageSignal = patternWallpaperImage(account: context.account, accountManager: context.sharedContext.accountManager, representations: convertedRepresentations, mode: .thumbnail, autoFetchFullSize: true) - |> mapToSignal { value -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> in - if let value = value { - return .single(value) + |> mapToSignal { generatorAndRects -> Signal<(TransformImageArguments) -> DrawingContext?, NoError> in + if let (generator, _) = generatorAndRects { + return .single(generator) } else { return .complete() } diff --git a/submodules/TelegramUI/Sources/Chat/ChatControllerThemeManagement.swift b/submodules/TelegramUI/Sources/Chat/ChatControllerThemeManagement.swift index 4d9aa139cf..921c93180e 100644 --- a/submodules/TelegramUI/Sources/Chat/ChatControllerThemeManagement.swift +++ b/submodules/TelegramUI/Sources/Chat/ChatControllerThemeManagement.swift @@ -182,7 +182,7 @@ extension ChatControllerImpl { previewTheme: { [weak self] chatTheme, dark in if let strongSelf = self { strongSelf.presentCrossfadeSnapshot() - strongSelf.chatThemeAndDarkAppearancePreviewPromise.set(.single((chatTheme ?? .emoticon(""), dark))) + strongSelf.chatThemeAndDarkAppearancePreviewPromise.set(.single((chatTheme, dark))) } }, changeWallpaper: { [weak self] in diff --git a/submodules/TelegramUI/Sources/ChatController.swift b/submodules/TelegramUI/Sources/ChatController.swift index a6353274f4..e02763bd13 100644 --- a/submodules/TelegramUI/Sources/ChatController.swift +++ b/submodules/TelegramUI/Sources/ChatController.swift @@ -1110,8 +1110,29 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G self.present(BotReceiptController(context: self.context, messageId: message.id), in: .window(.root), with: ViewControllerPresentationArguments(presentationAnimation: .modalSheet)) } return true - case .setChatTheme: - self.presentThemeSelection() + case let .setChatTheme(chatTheme): + switch chatTheme { + case .emoticon: + self.presentThemeSelection() + case let .gift(gift, _): + if case let .unique(uniqueGift) = gift { + let controller = self.context.sharedContext.makeGiftViewScreen(context: self.context, gift: uniqueGift, shareStory: { [weak self] uniqueGift in + Queue.mainQueue().after(0.15) { + if let self { + let controller = self.context.sharedContext.makeStorySharingScreen(context: self.context, subject: .gift(uniqueGift), parentController: self) + self.push(controller) + } + } + }, openChatTheme: { [weak self] in + if let self { + Queue.mainQueue().after(0.15) { + self.presentThemeSelection() + } + } + }, dismissed: nil) + self.push(controller) + } + } return true case let .setChatWallpaper(wallpaper, _): guard let peer = self.presentationInterfaceState.renderedPeer?.peer else { @@ -5808,10 +5829,15 @@ public final class ChatControllerImpl: TelegramBaseController, ChatController, G }) } } - case let .gift(gift, wallpaper): - let _ = gift - let _ = wallpaper - //TODO:release + case .gift: + if let theme = makePresentationTheme(chatTheme: chatTheme, dark: useDarkAppearance) { + theme.forceSync = true + presentationData = presentationData.withUpdated(theme: theme).withUpdated(chatWallpaper: theme.chat.defaultWallpaper) + + Queue.mainQueue().after(1.0, { + theme.forceSync = false + }) + } } } else if let darkAppearancePreview = darkAppearancePreview { useDarkAppearance = darkAppearancePreview diff --git a/submodules/TelegramUI/Sources/ChatControllerNode.swift b/submodules/TelegramUI/Sources/ChatControllerNode.swift index bcd4b9a5a6..8852a916e9 100644 --- a/submodules/TelegramUI/Sources/ChatControllerNode.swift +++ b/submodules/TelegramUI/Sources/ChatControllerNode.swift @@ -3582,7 +3582,7 @@ class ChatControllerNode: ASDisplayNode, ASScrollViewDelegate { let themeUpdated = presentationReadyUpdated || (self.chatPresentationInterfaceState.theme !== chatPresentationInterfaceState.theme) - self.backgroundNode.update(wallpaper: chatPresentationInterfaceState.chatWallpaper, animated: true) + self.backgroundNode.update(wallpaper: chatPresentationInterfaceState.chatWallpaper, starGift: chatPresentationInterfaceState.theme.starGift, animated: true) self.historyNode.verticalScrollIndicatorColor = UIColor(white: 0.5, alpha: 0.8) if self.pendingSwitchToChatLocation == nil { diff --git a/submodules/TelegramUI/Sources/ChatThemeScreen.swift b/submodules/TelegramUI/Sources/ChatThemeScreen.swift index 67c96af618..7f7107b815 100644 --- a/submodules/TelegramUI/Sources/ChatThemeScreen.swift +++ b/submodules/TelegramUI/Sources/ChatThemeScreen.swift @@ -743,6 +743,7 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega private var initialized = false private let uniqueGiftChatThemesContext: UniqueGiftChatThemesContext + private var currentUniqueGiftChatThemesState: UniqueGiftChatThemesContext.State? private let peerName: String @@ -891,10 +892,12 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega self.uniqueGiftChatThemesContext.state, self.selectedThemePromise.get(), self.isDarkAppearancePromise.get() - ).startStrict(next: { [weak self] themes, uniqueGiftChatThemes, selectedTheme, isDarkAppearance in + ).startStrict(next: { [weak self] themes, uniqueGiftChatThemesState, selectedTheme, isDarkAppearance in guard let strongSelf = self else { return } + + strongSelf.currentUniqueGiftChatThemesState = uniqueGiftChatThemesState let isFirstTime = strongSelf.entries == nil let presentationData = strongSelf.presentationData @@ -927,8 +930,8 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega wallpaper: nil )) } - for theme in uniqueGiftChatThemes.themes { - guard case let .gift(gift, wallpaperFile) = theme else { + for theme in uniqueGiftChatThemesState.themes { + guard case let .gift(gift, themeSettings) = theme else { continue } var emojiFile: TelegramMediaFile? @@ -939,16 +942,23 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega } } } + + var wallpaper: TelegramWallpaper? + if isDarkAppearance { + wallpaper = themeSettings.first(where: { $0.baseTheme == .night || $0.baseTheme == .tinted })?.wallpaper + } else { + wallpaper = themeSettings.first(where: { $0.baseTheme == .classic || $0.baseTheme == .day })?.wallpaper + } entries.append(ThemeSettingsThemeEntry( index: entries.count, chatTheme: theme, emojiFile: emojiFile, - themeReference: nil, + themeReference: .builtin(.dayClassic), nightMode: isDarkAppearance, selected: selectedTheme?.id == theme.id, theme: presentationData.theme, strings: presentationData.strings, - wallpaper: .file(TelegramWallpaper.File(id: wallpaperFile.fileId.id, accessHash: 0, isCreator: false, isDefault: false, isPattern: true, isDark: false, slug: "", file: wallpaperFile, settings: WallpaperSettings(blur: false, motion: false, colors: [], intensity: 100, rotation: 0))) + wallpaper: wallpaper )) } @@ -1008,6 +1018,15 @@ private class ChatThemeScreenNode: ViewControllerTracingNode, ASScrollViewDelega } } + self.listNode.visibleBottomContentOffsetChanged = { [weak self] offset in + guard let self, let state = self.currentUniqueGiftChatThemesState, case .ready(true) = state.dataState else { + return + } + if case let .known(value) = offset, value < 100.0 { + self.uniqueGiftChatThemesContext.loadMore() + } + } + self.updateCancelButton() } diff --git a/submodules/TelegramUI/Sources/OpenResolvedUrl.swift b/submodules/TelegramUI/Sources/OpenResolvedUrl.swift index faa42dd134..ae30ec10c5 100644 --- a/submodules/TelegramUI/Sources/OpenResolvedUrl.swift +++ b/submodules/TelegramUI/Sources/OpenResolvedUrl.swift @@ -1481,7 +1481,7 @@ func openResolvedUrlImpl( navigationController?.pushViewController(controller) } } - }, dismissed: { + }, openChatTheme: nil, dismissed: { dismissedImpl?() }) navigationController?.pushViewController(controller) diff --git a/submodules/TelegramUI/Sources/SharedAccountContext.swift b/submodules/TelegramUI/Sources/SharedAccountContext.swift index 693d64930e..59b425118f 100644 --- a/submodules/TelegramUI/Sources/SharedAccountContext.swift +++ b/submodules/TelegramUI/Sources/SharedAccountContext.swift @@ -3768,8 +3768,8 @@ public final class SharedAccountContextImpl: SharedAccountContext { return GiftViewScreen(context: context, subject: .message(message), shareStory: shareStory) } - public func makeGiftViewScreen(context: AccountContext, gift: StarGift.UniqueGift, shareStory: ((StarGift.UniqueGift) -> Void)?, dismissed: (() -> Void)?) -> ViewController { - let controller = GiftViewScreen(context: context, subject: .uniqueGift(gift, nil), shareStory: shareStory) + public func makeGiftViewScreen(context: AccountContext, gift: StarGift.UniqueGift, shareStory: ((StarGift.UniqueGift) -> Void)?, openChatTheme: (() -> Void)?, dismissed: (() -> Void)?) -> ViewController { + let controller = GiftViewScreen(context: context, subject: .uniqueGift(gift, nil), shareStory: shareStory, openChatTheme: openChatTheme) controller.disposed = { dismissed?() } diff --git a/submodules/WallpaperBackgroundNode/Sources/MetalWallpaperBackgroundNode.swift b/submodules/WallpaperBackgroundNode/Sources/MetalWallpaperBackgroundNode.swift deleted file mode 100644 index 8b13789179..0000000000 --- a/submodules/WallpaperBackgroundNode/Sources/MetalWallpaperBackgroundNode.swift +++ /dev/null @@ -1 +0,0 @@ - diff --git a/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift b/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift index 0e69daa3c4..0010790b54 100644 --- a/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift +++ b/submodules/WallpaperBackgroundNode/Sources/WallpaperBackgroundNode.swift @@ -8,6 +8,7 @@ import TelegramCore import AccountContext import SwiftSignalKit import WallpaperResources +import StickerResources import FastBlur import Svg import GZip @@ -85,6 +86,7 @@ public protocol WallpaperBackgroundNode: ASDisplayNode { var rotation: CGFloat { get set } func update(wallpaper: TelegramWallpaper, animated: Bool) + func update(wallpaper: TelegramWallpaper, starGift: StarGift?, animated: Bool) func _internalUpdateIsSettingUpWallpaper() func updateLayout(size: CGSize, displayMode: WallpaperDisplayMode, transition: ContainedViewLayoutTransition) func updateIsLooping(_ isLooping: Bool) @@ -758,11 +760,20 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou private var validLayout: (CGSize, WallpaperDisplayMode)? private var wallpaper: TelegramWallpaper? + private var starGift: StarGift? + private var modelRectIndex: Int32? + + private var modelStickerNode: DefaultAnimatedStickerNodeImpl? + private var isSettingUpWallpaper: Bool = false private struct CachedValidPatternImage { let generate: (TransformImageArguments) -> DrawingContext? let generated: ValidPatternGeneratedImage + let rects: [WallpaperGiftPatternRect] + let starGift: StarGift? + let symbolImage: UIImage? + let modelRectIndex: Int32? let image: UIImage } @@ -771,6 +782,10 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou private struct ValidPatternImage { let wallpaper: TelegramWallpaper let invertPattern: Bool + let rects: [WallpaperGiftPatternRect] + let starGift: StarGift? + let symbolImage: UIImage? + let modelRectIndex: Int32? let generate: (TransformImageArguments) -> DrawingContext? } private var validPatternImage: ValidPatternImage? @@ -781,10 +796,38 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou let patternColor: UInt32 let backgroundColor: UInt32 let invertPattern: Bool + let starGift: StarGift? + let modelRectIndex: Int32? + + public static func ==(lhs: ValidPatternGeneratedImage, rhs: ValidPatternGeneratedImage) -> Bool { + if lhs.wallpaper != rhs.wallpaper { + return false + } + if lhs.size != rhs.size { + return false + } + if lhs.patternColor != rhs.patternColor { + return false + } + if lhs.backgroundColor != rhs.backgroundColor { + return false + } + if lhs.invertPattern != rhs.invertPattern { + return false + } + if lhs.starGift?.slug != rhs.starGift?.slug { + return false + } + if lhs.modelRectIndex != rhs.modelRectIndex { + return false + } + return true + } } private var validPatternGeneratedImage: ValidPatternGeneratedImage? private let patternImageDisposable = MetaDisposable() + private let symbolImageDisposable = MetaDisposable() private var bubbleTheme: PresentationTheme? private var bubbleCorners: PresentationChatBubbleCorners? @@ -930,11 +973,26 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou } public func update(wallpaper: TelegramWallpaper, animated: Bool) { - if self.wallpaper == wallpaper { + self.update(wallpaper: wallpaper, starGift: nil, animated: animated) + } + + public func update(wallpaper: TelegramWallpaper, starGift: StarGift?, animated: Bool) { + if self.wallpaper == wallpaper && self.starGift == starGift { return } let previousWallpaper = self.wallpaper + let previousStarGift = self.starGift + self.wallpaper = wallpaper + self.starGift = starGift + + if previousWallpaper != wallpaper || previousStarGift?.slug != starGift?.slug { + if let _ = starGift { + self.modelRectIndex = Int32.random(in: 0 ..< 10) + } else { + self.modelRectIndex = nil + } + } if let _ = previousWallpaper, animated { if let snapshotView = self.view.snapshotView(afterScreenUpdates: false) { @@ -1132,6 +1190,7 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou } default: self.patternImageDisposable.set(nil) + self.symbolImageDisposable.set(nil) self.validPatternImage = nil self.patternImageLayer.isHidden = true self.patternImageLayer.fillWithColorUntilLoaded = nil @@ -1146,6 +1205,9 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou guard let wallpaper = self.wallpaper else { return } + + let starGift = self.starGift + let modelRectIndex = self.modelRectIndex var invertPattern: Bool = false var patternIsLight: Bool = false @@ -1169,13 +1231,20 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou break } } + + if let previousStarGift = self.validPatternImage?.starGift, !updated { + updated = true + if previousStarGift.slug == starGift?.slug { + updated = false + } + } if updated { self.validPatternGeneratedImage = nil self.validPatternImage = nil - if let cachedValidPatternImage = WallpaperBackgroundNodeImpl.cachedValidPatternImage, cachedValidPatternImage.generated.wallpaper == wallpaper && cachedValidPatternImage.generated.invertPattern == invertPattern { - self.validPatternImage = ValidPatternImage(wallpaper: cachedValidPatternImage.generated.wallpaper, invertPattern: invertPattern, generate: cachedValidPatternImage.generate) + if let cachedValidPatternImage = WallpaperBackgroundNodeImpl.cachedValidPatternImage, cachedValidPatternImage.generated.wallpaper == wallpaper && cachedValidPatternImage.generated.invertPattern == invertPattern && cachedValidPatternImage.starGift == starGift && cachedValidPatternImage.modelRectIndex == modelRectIndex { + self.validPatternImage = ValidPatternImage(wallpaper: cachedValidPatternImage.generated.wallpaper, invertPattern: invertPattern, rects: cachedValidPatternImage.rects, starGift: cachedValidPatternImage.starGift, symbolImage: cachedValidPatternImage.symbolImage, modelRectIndex: cachedValidPatternImage.modelRectIndex, generate: cachedValidPatternImage.generate) } else { func reference(for resource: EngineMediaResource, media: EngineMedia) -> MediaResourceReference { return .wallpaper(wallpaper: .slug(file.slug), resource: resource._asResource()) @@ -1189,37 +1258,33 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou convertedRepresentations.append(ImageRepresentationWithReference(representation: .init(dimensions: dimensions, resource: file.file.resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false, isPersonal: false), reference: reference(for: EngineMediaResource(file.file.resource), media: EngineMedia(file.file)))) let signal = patternWallpaperImage(account: self.context.account, accountManager: self.context.sharedContext.accountManager, representations: convertedRepresentations, mode: .screen, autoFetchFullSize: true) - self.patternImageDisposable.set((signal - |> deliverOnMainQueue).start(next: { [weak self] generator in - guard let strongSelf = self else { + var symbolImage: Signal = .single(nil) + if let starGift = self.starGift, case let .unique(uniqueGift) = starGift { + for attribute in uniqueGift.attributes { + if case let .pattern(_, file, _) = attribute, let dimensions = file.dimensions { + let size = dimensions.cgSize.aspectFitted(CGSize(width: 160.0, height: 160.0)) + symbolImage = chatMessageAnimatedSticker(postbox: self.context.account.postbox, userLocation: .other, file: file, small: false, size: size) + |> map { generator -> UIImage? in + return generator(TransformImageArguments(corners: ImageCorners(), imageSize: size, boundingSize: size, intrinsicInsets: .zero))?.generateImage() + } + break + } + } + } + self.patternImageDisposable.set(combineLatest(queue: Queue.mainQueue(), signal, symbolImage).start(next: { [weak self] generator, symbolImage in + guard let self else { return } - - if let generator = generator { - /*generator = { arguments in - let scale = arguments.scale ?? UIScreenScale - let context = DrawingContext(size: arguments.drawingSize, scale: scale, clear: true) - - context.withFlippedContext { c in - if let path = getAppBundle().path(forResource: "PATTERN_static", ofType: "svg"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) { - if let image = drawSvgImage(data, CGSize(width: arguments.drawingSize.width * scale, height: arguments.drawingSize.height * scale), .clear, .black, false) { - c.draw(image.cgImage!, in: CGRect(origin: CGPoint(), size: arguments.drawingSize)) - } - } - } - - return context - }*/ - - strongSelf.validPatternImage = ValidPatternImage(wallpaper: wallpaper, invertPattern: invertPattern, generate: generator) - strongSelf.validPatternGeneratedImage = nil - if let (size, displayMode) = strongSelf.validLayout { - strongSelf.loadPatternForSizeIfNeeded(size: size, displayMode: displayMode, transition: .immediate) + if let (generator, rects) = generator { + self.validPatternImage = ValidPatternImage(wallpaper: wallpaper, invertPattern: invertPattern, rects: rects, starGift: starGift, symbolImage: symbolImage, modelRectIndex: modelRectIndex, generate: generator) + self.validPatternGeneratedImage = nil + if let (size, displayMode) = self.validLayout { + self.loadPatternForSizeIfNeeded(size: size, displayMode: displayMode, transition: .immediate) } else { - strongSelf._isReady.set(true) + self._isReady.set(true) } } else { - strongSelf._isReady.set(true) + self._isReady.set(true) } })) } @@ -1244,8 +1309,8 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou self.patternImageLayer.backgroundColor = nil } - let updatedGeneratedImage = ValidPatternGeneratedImage(wallpaper: validPatternImage.wallpaper, size: size, patternColor: patternColor.rgb, backgroundColor: patternBackgroundColor.rgb, invertPattern: invertPattern) - + let updatedGeneratedImage = ValidPatternGeneratedImage(wallpaper: validPatternImage.wallpaper, size: size, patternColor: patternColor.rgb, backgroundColor: patternBackgroundColor.rgb, invertPattern: invertPattern, starGift: starGift, modelRectIndex: modelRectIndex) + if self.validPatternGeneratedImage != updatedGeneratedImage { self.validPatternGeneratedImage = updatedGeneratedImage @@ -1256,7 +1321,7 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou self.patternImageLayer.suspendCompositionUpdates = false self.patternImageLayer.updateCompositionIfNeeded() } else { - let patternArguments = TransformImageArguments(corners: ImageCorners(), imageSize: size, boundingSize: size, intrinsicInsets: UIEdgeInsets(), custom: PatternWallpaperArguments(colors: [patternBackgroundColor], rotation: nil, customPatternColor: patternColor, preview: false, displayMode: displayMode.argumentsDisplayMode), scale: min(2.0, UIScreenScale)) + let patternArguments = TransformImageArguments(corners: ImageCorners(), imageSize: size, boundingSize: size, intrinsicInsets: UIEdgeInsets(), custom: PatternWallpaperArguments(colors: [patternBackgroundColor], rotation: nil, customPatternColor: patternColor, preview: false, displayMode: displayMode.argumentsDisplayMode, symbolImage: generateTintedImage(image: validPatternImage.symbolImage, color: .white), modelRectIndex: self.modelRectIndex), scale: min(2.0, UIScreenScale)) if self.useSharedAnimationPhase || self.patternImageLayer.contents == nil { if let drawingContext = validPatternImage.generate(patternArguments) { if let image = drawingContext.generateImage() { @@ -1267,7 +1332,7 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou self.patternImageLayer.updateCompositionIfNeeded() if self.useSharedAnimationPhase { - WallpaperBackgroundNodeImpl.cachedValidPatternImage = CachedValidPatternImage(generate: validPatternImage.generate, generated: updatedGeneratedImage, image: image) + WallpaperBackgroundNodeImpl.cachedValidPatternImage = CachedValidPatternImage(generate: validPatternImage.generate, generated: updatedGeneratedImage, rects: validPatternImage.rects, starGift: validPatternImage.starGift, symbolImage: validPatternImage.symbolImage, modelRectIndex: validPatternImage.modelRectIndex, image: image) } } else { self.updatePatternPresentation() @@ -1288,7 +1353,7 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou strongSelf.updatePatternPresentation() if let image = image, strongSelf.useSharedAnimationPhase { - WallpaperBackgroundNodeImpl.cachedValidPatternImage = CachedValidPatternImage(generate: validPatternImage.generate, generated: updatedGeneratedImage, image: image) + WallpaperBackgroundNodeImpl.cachedValidPatternImage = CachedValidPatternImage(generate: validPatternImage.generate, generated: updatedGeneratedImage, rects: validPatternImage.rects, starGift: validPatternImage.starGift, symbolImage: validPatternImage.symbolImage, modelRectIndex: validPatternImage.modelRectIndex, image: image) } } } @@ -1306,6 +1371,65 @@ public final class WallpaperBackgroundNodeImpl: ASDisplayNode, WallpaperBackgrou self.updatePatternPresentation() } } + + var modelFile: TelegramMediaFile? + if let validPatternImage = self.validPatternImage, !validPatternImage.rects.isEmpty, let starGift = validPatternImage.starGift { + if case let .unique(uniqueGift) = starGift { + for attribute in uniqueGift.attributes { + if case let .model(_, file, _) = attribute { + modelFile = file + } + } + } + } + if let validPatternImage = self.validPatternImage, !validPatternImage.rects.isEmpty, let modelRectIndex = self.modelRectIndex, let modelFile { + let rect = validPatternImage.rects[Int(modelRectIndex) % validPatternImage.rects.count] + + let modelStickerNode: DefaultAnimatedStickerNodeImpl + if let current = self.modelStickerNode { + modelStickerNode = current + } else { + modelStickerNode = DefaultAnimatedStickerNodeImpl() + modelStickerNode.setup(source: AnimatedStickerResourceSource(account: self.context.account, resource: modelFile.resource, isVideo: false), width: 96, height: 96, playbackMode: .once, mode: .direct(cachePathPrefix: nil)) + modelStickerNode.visibility = true + self.modelStickerNode = modelStickerNode + self.addSubnode(modelStickerNode) + } + + let targetSize: CGSize = self.bounds.size + let containerSize: CGSize = rect.containerSize + let useAspectFit: Bool = false + + let renderScale: CGFloat = useAspectFit + ? min(targetSize.width / containerSize.width, targetSize.height / containerSize.height) + : max(targetSize.width / containerSize.width, targetSize.height / containerSize.height) + + let drawingSize = CGSize(width: containerSize.width * renderScale, height: containerSize.height * renderScale) + + let offsetX = (targetSize.width - drawingSize.width) * 0.5 + let offsetY = (targetSize.height - drawingSize.height) * 0.5 + + let onScreenCenter = CGPoint(x: offsetX + rect.center.x * renderScale, y: offsetY + rect.center.y * renderScale) + + let side = rect.side * rect.scale * renderScale + modelStickerNode.bounds = CGRect(origin: .zero, size: CGSize(width: side, height: side)) + modelStickerNode.position = onScreenCenter + modelStickerNode.updateLayout(size: modelStickerNode.bounds.size) + modelStickerNode.alpha = 0.5 + + modelStickerNode.layer.transform = CATransform3DMakeRotation(rect.rotation, 0, 0, 1) + } else { + if let modelStickerNode = self.modelStickerNode { + self.modelStickerNode = nil + if transition.isAnimated { + modelStickerNode.layer.animateAlpha(from: 1.0, to: 0.0, duration: 0.25, removeOnCompletion: false, completion: { [weak modelStickerNode] _ in + modelStickerNode?.removeFromSupernode() + }) + } else { + modelStickerNode.removeFromSupernode() + } + } + } transition.updateFrame(layer: self.patternImageLayer, frame: CGRect(origin: CGPoint(), size: size)) } @@ -1559,3 +1683,14 @@ private protocol WallpaperComponentView: AnyObject { public func createWallpaperBackgroundNode(context: AccountContext, forChatDisplay: Bool, useSharedAnimationPhase: Bool = false) -> WallpaperBackgroundNode { return WallpaperBackgroundNodeImpl(context: context, useSharedAnimationPhase: useSharedAnimationPhase) } + +private extension StarGift { + var slug: String? { + switch self { + case let .unique(uniqueGift): + return uniqueGift.slug + default: + return nil + } + } +} diff --git a/submodules/WallpaperResources/Sources/WallpaperResources.swift b/submodules/WallpaperResources/Sources/WallpaperResources.swift index 41f5be0378..6697d7cd1e 100644 --- a/submodules/WallpaperResources/Sources/WallpaperResources.swift +++ b/submodules/WallpaperResources/Sources/WallpaperResources.swift @@ -353,14 +353,18 @@ public struct PatternWallpaperArguments: TransformImageCustomArguments { let customPatternColor: UIColor? let bakePatternAlpha: CGFloat let displayMode: DisplayMode + let symbolImage: UIImage? + let modelRectIndex: Int32? - public init(colors: [UIColor], rotation: Int32?, customPatternColor: UIColor? = nil, preview: Bool = false, bakePatternAlpha: CGFloat = 1.0, displayMode: DisplayMode = .aspectFill) { + public init(colors: [UIColor], rotation: Int32?, customPatternColor: UIColor? = nil, preview: Bool = false, bakePatternAlpha: CGFloat = 1.0, displayMode: DisplayMode = .aspectFill, symbolImage: UIImage? = nil, modelRectIndex: Int32? = nil) { self.colors = colors self.rotation = rotation self.customPatternColor = customPatternColor self.preview = preview self.bakePatternAlpha = bakePatternAlpha self.displayMode = displayMode + self.symbolImage = symbolImage + self.modelRectIndex = modelRectIndex } public func serialized() -> NSArray { @@ -373,6 +377,9 @@ public struct PatternWallpaperArguments: TransformImageCustomArguments { array.add(NSNumber(value: self.preview)) array.add(NSNumber(value: Double(self.bakePatternAlpha))) array.add(NSNumber(value: self.displayMode.rawValue)) + if let symbolImage { + array.add(symbolImage) + } return array } } @@ -470,7 +477,23 @@ private func patternWallpaperDatas(account: Account, accountManager: AccountMana } } -public func patternWallpaperImage(account: Account, accountManager: AccountManager, representations: [ImageRepresentationWithReference], mode: PatternWallpaperDrawMode, autoFetchFullSize: Bool = false) -> Signal<((TransformImageArguments) -> DrawingContext?)?, NoError> { +public struct WallpaperGiftPatternRect: Equatable { + public let containerSize: CGSize + public let center: CGPoint + public let side: CGFloat + public let scale: CGFloat + public let rotation: CGFloat + + fileprivate init(containerSize: CGSize, rect: GiftPatternRect) { + self.containerSize = containerSize + self.center = rect.center + self.side = rect.side + self.scale = rect.scale + self.rotation = rect.rotation + } +} + +public func patternWallpaperImage(account: Account, accountManager: AccountManager, representations: [ImageRepresentationWithReference], mode: PatternWallpaperDrawMode, autoFetchFullSize: Bool = false) -> Signal<(generator: (TransformImageArguments) -> DrawingContext?, rects: [WallpaperGiftPatternRect])?, NoError> { return patternWallpaperDatas(account: account, accountManager: accountManager, representations: representations, mode: mode, autoFetchFullSize: autoFetchFullSize) |> mapToSignal { fullSizeData, fullSizeComplete in if !autoFetchFullSize || fullSizeComplete { @@ -481,7 +504,7 @@ public func patternWallpaperImage(account: Account, accountManager: AccountManag } } -private func patternWallpaperImageInternal(fullSizeData: Data?, fullSizeComplete: Bool, mode: PatternWallpaperDrawMode) -> Signal<((TransformImageArguments) -> DrawingContext?)?, NoError> { +private func patternWallpaperImageInternal(fullSizeData: Data?, fullSizeComplete: Bool, mode: PatternWallpaperDrawMode) -> Signal<(generator: (TransformImageArguments) -> DrawingContext?, rects: [WallpaperGiftPatternRect])?, NoError> { var prominent = false if case .thumbnail = mode { prominent = true @@ -491,7 +514,11 @@ private func patternWallpaperImageInternal(fullSizeData: Data?, fullSizeComplete return .single((fullSizeData, fullSizeComplete)) |> map { fullSizeData, fullSizeComplete in - return { arguments in + var rects: [WallpaperGiftPatternRect] = [] + if let fullSizeData, let patternData = getGiftPatternData(fullSizeData) { + rects = patternData.rects.map { WallpaperGiftPatternRect(containerSize: patternData.size, rect: $0) } + } + return ({ arguments in var scale = scale if scale.isZero { scale = arguments.scale ?? UIScreenScale @@ -561,12 +588,12 @@ private func patternWallpaperImageInternal(fullSizeData: Data?, fullSizeComplete var image: UIImage? if let fullSizeData = fullSizeData { if mode == .screen { - image = renderPreparedImage(fullSizeData, CGSize(width: size.width * context.scale, height: size.height * context.scale), .black, 1.0, displayMode == .aspectFit) + image = renderPreparedImageWithSymbol(fullSizeData, CGSize(width: size.width * context.scale, height: size.height * context.scale), .black, 1.0, displayMode == .aspectFit, customArguments.symbolImage, customArguments.modelRectIndex ?? -1) } else { image = UIImage(data: fullSizeData) } } - + if let customPatternColor = customArguments.customPatternColor, customPatternColor.alpha < 1.0 { patternIsInverted = true c.setBlendMode(.copy) @@ -674,7 +701,7 @@ private func patternWallpaperImageInternal(fullSizeData: Data?, fullSizeComplete } else { return nil } - } + }, rects) } } @@ -1452,6 +1479,10 @@ public func themeIconImage(account: Account, accountManager: AccountManager mapToSignal { wallpaper in if let wallpaper = wallpaper, case let .file(file) = wallpaper.wallpaper { @@ -1512,11 +1546,15 @@ public func themeIconImage(account: Account, accountManager: AccountManager mapToSignal { generator -> Signal<((UIColor, UIColor?, [UInt32]), [UIColor], [UIColor], UIImage?, Bool, Bool, CGFloat, Int32?), NoError> in + |> mapToSignal { generatorAndRects -> Signal<((UIColor, UIColor?, [UInt32]), [UIColor], [UIColor], UIImage?, Bool, Bool, CGFloat, Int32?), NoError> in let imageSize = CGSize(width: 148.0, height: 320.0) let imageArguments = TransformImageArguments(corners: ImageCorners(), imageSize: imageSize, boundingSize: imageSize, intrinsicInsets: UIEdgeInsets(), emptyColor: nil, custom: arguments) - let context = generator?(imageArguments) + let context = generatorAndRects?.generator(imageArguments) let image = context?.generateImage() if !file.settings.colors.isEmpty {