text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
<?code-excerpt path-base="example/lib"?> # Migration Guide from 0.2.x to 0.3.0 Starting November 2023, Android Billing Client V4 is no longer supported, requiring app developers using the plugin to migrate to 0.3.0. Version 0.3.0 introduces breaking changes to the API as a result of changes in the underlying Google Play Billing Library. For context around the changes see the [recent changes to subscriptions in Play Console][1] and the [Google Play Billing Library migration guide][2]. ## SKUs become Products SKUs have been replaced with products. For example, the `SkuDetailsWrapper` class has been replaced by `ProductDetailsWrapper`, and the `SkuType` enum has been replaced by `ProductType`. Products are used to represent both in-app purchases (also referred to as one-time purchases) and subscriptions. There are a few changes to the data model that are important to note. Previously, an SKU of `SkuType.subs` would contain a `freeTrialPeriod`, `introductoryPrice` and some related properties. In the new model, this has been replaced by a more generic approach. A subscription product can have multiple pricing phases, each with its own price, subscription period etc. This allows for more flexibility in the pricing model. In the next section we will look at how to migrate code that uses the old model to the new model. Instead of listing all possible use cases, we will focus on three: getting the price of a one time purchase, and handling both free trials and introductory prices for subscriptions. Other use cases can be migrated in a similar way. ### Use case: getting the price of a one time purchase Below code shows how to get the price of a one time purchase before and after the migration. Other properties can be obtained in a similar way. Code before migration: ```dart SkuDetailsWrapper sku; if (sku.type == SkuType.inapp) { String price = sku.price; } ``` Code after migration: <?code-excerpt "migration_guide_examples.dart (one-time-purchase-price)"?> ```dart /// Handles the one time purchase price of a product. void handleOneTimePurchasePrice(ProductDetails productDetails) { if (productDetails is GooglePlayProductDetails) { final ProductDetailsWrapper product = productDetails.productDetails; if (product.productType == ProductType.inapp) { // Unwrapping is safe because the product is a one time purchase. final OneTimePurchaseOfferDetailsWrapper offer = product.oneTimePurchaseOfferDetails!; final String price = offer.formattedPrice; } } } ``` ### Use case: free trials Below code shows how to handle free trials for subscriptions before and after the migration. As subscriptions can contain multiple offers, each containing multiple price phases, the logic is more involved. Code before migration: ```dart SkuDetailsWrapper sku; if (sku.type == SkuType.subs) { if (sku.freeTrialPeriod.isNotEmpty) { // Free trial period logic. } } ``` Code after migration: <?code-excerpt "migration_guide_examples.dart (subscription-free-trial)"?> ```dart /// Handles the free trial period of a subscription. void handleFreeTrialPeriod(ProductDetails productDetails) { if (productDetails is GooglePlayProductDetails) { final ProductDetailsWrapper product = productDetails.productDetails; if (product.productType == ProductType.subs) { // Unwrapping is safe because the product is a subscription. final SubscriptionOfferDetailsWrapper offer = product.subscriptionOfferDetails![productDetails.subscriptionIndex!]; final List<PricingPhaseWrapper> pricingPhases = offer.pricingPhases; if (pricingPhases.first.priceAmountMicros == 0) { // Free trial period logic. } } } } ``` ### Use case: introductory prices Below code shows how to handle introductory prices for subscriptions before and after the migration. As subscriptions can contain multiple offers, each containing multiple price phases, the logic is more involved. Code before migration: ```dart SkuDetailsWrapper sku; if (sku.type == SkuType.subs) { if (sku.introductoryPriceAmountMicros != 0) { // Introductory price period logic. } } ``` Code after migration: <?code-excerpt "migration_guide_examples.dart (subscription-introductory-price)"?> ```dart /// Handles the introductory price period of a subscription. void handleIntroductoryPricePeriod(ProductDetails productDetails) { if (productDetails is GooglePlayProductDetails) { final ProductDetailsWrapper product = productDetails.productDetails; if (product.productType == ProductType.subs) { // Unwrapping is safe because the product is a subscription. final SubscriptionOfferDetailsWrapper offer = product.subscriptionOfferDetails![productDetails.subscriptionIndex!]; final List<PricingPhaseWrapper> pricingPhases = offer.pricingPhases; if (pricingPhases.length >= 2 && pricingPhases.first.priceAmountMicros < pricingPhases[1].priceAmountMicros) { // Introductory pricing period logic. } } } } ``` ## Removal of `launchPriceChangeConfirmationFlow` The method `launchPriceChangeConfirmationFlow` has been removed. Price changes are no longer handled by the application but are instead handled by the Google Play Store automatically. See [subscription price changes][3] for more information. <!-- References --> [1]: https://support.google.com/googleplay/android-developer/answer/12124625 [2]: https://developer.android.com/google/play/billing/migrate-gpblv6#5-or-6 [3]: https://developer.android.com/google/play/billing/subscriptions#price-change
packages/packages/in_app_purchase/in_app_purchase_android/migration_guide.md/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/migration_guide.md", "repo_id": "packages", "token_count": 1649 }
1,071
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <OCMock/OCMock.h> #import <XCTest/XCTest.h> #import "FIAPaymentQueueHandler.h" #import "InAppPurchasePlugin+TestOnly.h" #import "Stubs.h" @import in_app_purchase_storekit; @interface InAppPurchasePluginTest : XCTestCase @property(strong, nonatomic) FIAPReceiptManagerStub *receiptManagerStub; @property(strong, nonatomic) InAppPurchasePlugin *plugin; @end @implementation InAppPurchasePluginTest - (void)setUp { self.receiptManagerStub = [FIAPReceiptManagerStub new]; self.plugin = [[InAppPurchasePluginStub alloc] initWithReceiptManager:self.receiptManagerStub]; } - (void)tearDown { } - (void)testCanMakePayments { FlutterError *error; NSNumber *result = [self.plugin canMakePaymentsWithError:&error]; XCTAssertTrue([result boolValue]); XCTAssertNil(error); } - (void)testPaymentQueueStorefront { if (@available(iOS 13, macOS 10.15, *)) { SKPaymentQueue *mockQueue = OCMClassMock(SKPaymentQueue.class); NSDictionary *storefrontMap = @{ @"countryCode" : @"USA", @"identifier" : @"unique_identifier", }; OCMStub(mockQueue.storefront).andReturn([[SKStorefrontStub alloc] initWithMap:storefrontMap]); self.plugin.paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:mockQueue transactionsUpdated:nil transactionRemoved:nil restoreTransactionFailed:nil restoreCompletedTransactionsFinished:nil shouldAddStorePayment:nil updatedDownloads:nil transactionCache:OCMClassMock(FIATransactionCache.class)]; FlutterError *error; SKStorefrontMessage *result = [self.plugin storefrontWithError:&error]; XCTAssertEqualObjects(result.countryCode, storefrontMap[@"countryCode"]); XCTAssertEqualObjects(result.identifier, storefrontMap[@"identifier"]); XCTAssertNil(error); } else { NSLog(@"Skip testPaymentQueueStorefront for iOS lower than 13.0 or macOS lower than 10.15."); } } - (void)testPaymentQueueStorefrontReturnsNil { if (@available(iOS 13, macOS 10.15, *)) { SKPaymentQueue *mockQueue = OCMClassMock(SKPaymentQueue.class); OCMStub(mockQueue.storefront).andReturn(nil); self.plugin.paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:mockQueue transactionsUpdated:nil transactionRemoved:nil restoreTransactionFailed:nil restoreCompletedTransactionsFinished:nil shouldAddStorePayment:nil updatedDownloads:nil transactionCache:OCMClassMock(FIATransactionCache.class)]; FlutterError *error; SKStorefrontMessage *resultMap = [self.plugin storefrontWithError:&error]; XCTAssertNil(resultMap); XCTAssertNil(error); } else { NSLog(@"Skip testPaymentQueueStorefront for iOS lower than 13.0 or macOS lower than 10.15."); } } - (void)testGetProductResponse { NSArray *argument = @[ @"123" ]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion handler successfully called"]; [self.plugin startProductRequestProductIdentifiers:argument completion:^(SKProductsResponseMessage *_Nullable response, FlutterError *_Nullable startProductRequestError) { XCTAssert( [response isKindOfClass:[SKProductsResponseMessage class]]); XCTAssertEqual(response.products.count, 1); XCTAssertEqual(response.invalidProductIdentifiers.count, 0); XCTAssertEqual(response.products[0].productIdentifier, @"123"); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:5]; } - (void)testFinishTransactionSucceeds { NSDictionary *args = @{ @"transactionIdentifier" : @"567", @"productIdentifier" : @"unique_identifier", }; NSDictionary *transactionMap = @{ @"transactionIdentifier" : @"567", @"transactionState" : @(SKPaymentTransactionStatePurchasing), @"payment" : [NSNull null], @"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub" code:123 userInfo:@{}]], @"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970), }; SKPaymentTransactionStub *paymentTransaction = [[SKPaymentTransactionStub alloc] initWithMap:transactionMap]; NSArray *array = @[ paymentTransaction ]; FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class); OCMStub([mockHandler getUnfinishedTransactions]).andReturn(array); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin finishTransactionFinishMap:args error:&error]; XCTAssertNil(error); } - (void)testFinishTransactionSucceedsWithNilTransaction { NSDictionary *args = @{ @"transactionIdentifier" : [NSNull null], @"productIdentifier" : @"unique_identifier", }; NSDictionary *paymentMap = @{ @"productIdentifier" : @"123", @"requestData" : @"abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh", @"quantity" : @(2), @"applicationUsername" : @"app user name", @"simulatesAskToBuyInSandbox" : @(NO) }; NSDictionary *transactionMap = @{ @"transactionState" : @(SKPaymentTransactionStatePurchasing), @"payment" : paymentMap, @"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub" code:123 userInfo:@{}]], @"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970), }; SKPaymentTransactionStub *paymentTransaction = [[SKPaymentTransactionStub alloc] initWithMap:transactionMap]; FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class); OCMStub([mockHandler getUnfinishedTransactions]).andReturn(@[ paymentTransaction ]); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin finishTransactionFinishMap:args error:&error]; XCTAssertNil(error); } - (void)testGetProductResponseWithRequestError { NSArray *argument = @[ @"123" ]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion handler successfully called"]; id mockHandler = OCMClassMock([FIAPRequestHandler class]); InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil handlerFactory:^FIAPRequestHandler *(SKRequest *request) { return mockHandler; }]; NSError *error = [NSError errorWithDomain:@"errorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"description"}]; OCMStub([mockHandler startProductRequestWithCompletionHandler:([OCMArg invokeBlockWithArgs:[NSNull null], error, nil])]); [plugin startProductRequestProductIdentifiers:argument completion:^(SKProductsResponseMessage *_Nullable response, FlutterError *_Nullable startProductRequestError) { [expectation fulfill]; XCTAssertNotNil(error); XCTAssertNotNil(startProductRequestError); XCTAssertEqualObjects( startProductRequestError.code, @"storekit_getproductrequest_platform_error"); }]; [self waitForExpectations:@[ expectation ] timeout:5]; } - (void)testGetProductResponseWithNoResponse { NSArray *argument = @[ @"123" ]; XCTestExpectation *expectation = [self expectationWithDescription:@"completion handler successfully called"]; id mockHandler = OCMClassMock([FIAPRequestHandler class]); InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil handlerFactory:^FIAPRequestHandler *(SKRequest *request) { return mockHandler; }]; NSError *error = [NSError errorWithDomain:@"errorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"description"}]; OCMStub([mockHandler startProductRequestWithCompletionHandler:([OCMArg invokeBlockWithArgs:[NSNull null], [NSNull null], nil])]); [plugin startProductRequestProductIdentifiers:argument completion:^(SKProductsResponseMessage *_Nullable response, FlutterError *_Nullable startProductRequestError) { [expectation fulfill]; XCTAssertNotNil(error); XCTAssertNotNil(startProductRequestError); XCTAssertEqualObjects(startProductRequestError.code, @"storekit_platform_no_response"); }]; [self waitForExpectations:@[ expectation ] timeout:5]; } - (void)testAddPaymentShouldReturnFlutterErrorWhenPaymentFails { NSDictionary *argument = @{ @"productIdentifier" : @"123", @"quantity" : @(1), @"simulatesAskToBuyInSandbox" : @YES, }; FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class); OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(NO); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin addPaymentPaymentMap:argument error:&error]; OCMVerify(times(1), [mockHandler addPayment:[OCMArg any]]); XCTAssertEqualObjects(@"storekit_duplicate_product_object", error.code); XCTAssertEqualObjects(@"There is a pending transaction for the same product identifier. " @"Please either wait for it to be finished or finish it manually " @"using `completePurchase` to avoid edge cases.", error.message); XCTAssertEqualObjects(argument, error.details); } - (void)testAddPaymentShouldReturnFlutterErrorWhenInvalidProduct { NSDictionary *argument = @{ // stubbed function will return nil for an empty productIdentifier @"productIdentifier" : @"", @"quantity" : @(1), @"simulatesAskToBuyInSandbox" : @YES, }; FlutterError *error; [self.plugin addPaymentPaymentMap:argument error:&error]; XCTAssertEqualObjects(@"storekit_invalid_payment_object", error.code); XCTAssertEqualObjects( @"You have requested a payment for an invalid product. Either the " @"`productIdentifier` of the payment is not valid or the product has not been " @"fetched before adding the payment to the payment queue.", error.message); XCTAssertEqualObjects(argument, error.details); } - (void)testAddPaymentSuccessWithoutPaymentDiscount { NSDictionary *argument = @{ @"productIdentifier" : @"123", @"quantity" : @(1), @"simulatesAskToBuyInSandbox" : @YES, }; FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class); OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(YES); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin addPaymentPaymentMap:argument error:&error]; XCTAssertNil(error); OCMVerify(times(1), [mockHandler addPayment:[OCMArg checkWithBlock:^BOOL(id obj) { SKPayment *payment = obj; XCTAssert(payment != nil); XCTAssertEqual(payment.productIdentifier, @"123"); XCTAssert(payment.quantity == 1); return YES; }]]); } - (void)testAddPaymentSuccessWithPaymentDiscount { NSDictionary *argument = @{ @"productIdentifier" : @"123", @"quantity" : @(1), @"simulatesAskToBuyInSandbox" : @YES, @"paymentDiscount" : @{ @"identifier" : @"test_identifier", @"keyIdentifier" : @"test_key_identifier", @"nonce" : @"4a11a9cc-3bc3-11ec-8d3d-0242ac130003", @"signature" : @"test_signature", @"timestamp" : @(1635847102), } }; FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class); OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(YES); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin addPaymentPaymentMap:argument error:&error]; XCTAssertNil(error); OCMVerify( times(1), [mockHandler addPayment:[OCMArg checkWithBlock:^BOOL(id obj) { SKPayment *payment = obj; if (@available(iOS 12.2, *)) { SKPaymentDiscount *discount = payment.paymentDiscount; return [discount.identifier isEqual:@"test_identifier"] && [discount.keyIdentifier isEqual:@"test_key_identifier"] && [discount.nonce isEqual:[[NSUUID alloc] initWithUUIDString:@"4a11a9cc-3bc3-11ec-8d3d-0242ac130003"]] && [discount.signature isEqual:@"test_signature"] && [discount.timestamp isEqual:@(1635847102)]; } return YES; }]]); } - (void)testAddPaymentFailureWithInvalidPaymentDiscount { // Support for payment discount is only available on iOS 12.2 and higher. if (@available(iOS 12.2, *)) { NSDictionary *argument = @{ @"productIdentifier" : @"123", @"quantity" : @(1), @"simulatesAskToBuyInSandbox" : @YES, @"paymentDiscount" : @{ @"keyIdentifier" : @"test_key_identifier", @"nonce" : @"4a11a9cc-3bc3-11ec-8d3d-0242ac130003", @"signature" : @"test_signature", @"timestamp" : @(1635847102), } }; FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class); id translator = OCMClassMock(FIAObjectTranslator.class); NSString *errorMsg = @"Some error occurred"; OCMStub(ClassMethod([translator getSKPaymentDiscountFromMap:[OCMArg any] withError:(NSString __autoreleasing **)[OCMArg setTo:errorMsg]])) .andReturn(nil); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin addPaymentPaymentMap:argument error:&error]; XCTAssertEqualObjects(@"storekit_invalid_payment_discount_object", error.code); XCTAssertEqualObjects(@"You have requested a payment and specified a " @"payment discount with invalid properties. Some error occurred", error.message); XCTAssertEqualObjects(argument, error.details); OCMVerify(never(), [mockHandler addPayment:[OCMArg any]]); } } - (void)testAddPaymentWithNullSandboxArgument { NSDictionary *argument = @{ @"productIdentifier" : @"123", @"quantity" : @(1), @"simulatesAskToBuyInSandbox" : [NSNull null], }; FIAPaymentQueueHandler *mockHandler = OCMClassMock(FIAPaymentQueueHandler.class); OCMStub([mockHandler addPayment:[OCMArg any]]).andReturn(YES); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin addPaymentPaymentMap:argument error:&error]; OCMVerify(times(1), [mockHandler addPayment:[OCMArg checkWithBlock:^BOOL(id obj) { SKPayment *payment = obj; return !payment.simulatesAskToBuyInSandbox; }]]); } - (void)testRestoreTransactions { XCTestExpectation *expectation = [self expectationWithDescription:@"result successfully restore transactions"]; SKPaymentQueueStub *queue = [SKPaymentQueueStub new]; queue.testState = SKPaymentTransactionStatePurchased; __block BOOL callbackInvoked = NO; self.plugin.paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:queue transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) { } transactionRemoved:nil restoreTransactionFailed:nil restoreCompletedTransactionsFinished:^() { callbackInvoked = YES; [expectation fulfill]; } shouldAddStorePayment:nil updatedDownloads:nil transactionCache:OCMClassMock(FIATransactionCache.class)]; [queue addTransactionObserver:self.plugin.paymentQueueHandler]; FlutterError *error; [self.plugin restoreTransactionsApplicationUserName:nil error:&error]; [self waitForExpectations:@[ expectation ] timeout:5]; XCTAssertTrue(callbackInvoked); } - (void)testRetrieveReceiptDataSuccess { FlutterError *error; NSString *result = [self.plugin retrieveReceiptDataWithError:&error]; XCTAssertNotNil(result); XCTAssert([result isKindOfClass:[NSString class]]); } - (void)testRetrieveReceiptDataNil { NSBundle *mockBundle = OCMPartialMock([NSBundle mainBundle]); OCMStub(mockBundle.appStoreReceiptURL).andReturn(nil); FlutterError *error; NSString *result = [self.plugin retrieveReceiptDataWithError:&error]; XCTAssertNil(result); } - (void)testRetrieveReceiptDataError { self.receiptManagerStub.returnError = YES; FlutterError *error; NSString *result = [self.plugin retrieveReceiptDataWithError:&error]; XCTAssertNil(result); XCTAssertNotNil(error); XCTAssert([error.code isKindOfClass:[NSString class]]); NSDictionary *details = error.details; XCTAssertNotNil(details[@"error"]); NSNumber *errorCode = (NSNumber *)details[@"error"][@"code"]; XCTAssertEqual(errorCode, [NSNumber numberWithInteger:99]); } - (void)testRefreshReceiptRequest { XCTestExpectation *expectation = [self expectationWithDescription:@"completion handler successfully called"]; [self.plugin refreshReceiptReceiptProperties:nil completion:^(FlutterError *_Nullable error) { [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:5]; } - (void)testRefreshReceiptRequestWithParams { NSDictionary *properties = @{ @"isExpired" : @NO, @"isRevoked" : @NO, @"isVolumePurchase" : @NO, }; XCTestExpectation *expectation = [self expectationWithDescription:@"completion handler successfully called"]; [self.plugin refreshReceiptReceiptProperties:properties completion:^(FlutterError *_Nullable error) { [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:5]; } - (void)testRefreshReceiptRequestWithError { NSDictionary *properties = @{ @"isExpired" : @NO, @"isRevoked" : @NO, @"isVolumePurchase" : @NO, }; XCTestExpectation *expectation = [self expectationWithDescription:@"completion handler successfully called"]; id mockHandler = OCMClassMock([FIAPRequestHandler class]); InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil handlerFactory:^FIAPRequestHandler *(SKRequest *request) { return mockHandler; }]; NSError *recieptError = [NSError errorWithDomain:@"errorDomain" code:0 userInfo:@{NSLocalizedDescriptionKey : @"description"}]; OCMStub([mockHandler startProductRequestWithCompletionHandler:([OCMArg invokeBlockWithArgs:[NSNull null], recieptError, nil])]); [plugin refreshReceiptReceiptProperties:properties completion:^(FlutterError *_Nullable error) { XCTAssertNotNil(error); XCTAssertEqualObjects( error.code, @"storekit_refreshreceiptrequest_platform_error"); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:5]; } /// presentCodeRedemptionSheetWithError:error is only available on iOS #if TARGET_OS_IOS - (void)testPresentCodeRedemptionSheet { FIAPaymentQueueHandler *mockHandler = OCMClassMock([FIAPaymentQueueHandler class]); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin presentCodeRedemptionSheetWithError:&error]; OCMVerify(times(1), [mockHandler presentCodeRedemptionSheet]); } #endif - (void)testGetPendingTransactions { SKPaymentQueue *mockQueue = OCMClassMock(SKPaymentQueue.class); NSDictionary *transactionMap = @{ @"transactionIdentifier" : [NSNull null], @"transactionState" : @(SKPaymentTransactionStatePurchasing), @"payment" : [NSNull null], @"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub" code:123 userInfo:@{}]], @"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970), @"originalTransaction" : [NSNull null], }; OCMStub(mockQueue.transactions).andReturn(@[ [[SKPaymentTransactionStub alloc] initWithMap:transactionMap] ]); self.plugin.paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:mockQueue transactionsUpdated:nil transactionRemoved:nil restoreTransactionFailed:nil restoreCompletedTransactionsFinished:nil shouldAddStorePayment:nil updatedDownloads:nil transactionCache:OCMClassMock(FIATransactionCache.class)]; FlutterError *error; SKPaymentTransactionStub *original = [[SKPaymentTransactionStub alloc] initWithMap:transactionMap]; SKPaymentTransactionMessage *originalPigeon = [FIAObjectTranslator convertTransactionToPigeon:original]; SKPaymentTransactionMessage *result = [self.plugin transactionsWithError:&error][0]; XCTAssertEqualObjects([self paymentTransactionToList:result], [self paymentTransactionToList:originalPigeon]); } - (void)testStartObservingPaymentQueue { FIAPaymentQueueHandler *mockHandler = OCMClassMock([FIAPaymentQueueHandler class]); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin startObservingPaymentQueueWithError:&error]; OCMVerify(times(1), [mockHandler startObservingPaymentQueue]); } - (void)testStopObservingPaymentQueue { FIAPaymentQueueHandler *mockHandler = OCMClassMock([FIAPaymentQueueHandler class]); self.plugin.paymentQueueHandler = mockHandler; FlutterError *error; [self.plugin stopObservingPaymentQueueWithError:&error]; OCMVerify(times(1), [mockHandler stopObservingPaymentQueue]); } #if TARGET_OS_IOS - (void)testRegisterPaymentQueueDelegate { if (@available(iOS 13, *)) { self.plugin.paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:[SKPaymentQueueStub new] transactionsUpdated:nil transactionRemoved:nil restoreTransactionFailed:nil restoreCompletedTransactionsFinished:nil shouldAddStorePayment:nil updatedDownloads:nil transactionCache:OCMClassMock(FIATransactionCache.class)]; // Verify the delegate is nil before we register one. XCTAssertNil(self.plugin.paymentQueueHandler.delegate); FlutterError *error; [self.plugin registerPaymentQueueDelegateWithError:&error]; // Verify the delegate is not nil after we registered one. XCTAssertNotNil(self.plugin.paymentQueueHandler.delegate); } } #endif - (void)testRemovePaymentQueueDelegate { if (@available(iOS 13, *)) { self.plugin.paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:[SKPaymentQueueStub new] transactionsUpdated:nil transactionRemoved:nil restoreTransactionFailed:nil restoreCompletedTransactionsFinished:nil shouldAddStorePayment:nil updatedDownloads:nil transactionCache:OCMClassMock(FIATransactionCache.class)]; self.plugin.paymentQueueHandler.delegate = OCMProtocolMock(@protocol(SKPaymentQueueDelegate)); // Verify the delegate is not nil before removing it. XCTAssertNotNil(self.plugin.paymentQueueHandler.delegate); FlutterError *error; [self.plugin removePaymentQueueDelegateWithError:&error]; // Verify the delegate is nill after removing it. XCTAssertNil(self.plugin.paymentQueueHandler.delegate); } } - (void)testHandleTransactionsUpdated { NSDictionary *transactionMap = @{ @"transactionIdentifier" : @"567", @"transactionState" : @(SKPaymentTransactionStatePurchasing), @"payment" : [NSNull null], @"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub" code:123 userInfo:@{}]], @"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970), }; InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil]; FlutterMethodChannel *mockChannel = OCMClassMock([FlutterMethodChannel class]); plugin.transactionObserverCallbackChannel = mockChannel; OCMStub([mockChannel invokeMethod:[OCMArg any] arguments:[OCMArg any]]); SKPaymentTransactionStub *paymentTransaction = [[SKPaymentTransactionStub alloc] initWithMap:transactionMap]; NSArray *array = [NSArray arrayWithObjects:paymentTransaction, nil]; NSMutableArray *maps = [NSMutableArray new]; [maps addObject:[FIAObjectTranslator getMapFromSKPaymentTransaction:paymentTransaction]]; [plugin handleTransactionsUpdated:array]; OCMVerify(times(1), [mockChannel invokeMethod:@"updatedTransactions" arguments:[OCMArg any]]); } - (void)testHandleTransactionsRemoved { NSDictionary *transactionMap = @{ @"transactionIdentifier" : @"567", @"transactionState" : @(SKPaymentTransactionStatePurchasing), @"payment" : [NSNull null], @"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub" code:123 userInfo:@{}]], @"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970), }; InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil]; FlutterMethodChannel *mockChannel = OCMClassMock([FlutterMethodChannel class]); plugin.transactionObserverCallbackChannel = mockChannel; OCMStub([mockChannel invokeMethod:[OCMArg any] arguments:[OCMArg any]]); SKPaymentTransactionStub *paymentTransaction = [[SKPaymentTransactionStub alloc] initWithMap:transactionMap]; NSArray *array = [NSArray arrayWithObjects:paymentTransaction, nil]; NSMutableArray *maps = [NSMutableArray new]; [maps addObject:[FIAObjectTranslator getMapFromSKPaymentTransaction:paymentTransaction]]; [plugin handleTransactionsRemoved:array]; OCMVerify(times(1), [mockChannel invokeMethod:@"removedTransactions" arguments:maps]); } - (void)testHandleTransactionRestoreFailed { InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil]; FlutterMethodChannel *mockChannel = OCMClassMock([FlutterMethodChannel class]); plugin.transactionObserverCallbackChannel = mockChannel; OCMStub([mockChannel invokeMethod:[OCMArg any] arguments:[OCMArg any]]); NSError *error; [plugin handleTransactionRestoreFailed:error]; OCMVerify(times(1), [mockChannel invokeMethod:@"restoreCompletedTransactionsFailed" arguments:[FIAObjectTranslator getMapFromNSError:error]]); } - (void)testRestoreCompletedTransactionsFinished { InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil]; FlutterMethodChannel *mockChannel = OCMClassMock([FlutterMethodChannel class]); plugin.transactionObserverCallbackChannel = mockChannel; OCMStub([mockChannel invokeMethod:[OCMArg any] arguments:[OCMArg any]]); [plugin restoreCompletedTransactionsFinished]; OCMVerify(times(1), [mockChannel invokeMethod:@"paymentQueueRestoreCompletedTransactionsFinished" arguments:nil]); } - (void)testShouldAddStorePayment { NSDictionary *paymentMap = @{ @"productIdentifier" : @"123", @"requestData" : @"abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh", @"quantity" : @(2), @"applicationUsername" : @"app user name", @"simulatesAskToBuyInSandbox" : @(NO) }; NSDictionary *productMap = @{ @"price" : @"1", @"priceLocale" : [FIAObjectTranslator getMapFromNSLocale:NSLocale.systemLocale], @"productIdentifier" : @"123", @"localizedTitle" : @"title", @"localizedDescription" : @"des", }; SKMutablePayment *payment = [FIAObjectTranslator getSKMutablePaymentFromMap:paymentMap]; SKProductStub *product = [[SKProductStub alloc] initWithMap:productMap]; InAppPurchasePlugin *plugin = [[InAppPurchasePlugin alloc] initWithReceiptManager:nil]; FlutterMethodChannel *mockChannel = OCMClassMock([FlutterMethodChannel class]); plugin.transactionObserverCallbackChannel = mockChannel; OCMStub([mockChannel invokeMethod:[OCMArg any] arguments:[OCMArg any]]); NSDictionary *args = @{ @"payment" : [FIAObjectTranslator getMapFromSKPayment:payment], @"product" : [FIAObjectTranslator getMapFromSKProduct:product] }; BOOL result = [plugin shouldAddStorePayment:payment product:product]; XCTAssertEqual(result, NO); OCMVerify(times(1), [mockChannel invokeMethod:@"shouldAddStorePayment" arguments:args]); } #if TARGET_OS_IOS - (void)testShowPriceConsentIfNeeded { FIAPaymentQueueHandler *mockQueueHandler = OCMClassMock(FIAPaymentQueueHandler.class); self.plugin.paymentQueueHandler = mockQueueHandler; FlutterError *error; [self.plugin showPriceConsentIfNeededWithError:&error]; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" if (@available(iOS 13.4, *)) { OCMVerify(times(1), [mockQueueHandler showPriceConsentIfNeeded]); } else { OCMVerify(never(), [mockQueueHandler showPriceConsentIfNeeded]); } #pragma clang diagnostic pop } #endif // The following methods are deserializer copied from Pigeon's output. - (NSArray *)paymentTransactionToList:(SKPaymentTransactionMessage *)paymentTransaction { return @[ (paymentTransaction.payment ? [self paymentToList:paymentTransaction.payment] : [NSNull null]), @(paymentTransaction.transactionState), (paymentTransaction.originalTransaction ? [self paymentTransactionToList:paymentTransaction.originalTransaction] : [NSNull null]), paymentTransaction.transactionTimeStamp ?: [NSNull null], paymentTransaction.transactionIdentifier ?: [NSNull null], (paymentTransaction.error ? [self errorToList:paymentTransaction.error] : [NSNull null]), ]; } - (NSArray *)paymentToList:(SKPaymentMessage *)payment { return @[ payment.productIdentifier ?: [NSNull null], payment.applicationUsername ?: [NSNull null], payment.requestData ?: [NSNull null], @(payment.quantity), @(payment.simulatesAskToBuyInSandbox), (payment.paymentDiscount ? [self paymentDiscountToList:payment.paymentDiscount] : [NSNull null]), ]; } - (NSArray *)paymentDiscountToList:(SKPaymentDiscountMessage *)discount { return @[ discount.identifier ?: [NSNull null], discount.keyIdentifier ?: [NSNull null], discount.nonce ?: [NSNull null], discount.signature ?: [NSNull null], @(discount.timestamp), ]; } - (NSArray *)errorToList:(SKErrorMessage *)error { return @[ @(error.code), error.domain ?: [NSNull null], error.userInfo ?: [NSNull null], ]; } @end
packages/packages/in_app_purchase/in_app_purchase_storekit/example/macos/RunnerTests/InAppPurchasePluginTests.m/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/macos/RunnerTests/InAppPurchasePluginTests.m", "repo_id": "packages", "token_count": 14419 }
1,072
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <XCTest/XCTest.h> #import "Stubs.h" @import in_app_purchase_storekit; @interface TranslatorTest : XCTestCase @property(strong, nonatomic) NSDictionary *periodMap; @property(strong, nonatomic) NSMutableDictionary *discountMap; @property(strong, nonatomic) NSMutableDictionary *discountMissingIdentifierMap; @property(strong, nonatomic) NSMutableDictionary *productMap; @property(strong, nonatomic) NSDictionary *productResponseMap; @property(strong, nonatomic) NSDictionary *paymentMap; @property(copy, nonatomic) NSDictionary *paymentDiscountMap; @property(strong, nonatomic) NSDictionary *transactionMap; @property(strong, nonatomic) NSDictionary *errorMap; @property(strong, nonatomic) NSDictionary *localeMap; @property(strong, nonatomic) NSDictionary *storefrontMap; @property(strong, nonatomic) NSDictionary *storefrontAndPaymentTransactionMap; @end @implementation TranslatorTest - (void)setUp { self.periodMap = @{@"numberOfUnits" : @(0), @"unit" : @(0)}; self.discountMap = [[NSMutableDictionary alloc] initWithDictionary:@{ @"price" : @"1", @"priceLocale" : [FIAObjectTranslator getMapFromNSLocale:NSLocale.systemLocale], @"numberOfPeriods" : @1, @"subscriptionPeriod" : self.periodMap, @"paymentMode" : @1, }]; if (@available(iOS 12.2, *)) { self.discountMap[@"identifier"] = @"test offer id"; self.discountMap[@"type"] = @(SKProductDiscountTypeIntroductory); } self.discountMissingIdentifierMap = [[NSMutableDictionary alloc] initWithDictionary:@{ @"price" : @"1", @"priceLocale" : [FIAObjectTranslator getMapFromNSLocale:NSLocale.systemLocale], @"numberOfPeriods" : @1, @"subscriptionPeriod" : self.periodMap, @"paymentMode" : @1, @"identifier" : [NSNull null], @"type" : @0, }]; self.productMap = [[NSMutableDictionary alloc] initWithDictionary:@{ @"price" : @"1", @"priceLocale" : [FIAObjectTranslator getMapFromNSLocale:NSLocale.systemLocale], @"productIdentifier" : @"123", @"localizedTitle" : @"title", @"localizedDescription" : @"des", }]; self.productMap[@"subscriptionPeriod"] = self.periodMap; self.productMap[@"introductoryPrice"] = self.discountMap; if (@available(iOS 12.2, *)) { self.productMap[@"discounts"] = @[ self.discountMap ]; } self.productMap[@"subscriptionGroupIdentifier"] = @"com.group"; self.productResponseMap = @{@"products" : @[ self.productMap ], @"invalidProductIdentifiers" : @[]}; self.paymentMap = @{ @"productIdentifier" : @"123", @"requestData" : @"abcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefghabcdefgh", @"quantity" : @(2), @"applicationUsername" : @"app user name", @"simulatesAskToBuyInSandbox" : @(NO) }; self.paymentDiscountMap = @{ @"identifier" : @"payment_discount_identifier", @"keyIdentifier" : @"payment_discount_key_identifier", @"nonce" : @"d18981e0-9003-4365-98a2-4b90e3b62c52", @"signature" : @"this is a encrypted signature", @"timestamp" : @([NSDate date].timeIntervalSince1970), }; NSDictionary *originalTransactionMap = @{ @"transactionIdentifier" : @"567", @"transactionState" : @(SKPaymentTransactionStatePurchasing), @"payment" : [NSNull null], @"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub" code:123 userInfo:@{}]], @"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970), @"originalTransaction" : [NSNull null], }; self.transactionMap = @{ @"transactionIdentifier" : @"567", @"transactionState" : @(SKPaymentTransactionStatePurchasing), @"payment" : [NSNull null], @"error" : [FIAObjectTranslator getMapFromNSError:[NSError errorWithDomain:@"test_stub" code:123 userInfo:@{}]], @"transactionTimeStamp" : @([NSDate date].timeIntervalSince1970), @"originalTransaction" : originalTransactionMap, }; self.errorMap = @{ @"code" : @(123), @"domain" : @"test_domain", @"userInfo" : @{ @"key" : @"value", } }; self.storefrontMap = @{ @"countryCode" : @"USA", @"identifier" : @"unique_identifier", }; self.storefrontAndPaymentTransactionMap = @{ @"storefront" : self.storefrontMap, @"transaction" : self.transactionMap, }; } - (void)testSKProductSubscriptionPeriodStubToMap { SKProductSubscriptionPeriodStub *period = [[SKProductSubscriptionPeriodStub alloc] initWithMap:self.periodMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKProductSubscriptionPeriod:period]; XCTAssertEqualObjects(map, self.periodMap); } - (void)testSKProductDiscountStubToMap { SKProductDiscountStub *discount = [[SKProductDiscountStub alloc] initWithMap:self.discountMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKProductDiscount:discount]; XCTAssertEqualObjects(map, self.discountMap); } - (void)testProductToMap { SKProductStub *product = [[SKProductStub alloc] initWithMap:self.productMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKProduct:product]; XCTAssertEqualObjects(map, self.productMap); } - (void)testProductResponseToMap { SKProductsResponseStub *response = [[SKProductsResponseStub alloc] initWithMap:self.productResponseMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKProductsResponse:response]; XCTAssertEqualObjects(map, self.productResponseMap); } - (void)testPaymentToMap { SKMutablePayment *payment = [FIAObjectTranslator getSKMutablePaymentFromMap:self.paymentMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKPayment:payment]; XCTAssertEqualObjects(map, self.paymentMap); } - (void)testPaymentTransactionToMap { // payment is not KVC, cannot test payment field. SKPaymentTransactionStub *paymentTransaction = [[SKPaymentTransactionStub alloc] initWithMap:self.transactionMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKPaymentTransaction:paymentTransaction]; XCTAssertEqualObjects(map, self.transactionMap); } - (void)testError { NSErrorStub *error = [[NSErrorStub alloc] initWithMap:self.errorMap]; NSDictionary *map = [FIAObjectTranslator getMapFromNSError:error]; XCTAssertEqualObjects(map, self.errorMap); } - (void)testErrorWithNSNumberAsUserInfo { NSError *error = [NSError errorWithDomain:SKErrorDomain code:3 userInfo:@{@"key" : @42}]; NSDictionary *expectedMap = @{@"domain" : SKErrorDomain, @"code" : @3, @"userInfo" : @{@"key" : @42}}; NSDictionary *map = [FIAObjectTranslator getMapFromNSError:error]; XCTAssertEqualObjects(expectedMap, map); } - (void)testErrorWithMultipleUnderlyingErrors { NSError *underlyingErrorOne = [NSError errorWithDomain:SKErrorDomain code:2 userInfo:nil]; NSError *underlyingErrorTwo = [NSError errorWithDomain:SKErrorDomain code:1 userInfo:nil]; NSError *mainError = [NSError errorWithDomain:SKErrorDomain code:3 userInfo:@{@"underlyingErrors" : @[ underlyingErrorOne, underlyingErrorTwo ]}]; NSDictionary *expectedMap = @{ @"domain" : SKErrorDomain, @"code" : @3, @"userInfo" : @{ @"underlyingErrors" : @[ @{@"domain" : SKErrorDomain, @"code" : @2, @"userInfo" : @{}}, @{@"domain" : SKErrorDomain, @"code" : @1, @"userInfo" : @{}} ] } }; NSDictionary *map = [FIAObjectTranslator getMapFromNSError:mainError]; XCTAssertEqualObjects(expectedMap, map); } - (void)testErrorWithNestedUnderlyingError { NSError *underlyingError = [NSError errorWithDomain:SKErrorDomain code:2 userInfo:nil]; NSError *mainError = [NSError errorWithDomain:SKErrorDomain code:3 userInfo:@{@"nesting" : @{@"underlyingError" : underlyingError}}]; NSDictionary *expectedMap = @{ @"domain" : SKErrorDomain, @"code" : @3, @"userInfo" : @{ @"nesting" : @{ @"underlyingError" : @{@"domain" : SKErrorDomain, @"code" : @2, @"userInfo" : @{}}, } } }; NSDictionary *map = [FIAObjectTranslator getMapFromNSError:mainError]; XCTAssertEqualObjects(expectedMap, map); } - (void)testErrorWithUnsupportedUserInfo { NSError *error = [NSError errorWithDomain:SKErrorDomain code:3 userInfo:@{@"user_info" : [[NSObject alloc] init]}]; NSDictionary *expectedMap = @{ @"domain" : SKErrorDomain, @"code" : @3, @"userInfo" : @{ @"user_info" : [NSString stringWithFormat: @"Unable to encode native userInfo object of type %@ to map. Please submit an " @"issue at https://github.com/flutter/flutter/issues/new with the title " @"\"[in_app_purchase_storekit] Unable to encode userInfo of type %@\" and add " @"reproduction steps and the error details in the description field.", [NSObject class], [NSObject class]] } }; NSDictionary *map = [FIAObjectTranslator getMapFromNSError:error]; XCTAssertEqualObjects(expectedMap, map); } - (void)testLocaleToMap { NSLocale *system = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; NSDictionary *map = [FIAObjectTranslator getMapFromNSLocale:system]; XCTAssertEqualObjects(map[@"currencySymbol"], system.currencySymbol); XCTAssertEqualObjects(map[@"countryCode"], system.countryCode); } - (void)testSKStorefrontToMap { if (@available(iOS 13.0, *)) { SKStorefront *storefront = [[SKStorefrontStub alloc] initWithMap:self.storefrontMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKStorefront:storefront]; XCTAssertEqualObjects(map, self.storefrontMap); } } - (void)testSKStorefrontAndSKPaymentTransactionToMap { if (@available(iOS 13.0, *)) { SKStorefront *storefront = [[SKStorefrontStub alloc] initWithMap:self.storefrontMap]; SKPaymentTransaction *transaction = [[SKPaymentTransactionStub alloc] initWithMap:self.transactionMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKStorefront:storefront andSKPaymentTransaction:transaction]; XCTAssertEqualObjects(map, self.storefrontAndPaymentTransactionMap); } } - (void)testSKPaymentDiscountFromMap { if (@available(iOS 12.2, *)) { NSString *error = nil; SKPaymentDiscount *paymentDiscount = [FIAObjectTranslator getSKPaymentDiscountFromMap:self.paymentDiscountMap withError:&error]; XCTAssertEqual(paymentDiscount.identifier, self.paymentDiscountMap[@"identifier"]); XCTAssertEqual(paymentDiscount.keyIdentifier, self.paymentDiscountMap[@"keyIdentifier"]); XCTAssertEqualObjects(paymentDiscount.nonce, [[NSUUID alloc] initWithUUIDString:self.paymentDiscountMap[@"nonce"]]); XCTAssertEqual(paymentDiscount.signature, self.paymentDiscountMap[@"signature"]); XCTAssertEqual(paymentDiscount.timestamp, self.paymentDiscountMap[@"timestamp"]); } } - (void)testSKPaymentDiscountFromMapMissingIdentifier { if (@available(iOS 12.2, *)) { NSArray *invalidValues = @[ [NSNull null], @(1), @"" ]; for (id value in invalidValues) { NSDictionary *discountMap = @{ @"identifier" : value, @"keyIdentifier" : @"payment_discount_key_identifier", @"nonce" : @"d18981e0-9003-4365-98a2-4b90e3b62c52", @"signature" : @"this is a encrypted signature", @"timestamp" : @([NSDate date].timeIntervalSince1970), }; NSString *error = nil; [FIAObjectTranslator getSKPaymentDiscountFromMap:discountMap withError:&error]; XCTAssertNotNil(error); XCTAssertEqualObjects( error, @"When specifying a payment discount the 'identifier' field is mandatory."); } } } - (void)testGetMapFromSKProductDiscountMissingIdentifier { if (@available(iOS 12.2, *)) { SKProductDiscountStub *discount = [[SKProductDiscountStub alloc] initWithMap:self.discountMissingIdentifierMap]; NSDictionary *map = [FIAObjectTranslator getMapFromSKProductDiscount:discount]; XCTAssertEqualObjects(map, self.discountMissingIdentifierMap); } } - (void)testSKPaymentDiscountFromMapMissingKeyIdentifier { if (@available(iOS 12.2, *)) { NSArray *invalidValues = @[ [NSNull null], @(1), @"" ]; for (id value in invalidValues) { NSDictionary *discountMap = @{ @"identifier" : @"payment_discount_identifier", @"keyIdentifier" : value, @"nonce" : @"d18981e0-9003-4365-98a2-4b90e3b62c52", @"signature" : @"this is a encrypted signature", @"timestamp" : @([NSDate date].timeIntervalSince1970), }; NSString *error = nil; [FIAObjectTranslator getSKPaymentDiscountFromMap:discountMap withError:&error]; XCTAssertNotNil(error); XCTAssertEqualObjects( error, @"When specifying a payment discount the 'keyIdentifier' field is mandatory."); } } } - (void)testSKPaymentDiscountFromMapMissingNonce { if (@available(iOS 12.2, *)) { NSArray *invalidValues = @[ [NSNull null], @(1), @"" ]; for (id value in invalidValues) { NSDictionary *discountMap = @{ @"identifier" : @"payment_discount_identifier", @"keyIdentifier" : @"payment_discount_key_identifier", @"nonce" : value, @"signature" : @"this is a encrypted signature", @"timestamp" : @([NSDate date].timeIntervalSince1970), }; NSString *error = nil; [FIAObjectTranslator getSKPaymentDiscountFromMap:discountMap withError:&error]; XCTAssertNotNil(error); XCTAssertEqualObjects(error, @"When specifying a payment discount the 'nonce' field is mandatory."); } } } - (void)testSKPaymentDiscountFromMapMissingSignature { if (@available(iOS 12.2, *)) { NSArray *invalidValues = @[ [NSNull null], @(1), @"" ]; for (id value in invalidValues) { NSDictionary *discountMap = @{ @"identifier" : @"payment_discount_identifier", @"keyIdentifier" : @"payment_discount_key_identifier", @"nonce" : @"d18981e0-9003-4365-98a2-4b90e3b62c52", @"signature" : value, @"timestamp" : @([NSDate date].timeIntervalSince1970), }; NSString *error = nil; [FIAObjectTranslator getSKPaymentDiscountFromMap:discountMap withError:&error]; XCTAssertNotNil(error); XCTAssertEqualObjects( error, @"When specifying a payment discount the 'signature' field is mandatory."); } } } - (void)testSKPaymentDiscountFromMapMissingTimestamp { if (@available(iOS 12.2, *)) { NSArray *invalidValues = @[ [NSNull null], @"", @(-1) ]; for (id value in invalidValues) { NSDictionary *discountMap = @{ @"identifier" : @"payment_discount_identifier", @"keyIdentifier" : @"payment_discount_key_identifier", @"nonce" : @"d18981e0-9003-4365-98a2-4b90e3b62c52", @"signature" : @"this is a encrypted signature", @"timestamp" : value, }; NSString *error = nil; [FIAObjectTranslator getSKPaymentDiscountFromMap:discountMap withError:&error]; XCTAssertNotNil(error); XCTAssertEqualObjects( error, @"When specifying a payment discount the 'timestamp' field is mandatory."); } } } - (void)testSKPaymentDiscountFromMapOverflowingTimestamp { if (@available(iOS 12.2, *)) { NSDictionary *discountMap = @{ @"identifier" : @"payment_discount_identifier", @"keyIdentifier" : @"payment_discount_key_identifier", @"nonce" : @"d18981e0-9003-4365-98a2-4b90e3b62c52", @"signature" : @"this is a encrypted signature", @"timestamp" : @1665044583595, // timestamp 2022 Oct }; NSString *error = nil; SKPaymentDiscount *paymentDiscount = [FIAObjectTranslator getSKPaymentDiscountFromMap:discountMap withError:&error]; XCTAssertNil(error); XCTAssertNotNil(paymentDiscount); XCTAssertEqual(paymentDiscount.identifier, discountMap[@"identifier"]); XCTAssertEqual(paymentDiscount.keyIdentifier, discountMap[@"keyIdentifier"]); XCTAssertEqualObjects(paymentDiscount.nonce, [[NSUUID alloc] initWithUUIDString:discountMap[@"nonce"]]); XCTAssertEqual(paymentDiscount.signature, discountMap[@"signature"]); XCTAssertEqual(paymentDiscount.timestamp, discountMap[@"timestamp"]); } } - (void)testSKPaymentDiscountConvertToPigeon { if (@available(iOS 12.2, *)) { NSString *error = nil; SKPaymentDiscount *paymentDiscount = [FIAObjectTranslator getSKPaymentDiscountFromMap:self.paymentDiscountMap withError:&error]; SKPaymentDiscountMessage *paymentDiscountPigeon = [FIAObjectTranslator convertPaymentDiscountToPigeon:paymentDiscount]; XCTAssertNotNil(paymentDiscountPigeon); XCTAssertEqual(paymentDiscount.identifier, paymentDiscountPigeon.identifier); XCTAssertEqual(paymentDiscount.keyIdentifier, paymentDiscount.keyIdentifier); XCTAssertEqualObjects(paymentDiscount.nonce, [[NSUUID alloc] initWithUUIDString:paymentDiscountPigeon.nonce]); XCTAssertEqual(paymentDiscount.signature, paymentDiscountPigeon.signature); XCTAssertEqual([paymentDiscount.timestamp intValue], paymentDiscountPigeon.timestamp); } } - (void)testSKErrorConvertToPigeon { NSError *error = [NSError errorWithDomain:SKErrorDomain code:3 userInfo:@{@"key" : @42}]; SKErrorMessage *msg = [SKErrorMessage makeWithCode:3 domain:SKErrorDomain userInfo:@{@"key" : @42}]; SKErrorMessage *skerror = [FIAObjectTranslator convertSKErrorToPigeon:error]; XCTAssertEqual(skerror.domain, msg.domain); XCTAssertEqual(skerror.code, msg.code); XCTAssertEqualObjects(skerror.userInfo, msg.userInfo); } - (void)testSKPaymentConvertToPigeon { if (@available(iOS 12.2, *)) { SKMutablePayment *payment = [FIAObjectTranslator getSKMutablePaymentFromMap:self.paymentMap]; SKPaymentMessage *msg = [FIAObjectTranslator convertPaymentToPigeon:payment]; XCTAssertEqual(payment.productIdentifier, msg.productIdentifier); XCTAssertEqualObjects(payment.requestData, [msg.requestData dataUsingEncoding:NSUTF8StringEncoding]); XCTAssertEqual(payment.quantity, msg.quantity); XCTAssertEqual(payment.applicationUsername, msg.applicationUsername); XCTAssertEqual(payment.simulatesAskToBuyInSandbox, msg.simulatesAskToBuyInSandbox); } } - (void)testSKPaymentTransactionConvertToPigeon { SKPaymentTransactionStub *paymentTransaction = [[SKPaymentTransactionStub alloc] initWithMap:self.transactionMap]; SKPaymentTransactionMessage *msg = [FIAObjectTranslator convertTransactionToPigeon:paymentTransaction]; XCTAssertEqual(msg.payment, NULL); XCTAssertEqual(msg.transactionState, SKPaymentTransactionStateMessagePurchasing); XCTAssertEqual(paymentTransaction.transactionDate, [NSDate dateWithTimeIntervalSince1970:[msg.transactionTimeStamp doubleValue]]); XCTAssertEqual(paymentTransaction.transactionIdentifier, msg.transactionIdentifier); } - (void)testSKProductResponseCovertToPigeon { SKProductsResponseStub *response = [[SKProductsResponseStub alloc] initWithMap:self.productResponseMap]; SKProductsResponseMessage *responseMsg = [FIAObjectTranslator convertProductsResponseToPigeon:response]; XCTAssertEqual(responseMsg.products.count, 1); XCTAssertEqual(responseMsg.invalidProductIdentifiers.count, 0); SKProductMessage *productMsg = responseMsg.products[0]; // These values are being set in productResponseMap in setUp() XCTAssertEqualObjects(productMsg.price, @"1"); XCTAssertEqualObjects(productMsg.productIdentifier, @"123"); XCTAssertEqualObjects(productMsg.localizedTitle, @"title"); XCTAssertEqualObjects(productMsg.localizedDescription, @"des"); XCTAssertEqualObjects(productMsg.subscriptionGroupIdentifier, @"com.group"); SKPriceLocaleMessage *localeMsg = productMsg.priceLocale; SKProductSubscriptionPeriodMessage *subPeriod = productMsg.subscriptionPeriod; SKProductDiscountMessage *introDiscount = productMsg.introductoryPrice; NSArray<SKProductDiscountMessage *> *discounts = productMsg.discounts; XCTAssertEqualObjects(localeMsg.countryCode, nil); XCTAssertEqualObjects(localeMsg.currencyCode, nil); XCTAssertEqualObjects(localeMsg.currencySymbol, @"\u00a4"); XCTAssertEqual(subPeriod.unit, SKSubscriptionPeriodUnitMessageDay); XCTAssertEqual(subPeriod.numberOfUnits, 0); XCTAssertEqualObjects(introDiscount.price, @"1"); XCTAssertEqual(introDiscount.numberOfPeriods, 1); XCTAssertEqual(introDiscount.paymentMode, SKProductDiscountPaymentModeMessagePayUpFront); XCTAssertEqual(discounts.count, 1); } @end
packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/TranslatorTests.m/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/example/shared/RunnerTests/TranslatorTests.m", "repo_id": "packages", "token_count": 8532 }
1,073
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'sk_product_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** SkProductResponseWrapper _$SkProductResponseWrapperFromJson(Map json) => SkProductResponseWrapper( products: (json['products'] as List<dynamic>?) ?.map((e) => SKProductWrapper.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? [], invalidProductIdentifiers: (json['invalidProductIdentifiers'] as List<dynamic>?) ?.map((e) => e as String) .toList() ?? [], ); SKProductSubscriptionPeriodWrapper _$SKProductSubscriptionPeriodWrapperFromJson( Map json) => SKProductSubscriptionPeriodWrapper( numberOfUnits: json['numberOfUnits'] as int? ?? 0, unit: const SKSubscriptionPeriodUnitConverter() .fromJson(json['unit'] as int?), ); SKProductDiscountWrapper _$SKProductDiscountWrapperFromJson(Map json) => SKProductDiscountWrapper( price: json['price'] as String? ?? '', priceLocale: SKPriceLocaleWrapper.fromJson((json['priceLocale'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), numberOfPeriods: json['numberOfPeriods'] as int? ?? 0, paymentMode: const SKProductDiscountPaymentModeConverter() .fromJson(json['paymentMode'] as int?), subscriptionPeriod: SKProductSubscriptionPeriodWrapper.fromJson( (json['subscriptionPeriod'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), identifier: json['identifier'] as String? ?? null, type: const SKProductDiscountTypeConverter().fromJson(json['type'] as int?), ); SKProductWrapper _$SKProductWrapperFromJson(Map json) => SKProductWrapper( productIdentifier: json['productIdentifier'] as String? ?? '', localizedTitle: json['localizedTitle'] as String? ?? '', localizedDescription: json['localizedDescription'] as String? ?? '', priceLocale: SKPriceLocaleWrapper.fromJson((json['priceLocale'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), subscriptionGroupIdentifier: json['subscriptionGroupIdentifier'] as String?, price: json['price'] as String? ?? '', subscriptionPeriod: json['subscriptionPeriod'] == null ? null : SKProductSubscriptionPeriodWrapper.fromJson( (json['subscriptionPeriod'] as Map?)?.map( (k, e) => MapEntry(k as String, e), )), introductoryPrice: json['introductoryPrice'] == null ? null : SKProductDiscountWrapper.fromJson( Map<String, dynamic>.from(json['introductoryPrice'] as Map)), discounts: (json['discounts'] as List<dynamic>?) ?.map((e) => SKProductDiscountWrapper.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? [], ); SKPriceLocaleWrapper _$SKPriceLocaleWrapperFromJson(Map json) => SKPriceLocaleWrapper( currencySymbol: json['currencySymbol'] as String? ?? '', currencyCode: json['currencyCode'] as String? ?? '', countryCode: json['countryCode'] as String? ?? '', );
packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_product_wrapper.g.dart", "repo_id": "packages", "token_count": 1407 }
1,074
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_storekit/src/messages.g.dart'; import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; void main() { final SKPriceLocaleWrapper locale = SKPriceLocaleWrapper( currencySymbol: r'$', currencyCode: 'USD', countryCode: 'USA'); final SKProductSubscriptionPeriodWrapper subPeriod = SKProductSubscriptionPeriodWrapper( numberOfUnits: 1, unit: SKSubscriptionPeriodUnit.month); final SKProductDiscountWrapper discount = SKProductDiscountWrapper( price: '0.99', priceLocale: locale, numberOfPeriods: 1, paymentMode: SKProductDiscountPaymentMode.payUpFront, subscriptionPeriod: subPeriod, identifier: 'discount', type: SKProductDiscountType.subscription); final SKProductWrapper product = SKProductWrapper( productIdentifier: 'fake_product', localizedTitle: 'title', localizedDescription: 'description', priceLocale: locale, price: '3.99', subscriptionGroupIdentifier: 'sub_group', discounts: <SKProductDiscountWrapper>[discount]); final SkProductResponseWrapper productResponse = SkProductResponseWrapper( products: <SKProductWrapper>[product], invalidProductIdentifiers: const <String>['invalid_identifier']); test('test SKPriceLocale pigeon converters', () { final SKPriceLocaleMessage msg = SKPriceLocaleWrapper.convertToPigeon(locale); expect(msg.currencySymbol, r'$'); expect(msg.currencyCode, 'USD'); expect(msg.countryCode, 'USA'); final SKPriceLocaleWrapper convertedWrapper = SKPriceLocaleWrapper.convertFromPigeon(msg); expect(convertedWrapper, locale); }); test('test SKProductSubscription pigeon converters', () { final SKProductSubscriptionPeriodMessage msg = SKProductSubscriptionPeriodWrapper.convertToPigeon(subPeriod); expect(msg.unit, SKSubscriptionPeriodUnitMessage.month); expect(msg.numberOfUnits, 1); final SKProductSubscriptionPeriodWrapper convertedWrapper = SKProductSubscriptionPeriodWrapper.convertFromPigeon(msg); expect(convertedWrapper, subPeriod); }); test('test SKProductDiscount pigeon converters', () { final SKProductDiscountMessage msg = SKProductDiscountWrapper.convertToPigeon(discount); expect(msg.price, '0.99'); expect(msg.numberOfPeriods, 1); expect(msg.paymentMode, SKProductDiscountPaymentModeMessage.payUpFront); expect(msg.identifier, 'discount'); expect(msg.type, SKProductDiscountTypeMessage.subscription); final SKProductDiscountWrapper convertedWrapper = SKProductDiscountWrapper.convertFromPigeon(msg); expect(convertedWrapper, discount); }); test('test SKProduct pigeon converters', () { final SKProductMessage msg = SKProductWrapper.convertToPigeon(product); expect(msg.productIdentifier, 'fake_product'); expect(msg.localizedTitle, 'title'); expect(msg.localizedDescription, 'description'); expect(msg.price, '3.99'); expect(msg.discounts?.length, 1); final SKProductWrapper convertedWrapper = SKProductWrapper.convertFromPigeon(msg); expect(convertedWrapper, product); }); test('test SKProductResponse pigeon converters', () { final SKProductsResponseMessage msg = SkProductResponseWrapper.convertToPigeon(productResponse); expect(msg.products?.length, 1); expect(msg.invalidProductIdentifiers, <String>['invalid_identifier']); final SkProductResponseWrapper convertedWrapper = SkProductResponseWrapper.convertFromPigeon(msg); expect(convertedWrapper, productResponse); }); test('test SKerror pigeon converter', () { final SKErrorMessage msg = SKErrorMessage(code: 99, domain: 'domain'); final SKError wrapper = SKError.convertFromPigeon(msg); expect(wrapper.code, 99); expect(wrapper.domain, 'domain'); expect(wrapper.userInfo, <String, Object>{}); }); }
packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/pigeon_converter_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/pigeon_converter_test.dart", "repo_id": "packages", "token_count": 1431 }
1,075
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:ios_platform_images/ios_platform_images.dart'; void main() => runApp(const MyApp()); /// Main widget for the example app. class MyApp extends StatefulWidget { /// Default Constructor const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { @override void initState() { super.initState(); IosPlatformImages.resolveURL('textfile') // ignore: avoid_print .then((String? value) => print(value)); } @override Widget build(BuildContext context) { // #docregion Usage // "flutter" is a resource in Assets.xcassets. final Image xcassetImage = Image( image: IosPlatformImages.load('flutter'), semanticLabel: 'Flutter logo', ); // #enddocregion Usage return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Plugin example app'), ), body: Center( child: xcassetImage, ), ), ); } }
packages/packages/ios_platform_images/example/lib/main.dart/0
{ "file_path": "packages/packages/ios_platform_images/example/lib/main.dart", "repo_id": "packages", "token_count": 456 }
1,076
group 'io.flutter.plugins.localauth' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'io.flutter.plugins.localauth' } compileSdk 34 defaultConfig { minSdkVersion 16 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } lintOptions { checkAllWarnings true warningsAsErrors true disable 'AndroidGradlePluginVersion', 'InvalidPackage', 'GradleDependency' } testOptions { unitTests.includeAndroidResources = true unitTests.returnDefaultValues = true unitTests.all { testLogging { events "passed", "skipped", "failed", "standardOut", "standardError" outputs.upToDateWhen {false} showStandardStreams = true } } } } dependencies { api "androidx.core:core:1.10.1" api "androidx.biometric:biometric:1.1.0" api "androidx.fragment:fragment:1.6.2" testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:5.0.0' testImplementation 'org.robolectric:robolectric:4.10.3' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test:rules:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' // TODO(camsim99): org.jetbrains.kotlin:kotlin-bom artifact purpose is to align kotlin stdlib and related code versions. // This should be removed when https://github.com/flutter/flutter/issues/125062 is fixed. implementation(platform("org.jetbrains.kotlin:kotlin-bom:1.8.10")) }
packages/packages/local_auth/local_auth_android/android/build.gradle/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/build.gradle", "repo_id": "packages", "token_count": 898 }
1,077
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Flutter/Flutter.h> #import <LocalAuthentication/LocalAuthentication.h> /// Protocol for a source of LAContext instances. Used to allow context injection in unit tests. @protocol FLADAuthContextFactory <NSObject> - (LAContext *)createAuthContext; @end @interface FLALocalAuthPlugin () /// Returns an instance that uses the given factory to create LAContexts. - (instancetype)initWithContextFactory:(NSObject<FLADAuthContextFactory> *)factory NS_DESIGNATED_INITIALIZER; @end
packages/packages/local_auth/local_auth_darwin/darwin/Classes/FLALocalAuthPlugin_Test.h/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/darwin/Classes/FLALocalAuthPlugin_Test.h", "repo_id": "packages", "token_count": 191 }
1,078
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:local_auth_darwin/local_auth_darwin.dart'; import 'package:local_auth_darwin/src/messages.g.dart'; import 'package:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'local_auth_darwin_test.mocks.dart'; @GenerateMocks(<Type>[LocalAuthApi]) void main() { late MockLocalAuthApi api; late LocalAuthDarwin plugin; setUp(() { api = MockLocalAuthApi(); plugin = LocalAuthDarwin(api: api); }); test('registers instance', () { LocalAuthDarwin.registerWith(); expect(LocalAuthPlatform.instance, isA<LocalAuthDarwin>()); }); group('deviceSupportsBiometrics', () { test('handles true', () async { when(api.deviceCanSupportBiometrics()).thenAnswer((_) async => true); expect(await plugin.deviceSupportsBiometrics(), true); }); test('handles false', () async { when(api.deviceCanSupportBiometrics()).thenAnswer((_) async => false); expect(await plugin.deviceSupportsBiometrics(), false); }); }); group('isDeviceSupported', () { test('handles true', () async { when(api.isDeviceSupported()).thenAnswer((_) async => true); expect(await plugin.isDeviceSupported(), true); }); test('handles false', () async { when(api.isDeviceSupported()).thenAnswer((_) async => false); expect(await plugin.isDeviceSupported(), false); }); }); group('stopAuthentication', () { test('always returns false', () async { expect(await plugin.stopAuthentication(), false); }); }); group('getEnrolledBiometrics', () { test('translates values', () async { when(api.getEnrolledBiometrics()) .thenAnswer((_) async => <AuthBiometricWrapper>[ AuthBiometricWrapper(value: AuthBiometric.face), AuthBiometricWrapper(value: AuthBiometric.fingerprint), ]); final List<BiometricType> result = await plugin.getEnrolledBiometrics(); expect(result, <BiometricType>[ BiometricType.face, BiometricType.fingerprint, ]); }); test('handles empty', () async { when(api.getEnrolledBiometrics()) .thenAnswer((_) async => <AuthBiometricWrapper>[]); final List<BiometricType> result = await plugin.getEnrolledBiometrics(); expect(result, <BiometricType>[]); }); }); group('authenticate', () { group('strings', () { test('passes default values when nothing is provided', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.success)); const String reason = 'test reason'; await plugin.authenticate( localizedReason: reason, authMessages: <AuthMessages>[]); final VerificationResult result = verify(api.authenticate(any, captureAny)); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from // auth_messages_ios.dart expect(strings.lockOut, iOSLockOut); expect(strings.goToSettingsButton, goToSettings); expect(strings.goToSettingsDescription, iOSGoToSettingsDescription); expect(strings.cancelButton, iOSOkButton); expect(strings.localizedFallbackTitle, null); }); test('passes default values when only other platform values are provided', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.success)); const String reason = 'test reason'; await plugin.authenticate( localizedReason: reason, authMessages: <AuthMessages>[AnotherPlatformAuthMessages()]); final VerificationResult result = verify(api.authenticate(any, captureAny)); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the default values from // auth_messages_ios.dart expect(strings.lockOut, iOSLockOut); expect(strings.goToSettingsButton, goToSettings); expect(strings.goToSettingsDescription, iOSGoToSettingsDescription); expect(strings.cancelButton, iOSOkButton); expect(strings.localizedFallbackTitle, null); }); test('passes all non-default values correctly', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.success)); // These are arbitrary values; all that matters is that: // - they are different from the defaults, and // - they are different from each other. const String reason = 'A'; const String lockOut = 'B'; const String goToSettingsButton = 'C'; const String gotToSettingsDescription = 'D'; const String cancel = 'E'; const String localizedFallbackTitle = 'F'; await plugin .authenticate(localizedReason: reason, authMessages: <AuthMessages>[ const IOSAuthMessages( lockOut: lockOut, goToSettingsButton: goToSettingsButton, goToSettingsDescription: gotToSettingsDescription, cancelButton: cancel, localizedFallbackTitle: localizedFallbackTitle, ), AnotherPlatformAuthMessages(), ]); final VerificationResult result = verify(api.authenticate(any, captureAny)); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); expect(strings.lockOut, lockOut); expect(strings.goToSettingsButton, goToSettingsButton); expect(strings.goToSettingsDescription, gotToSettingsDescription); expect(strings.cancelButton, cancel); expect(strings.localizedFallbackTitle, localizedFallbackTitle); }); test('passes provided messages with default fallbacks', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.success)); // These are arbitrary values; all that matters is that: // - they are different from the defaults, and // - they are different from each other. const String reason = 'A'; const String lockOut = 'B'; const String localizedFallbackTitle = 'C'; const String cancel = 'D'; await plugin .authenticate(localizedReason: reason, authMessages: <AuthMessages>[ const IOSAuthMessages( lockOut: lockOut, localizedFallbackTitle: localizedFallbackTitle, cancelButton: cancel, ), ]); final VerificationResult result = verify(api.authenticate(any, captureAny)); final AuthStrings strings = result.captured[0] as AuthStrings; expect(strings.reason, reason); // These should all be the provided values. expect(strings.lockOut, lockOut); expect(strings.localizedFallbackTitle, localizedFallbackTitle); expect(strings.cancelButton, cancel); // These were not set, so should all be the default values from // auth_messages_ios.dart expect(strings.goToSettingsButton, goToSettings); expect(strings.goToSettingsDescription, iOSGoToSettingsDescription); }); }); group('options', () { test('passes default values', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.success)); await plugin.authenticate( localizedReason: 'reason', authMessages: <AuthMessages>[]); final VerificationResult result = verify(api.authenticate(captureAny, any)); final AuthOptions options = result.captured[0] as AuthOptions; expect(options.biometricOnly, false); expect(options.sticky, false); expect(options.useErrorDialogs, true); }); test('passes provided non-default values', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.success)); await plugin.authenticate( localizedReason: 'reason', authMessages: <AuthMessages>[], options: const AuthenticationOptions( biometricOnly: true, stickyAuth: true, useErrorDialogs: false, )); final VerificationResult result = verify(api.authenticate(captureAny, any)); final AuthOptions options = result.captured[0] as AuthOptions; expect(options.biometricOnly, true); expect(options.sticky, true); expect(options.useErrorDialogs, false); }); }); group('return values', () { test('handles success', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.success)); final bool result = await plugin.authenticate( localizedReason: 'reason', authMessages: <AuthMessages>[]); expect(result, true); }); test('handles failure', () async { when(api.authenticate(any, any)).thenAnswer( (_) async => AuthResultDetails(result: AuthResult.failure)); final bool result = await plugin.authenticate( localizedReason: 'reason', authMessages: <AuthMessages>[]); expect(result, false); }); test('converts errorNotAvailable to legacy PlatformException', () async { const String errorMessage = 'a message'; const String errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer((_) async => AuthResultDetails( result: AuthResult.errorNotAvailable, errorMessage: errorMessage, errorDetails: errorDetails)); expect( () async => plugin.authenticate( localizedReason: 'reason', authMessages: <AuthMessages>[]), throwsA(isA<PlatformException>() .having((PlatformException e) => e.code, 'code', 'NotAvailable') .having( (PlatformException e) => e.message, 'message', errorMessage) .having((PlatformException e) => e.details, 'details', errorDetails))); }); test('converts errorNotEnrolled to legacy PlatformException', () async { const String errorMessage = 'a message'; const String errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer((_) async => AuthResultDetails( result: AuthResult.errorNotEnrolled, errorMessage: errorMessage, errorDetails: errorDetails)); expect( () async => plugin.authenticate( localizedReason: 'reason', authMessages: <AuthMessages>[]), throwsA(isA<PlatformException>() .having((PlatformException e) => e.code, 'code', 'NotEnrolled') .having( (PlatformException e) => e.message, 'message', errorMessage) .having((PlatformException e) => e.details, 'details', errorDetails))); }); test('converts errorPasscodeNotSet to legacy PlatformException', () async { const String errorMessage = 'a message'; const String errorDetails = 'some details'; when(api.authenticate(any, any)).thenAnswer((_) async => AuthResultDetails( result: AuthResult.errorPasscodeNotSet, errorMessage: errorMessage, errorDetails: errorDetails)); expect( () async => plugin.authenticate( localizedReason: 'reason', authMessages: <AuthMessages>[]), throwsA(isA<PlatformException>() .having( (PlatformException e) => e.code, 'code', 'PasscodeNotSet') .having( (PlatformException e) => e.message, 'message', errorMessage) .having((PlatformException e) => e.details, 'details', errorDetails))); }); }); }); } class AnotherPlatformAuthMessages extends AuthMessages { @override Map<String, String> get args => throw UnimplementedError(); }
packages/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.dart", "repo_id": "packages", "token_count": 5075 }
1,079
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:collection'; import 'dart:convert'; import 'package:crypto/crypto.dart'; import 'package:googleapis_auth/googleapis_auth.dart'; import 'package:http/http.dart'; /// Common format of a metric data point. class MetricPoint { /// Creates a new data point. MetricPoint( this.value, Map<String, String?> tags, ) : _tags = SplayTreeMap<String, String>.from(tags); /// Can store integer values. final double? value; /// Test name, unit, timestamp, configs, git revision, ..., in sorted order. UnmodifiableMapView<String, String> get tags => UnmodifiableMapView<String, String>(_tags); final SplayTreeMap<String, String> _tags; /// Unique identifier for updating existing data point. /// /// We shouldn't have to worry about hash collisions until we have about /// 2^128 points. /// /// This id should stay constant even if the [tags.keys] are reordered. /// (Because we are using an ordered SplayTreeMap to generate the id.) String get id => sha256.convert(utf8.encode('$_tags')).toString(); @override String toString() { return 'MetricPoint(value=$value, tags=$_tags)'; } } /// Interface to write [MetricPoint]. abstract class MetricDestination { /// Insert new data points or modify old ones with matching id. Future<void> update( List<MetricPoint> points, DateTime commitTime, String taskName); } /// Create `AuthClient` in case we only have an access token without the full /// credentials json. It's currently the case for Chrmoium LUCI bots. AuthClient authClientFromAccessToken(String token, List<String> scopes) { final DateTime anHourLater = DateTime.now().add(const Duration(hours: 1)); final AccessToken accessToken = AccessToken('Bearer', token, anHourLater.toUtc()); final AccessCredentials accessCredentials = AccessCredentials(accessToken, null, scopes); return authenticatedClient(Client(), accessCredentials); }
packages/packages/metrics_center/lib/src/common.dart/0
{ "file_path": "packages/packages/metrics_center/lib/src/common.dart", "repo_id": "packages", "token_count": 635 }
1,080
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:multicast_dns/src/packet.dart'; import 'package:multicast_dns/src/resource_record.dart'; import 'package:test/test.dart'; const int _kSrvHeaderSize = 6; void main() { testValidPackages(); testBadPackages(); testNonUtf8DomainName(); // testHexDumpList(); testPTRRData(); testSRVRData(); } void testValidPackages() { test('Can decode valid packets', () { List<ResourceRecord> result = decodeMDnsResponse(package1)!; expect(result, isNotNull); expect(result.length, 1); IPAddressResourceRecord ipResult = result[0] as IPAddressResourceRecord; expect(ipResult.name, 'raspberrypi.local'); expect(ipResult.address.address, '192.168.1.191'); result = decodeMDnsResponse(package2)!; expect(result.length, 2); ipResult = result[0] as IPAddressResourceRecord; expect(ipResult.name, 'raspberrypi.local'); expect(ipResult.address.address, '192.168.1.191'); ipResult = result[1] as IPAddressResourceRecord; expect(ipResult.name, 'raspberrypi.local'); expect(ipResult.address.address, '169.254.95.83'); result = decodeMDnsResponse(package3)!; expect(result.length, 8); expect(result, <ResourceRecord>[ TxtResourceRecord( 'raspberrypi [b8:27:eb:03:92:4b]._workstation._tcp.local', result[0].validUntil, text: '', ), PtrResourceRecord( '_udisks-ssh._tcp.local', result[1].validUntil, domainName: 'raspberrypi._udisks-ssh._tcp.local', ), SrvResourceRecord( 'raspberrypi._udisks-ssh._tcp.local', result[2].validUntil, target: 'raspberrypi.local', port: 22, priority: 0, weight: 0, ), TxtResourceRecord( 'raspberrypi._udisks-ssh._tcp.local', result[3].validUntil, text: '', ), PtrResourceRecord('_services._dns-sd._udp.local', result[4].validUntil, domainName: '_udisks-ssh._tcp.local'), PtrResourceRecord( '_workstation._tcp.local', result[5].validUntil, domainName: 'raspberrypi [b8:27:eb:03:92:4b]._workstation._tcp.local', ), SrvResourceRecord( 'raspberrypi [b8:27:eb:03:92:4b]._workstation._tcp.local', result[6].validUntil, target: 'raspberrypi.local', port: 9, priority: 0, weight: 0, ), PtrResourceRecord( '_services._dns-sd._udp.local', result[7].validUntil, domainName: '_workstation._tcp.local', ), ]); result = decodeMDnsResponse(packagePtrResponse)!; expect(6, result.length); expect(result, <ResourceRecord>[ PtrResourceRecord( '_fletch_agent._tcp.local', result[0].validUntil, domainName: 'fletch-agent on raspberrypi._fletch_agent._tcp.local', ), TxtResourceRecord( 'fletch-agent on raspberrypi._fletch_agent._tcp.local', result[1].validUntil, text: '', ), SrvResourceRecord( 'fletch-agent on raspberrypi._fletch_agent._tcp.local', result[2].validUntil, target: 'raspberrypi.local', port: 12121, priority: 0, weight: 0, ), IPAddressResourceRecord( 'raspberrypi.local', result[3].validUntil, address: InternetAddress('fe80:0000:0000:0000:ba27:ebff:fe69:6e3a'), ), IPAddressResourceRecord( 'raspberrypi.local', result[4].validUntil, address: InternetAddress('192.168.1.1'), ), IPAddressResourceRecord( 'raspberrypi.local', result[5].validUntil, address: InternetAddress('169.254.167.172'), ), ]); }); // Fixes https://github.com/flutter/flutter/issues/31854 test('Can decode packages with question, answer and additional', () { final List<ResourceRecord> result = decodeMDnsResponse(packetWithQuestionAnArCount)!; expect(result, isNotNull); expect(result.length, 2); expect(result, <ResourceRecord>[ PtrResourceRecord( '_______________.____._____', result[0].validUntil, domainName: '_______________________._______________.____._____', ), PtrResourceRecord( '_______________.____._____', result[1].validUntil, domainName: '____________________________._______________.____._____', ), ]); }); // Fixes https://github.com/flutter/flutter/issues/31854 test('Can decode packages without question and with answer and additional', () { final List<ResourceRecord> result = decodeMDnsResponse(packetWithoutQuestionWithAnArCount)!; expect(result, isNotNull); expect(result.length, 2); expect(result, <ResourceRecord>[ PtrResourceRecord( '_______________.____._____', result[0].validUntil, domainName: '______________________._______________.____._____', ), TxtResourceRecord( '______________________.____________.____._____', result[1].validUntil, text: 'model=MacBookPro14,3\nosxvers=18\necolor=225,225,223\n', ), ]); }); test('Can decode packages with a long text resource', () { final List<ResourceRecord> result = decodeMDnsResponse(packetWithLongTxt)!; expect(result, isNotNull); expect(result.length, 2); expect(result, <ResourceRecord>[ PtrResourceRecord( '_______________.____._____', result[0].validUntil, domainName: '______________________._______________.____._____', ), TxtResourceRecord( '______________________.____________.____._____', result[1].validUntil, text: '${')' * 129}\n', ), ]); }); } void testBadPackages() { test('Returns null for invalid packets', () { for (final List<int> p in <List<int>>[package1, package2, package3]) { for (int i = 0; i < p.length; i++) { expect(decodeMDnsResponse(p.sublist(0, i)), isNull); } } }); } void testPTRRData() { test('Can read FQDN from PTR data', () { expect('sgjesse-macbookpro2 [78:31:c1:b8:55:38]._workstation._tcp.local', readFQDN(ptrRData)); expect('fletch-agent._fletch_agent._tcp.local', readFQDN(ptrRData2)); }); } void testSRVRData() { test('Can read FQDN from SRV data', () { expect('fletch.local', readFQDN(srvRData, _kSrvHeaderSize)); }); } void testNonUtf8DomainName() { test('Returns non-null for non-utf8 domain name', () { final List<ResourceRecord> result = decodeMDnsResponse(nonUtf8Package)!; expect(result, isNotNull); expect(result[0] is TxtResourceRecord, isTrue); final TxtResourceRecord txt = result[0] as TxtResourceRecord; expect(txt.name, contains('�')); }); } // One address. const List<int> package1 = <int>[ 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0xc0, 0xa8, 0x01, 0xbf ]; // Two addresses. const List<int> package2 = <int>[ 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0xc0, 0xa8, 0x01, 0xbf, 0xc0, 0x0c, 0x00, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0xa9, 0xfe, 0x5f, 0x53 ]; // Eight mixed answers. const List<int> package3 = <int>[ 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0x20, 0x5b, 0x62, 0x38, 0x3a, 0x32, 0x37, 0x3a, 0x65, 0x62, 0x3a, 0x30, 0x33, 0x3a, 0x39, 0x32, 0x3a, 0x34, 0x62, 0x5d, 0x0c, 0x5f, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x10, 0x80, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x01, 0x00, 0x0b, 0x5f, 0x75, 0x64, 0x69, 0x73, 0x6b, 0x73, 0x2d, 0x73, 0x73, 0x68, 0xc0, 0x39, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x0e, 0x0b, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0xc0, 0x50, 0xc0, 0x68, 0x00, 0x21, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x0b, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0xc0, 0x3e, 0xc0, 0x68, 0x00, 0x10, 0x80, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x01, 0x00, 0x09, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x07, 0x5f, 0x64, 0x6e, 0x73, 0x2d, 0x73, 0x64, 0x04, 0x5f, 0x75, 0x64, 0x70, 0xc0, 0x3e, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x02, 0xc0, 0x50, 0xc0, 0x2c, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x02, 0xc0, 0x0c, 0xc0, 0x0c, 0x00, 0x21, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0xc0, 0x88, 0xc0, 0xa3, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x02, 0xc0, 0x2c ]; const List<int> packagePtrResponse = <int>[ 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x5f, 0x66, 0x6c, 0x65, 0x74, 0x63, 0x68, 0x5f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x1e, 0x1b, 0x66, 0x6c, 0x65, 0x74, 0x63, 0x68, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x20, 0x6f, 0x6e, 0x20, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0xc0, 0x0c, 0xc0, 0x30, 0x00, 0x10, 0x80, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x01, 0x00, 0xc0, 0x30, 0x00, 0x21, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x2f, 0x59, 0x0b, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0xc0, 0x1f, 0xc0, 0x6d, 0x00, 0x1c, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x10, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xba, 0x27, 0xeb, 0xff, 0xfe, 0x69, 0x6e, 0x3a, 0xc0, 0x6d, 0x00, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0xc0, 0xa8, 0x01, 0x01, 0xc0, 0x6d, 0x00, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x04, 0xa9, 0xfe, 0xa7, 0xac ]; const List<int> ptrRData = <int>[ 0x27, 0x73, 0x67, 0x6a, 0x65, 0x73, 0x73, 0x65, 0x2d, 0x6d, 0x61, 0x63, 0x62, 0x6f, 0x6f, 0x6b, 0x70, 0x72, 0x6f, 0x32, 0x20, 0x5b, 0x37, 0x38, 0x3a, 0x33, 0x31, 0x3a, 0x63, 0x31, 0x3a, 0x62, 0x38, 0x3a, 0x35, 0x35, 0x3a, 0x33, 0x38, 0x5d, 0x0c, 0x5f, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00 ]; const List<int> ptrRData2 = <int>[ 0x0c, 0x66, 0x6c, 0x65, 0x74, 0x63, 0x68, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x0d, 0x5f, 0x66, 0x6c, 0x65, 0x74, 0x63, 0x68, 0x5f, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00 ]; const List<int> srvRData = <int>[ 0x00, 0x00, 0x00, 0x00, 0x2f, 0x59, 0x06, 0x66, 0x6c, 0x65, 0x74, 0x63, 0x68, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00 ]; const List<int> packetWithQuestionAnArCount = <int>[ 0, 0, 2, 0, 0, 1, 0, 1, 0, 0, 0, 1, 15, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 4, 95, 95, 95, 95, 5, 95, 95, 95, 95, 95, 0, 0, 12, 0, 1, 192, 12, 0, 12, 0, 1, 0, 0, 14, 13, 0, 26, 23, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 192, 12, 192, 12, 0, 12, 0, 1, 0, 0, 14, 13, 0, 31, 28, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 192, 12, ]; const List<int> packetWithoutQuestionWithAnArCount = <int>[ 0, 0, 132, 0, 0, 0, 0, 1, 0, 0, 0, 1, 15, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 4, 95, 95, 95, 95, 5, 95, 95, 95, 95, 95, 0, 0, 12, 0, 1, 0, 0, 17, 148, 0, 25, 22, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 192, 12, 22, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 12, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 192, 28, 0, 16, 0, 1, 0, 0, 17, 148, 0, 51, 20, 109, 111, 100, 101, 108, 61, 77, 97, 99, 66, 111, 111, 107, 80, 114, 111, 49, 52, 44, 51, 10, 111, 115, 120, 118, 101, 114, 115, 61, 49, 56, 18, 101, 99, 111, 108, 111, 114, 61, 50, 50, 53, 44, 50, 50, 53, 44, 50, 50, 51, ]; // This is the same as packetWithoutQuestionWithAnArCount, but the text // resource just has a single long string. If the length isn't decoded // separately from the string, there will be utf8 decoding failures. const List<int> packetWithLongTxt = <int>[ 0, 0, 132, 0, 0, 0, 0, 1, 0, 0, 0, 1, 15, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 4, 95, 95, 95, 95, 5, 95, 95, 95, 95, 95, 0, 0, 12, 0, 1, 0, 0, 17, 148, 0, 25, 22, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 192, 12, 22, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 12, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 95, 192, 28, 0, 16, 0, 1, 0, 0, 17, 148, 0, 51, // Long string starts here. 129, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 16 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 32 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 64 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, // 128, 41, // 129 ]; // Package with a domain name that is not valid utf-8. const List<int> nonUtf8Package = <int>[ 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0x20, 0x5b, 0x62, 0x38, 0x3a, 0x32, 0x37, 0x3a, 0x65, 0x62, 0xd2, 0x30, 0x33, 0x3a, 0x39, 0x32, 0x3a, 0x34, 0x62, 0x5d, 0x0c, 0x5f, 0x77, 0x6f, 0x72, 0x6b, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x10, 0x80, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x01, 0x00, 0x0b, 0x5f, 0x75, 0x64, 0x69, 0x73, 0x6b, 0x73, 0x2d, 0x73, 0x73, 0x68, 0xc0, 0x39, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x0e, 0x0b, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0xc0, 0x50, 0xc0, 0x68, 0x00, 0x21, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x0b, 0x72, 0x61, 0x73, 0x70, 0x62, 0x65, 0x72, 0x72, 0x79, 0x70, 0x69, 0xc0, 0x3e, 0xc0, 0x68, 0x00, 0x10, 0x80, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x01, 0x00, 0x09, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x73, 0x07, 0x5f, 0x64, 0x6e, 0x73, 0x2d, 0x73, 0x64, 0x04, 0x5f, 0x75, 0x64, 0x70, 0xc0, 0x3e, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x02, 0xc0, 0x50, 0xc0, 0x2c, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x02, 0xc0, 0x0c, 0xc0, 0x0c, 0x00, 0x21, 0x80, 0x01, 0x00, 0x00, 0x00, 0x78, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0xc0, 0x88, 0xc0, 0xa3, 0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x11, 0x94, 0x00, 0x02, 0xc0, 0x2c ];
packages/packages/multicast_dns/test/decode_test.dart/0
{ "file_path": "packages/packages/multicast_dns/test/decode_test.dart", "repo_id": "packages", "token_count": 10776 }
1,081
name: image_colors description: A simple example of how to use the PaletteGenerator to load the palette from an image file. publish_to: none version: 0.1.0 environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter palette_generator: path: ../ dev_dependencies: flutter_test: sdk: flutter flutter: uses-material-design: true assets: - assets/landscape.png
packages/packages/palette_generator/example/pubspec.yaml/0
{ "file_path": "packages/packages/palette_generator/example/pubspec.yaml", "repo_id": "packages", "token_count": 161 }
1,082
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.pathprovider; import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugins.pathprovider.Messages.PathProviderApi; import io.flutter.util.PathUtils; import java.io.File; import java.util.ArrayList; import java.util.List; public class PathProviderPlugin implements FlutterPlugin, PathProviderApi { static final String TAG = "PathProviderPlugin"; private Context context; public PathProviderPlugin() {} private void setup(BinaryMessenger messenger, Context context) { try { PathProviderApi.setup(messenger, this); } catch (Exception ex) { Log.e(TAG, "Received exception while setting up PathProviderPlugin", ex); } this.context = context; } @SuppressWarnings("deprecation") public static void registerWith( @NonNull io.flutter.plugin.common.PluginRegistry.Registrar registrar) { PathProviderPlugin instance = new PathProviderPlugin(); instance.setup(registrar.messenger(), registrar.context()); } @Override public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { setup(binding.getBinaryMessenger(), binding.getApplicationContext()); } @Override public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { PathProviderApi.setup(binding.getBinaryMessenger(), null); } @Override public @Nullable String getTemporaryPath() { return getPathProviderTemporaryDirectory(); } @Override public @Nullable String getApplicationSupportPath() { return getApplicationSupportDirectory(); } @Override public @Nullable String getApplicationDocumentsPath() { return getPathProviderApplicationDocumentsDirectory(); } @Override public @Nullable String getApplicationCachePath() { return context.getCacheDir().getPath(); } @Override public @Nullable String getExternalStoragePath() { return getPathProviderStorageDirectory(); } @Override public @NonNull List<String> getExternalCachePaths() { return getPathProviderExternalCacheDirectories(); } @Override public @NonNull List<String> getExternalStoragePaths( @NonNull Messages.StorageDirectory directory) { return getPathProviderExternalStorageDirectories(directory); } private String getPathProviderTemporaryDirectory() { return context.getCacheDir().getPath(); } private String getApplicationSupportDirectory() { return PathUtils.getFilesDir(context); } private String getPathProviderApplicationDocumentsDirectory() { return PathUtils.getDataDirectory(context); } private String getPathProviderStorageDirectory() { final File dir = context.getExternalFilesDir(null); if (dir == null) { return null; } return dir.getAbsolutePath(); } private List<String> getPathProviderExternalCacheDirectories() { final List<String> paths = new ArrayList<>(); if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { for (File dir : context.getExternalCacheDirs()) { if (dir != null) { paths.add(dir.getAbsolutePath()); } } } else { File dir = context.getExternalCacheDir(); if (dir != null) { paths.add(dir.getAbsolutePath()); } } return paths; } private String getStorageDirectoryString(@NonNull Messages.StorageDirectory directory) { switch (directory) { case ROOT: return null; case MUSIC: return "music"; case PODCASTS: return "podcasts"; case RINGTONES: return "ringtones"; case ALARMS: return "alarms"; case NOTIFICATIONS: return "notifications"; case PICTURES: return "pictures"; case MOVIES: return "movies"; case DOWNLOADS: return "downloads"; case DCIM: return "dcim"; case DOCUMENTS: return "documents"; default: throw new RuntimeException("Unrecognized directory: " + directory); } } private List<String> getPathProviderExternalStorageDirectories( @NonNull Messages.StorageDirectory directory) { final List<String> paths = new ArrayList<>(); if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { for (File dir : context.getExternalFilesDirs(getStorageDirectoryString(directory))) { if (dir != null) { paths.add(dir.getAbsolutePath()); } } } else { File dir = context.getExternalFilesDir(getStorageDirectoryString(directory)); if (dir != null) { paths.add(dir.getAbsolutePath()); } } return paths; } }
packages/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/PathProviderPlugin.java/0
{ "file_path": "packages/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/PathProviderPlugin.java", "repo_id": "packages", "token_count": 1709 }
1,083
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/path_provider/path_provider_android/example/android/gradle.properties/0
{ "file_path": "packages/packages/path_provider/path_provider_android/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
1,084
## NEXT * Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6. ## 2.3.2 * Adds privacy manifest. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.3.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.3.0 * Adds getApplicationCachePath() for storing app-specific cache files. ## 2.2.4 * Updates to the latest version of `pigeon`. * Updates minimum supported macOS version to 10.14. ## 2.2.3 * Updates minimum iOS version to 11. ## 2.2.2 * Updates pigeon for null value handling fixes. * Updates minimum Flutter version to 3.3. ## 2.2.1 * Updates to `pigeon` version 9. ## 2.2.0 * Adds support for `getContainerPath` on iOS. ## 2.1.3 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 2.1.2 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum supported Flutter version to 3.0. ## 2.1.1 * Fixes a regression in the path retured by `getApplicationSupportDirectory` on iOS. ## 2.1.0 * Renames the package previously published as [`path_provider_macos`](https://pub.dev/packages/path_provider_macos) * Adds iOS support.
packages/packages/path_provider/path_provider_foundation/CHANGELOG.md/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/CHANGELOG.md", "repo_id": "packages", "token_count": 404 }
1,085
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'messages.g.dart'; /// The iOS and macOS implementation of [PathProviderPlatform]. class PathProviderFoundation extends PathProviderPlatform { /// Constructor that accepts a testable PathProviderPlatformProvider. PathProviderFoundation({ @visibleForTesting PathProviderPlatformProvider? platform, }) : _platformProvider = platform ?? PathProviderPlatformProvider(); final PathProviderPlatformProvider _platformProvider; final PathProviderApi _pathProvider = PathProviderApi(); /// Registers this class as the default instance of [PathProviderPlatform] static void registerWith() { PathProviderPlatform.instance = PathProviderFoundation(); } @override Future<String?> getTemporaryPath() { return _pathProvider.getDirectoryPath(DirectoryType.temp); } @override Future<String?> getApplicationSupportPath() async { final String? path = await _pathProvider.getDirectoryPath(DirectoryType.applicationSupport); if (path != null) { // Ensure the directory exists before returning it, for consistency with // other platforms. await Directory(path).create(recursive: true); } return path; } @override Future<String?> getLibraryPath() { return _pathProvider.getDirectoryPath(DirectoryType.library); } @override Future<String?> getApplicationDocumentsPath() { return _pathProvider.getDirectoryPath(DirectoryType.applicationDocuments); } @override Future<String?> getApplicationCachePath() async { final String? path = await _pathProvider.getDirectoryPath(DirectoryType.applicationCache); if (path != null) { // Ensure the directory exists before returning it, for consistency with // other platforms. await Directory(path).create(recursive: true); } return path; } @override Future<String?> getExternalStoragePath() async { throw UnsupportedError( 'getExternalStoragePath is not supported on this platform'); } @override Future<List<String>?> getExternalCachePaths() async { throw UnsupportedError( 'getExternalCachePaths is not supported on this platform'); } @override Future<List<String>?> getExternalStoragePaths({ StorageDirectory? type, }) async { throw UnsupportedError( 'getExternalStoragePaths is not supported on this platform'); } @override Future<String?> getDownloadsPath() { return _pathProvider.getDirectoryPath(DirectoryType.downloads); } /// Returns the path to the container of the specified App Group. /// This is only supported for iOS. Future<String?> getContainerPath({required String appGroupIdentifier}) async { if (!_platformProvider.isIOS) { throw UnsupportedError( 'getContainerPath is not supported on this platform'); } return _pathProvider.getContainerPath(appGroupIdentifier); } } /// Helper class for returning information about the current platform. @visibleForTesting class PathProviderPlatformProvider { /// Specifies whether the current platform is iOS. bool get isIOS => Platform.isIOS; }
packages/packages/path_provider/path_provider_foundation/lib/path_provider_foundation.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/lib/path_provider_foundation.dart", "repo_id": "packages", "token_count": 1001 }
1,086
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path_provider_linux/path_provider_linux.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('getTemporaryDirectory', (WidgetTester tester) async { final PathProviderLinux provider = PathProviderLinux(); final String? result = await provider.getTemporaryPath(); _verifySampleFile(result, 'temporaryDirectory'); }); testWidgets('getDownloadDirectory', (WidgetTester tester) async { if (!Platform.isLinux) { return; } final PathProviderLinux provider = PathProviderLinux(); final String? result = await provider.getDownloadsPath(); _verifySampleFile(result, 'downloadDirectory'); }); testWidgets('getApplicationDocumentsDirectory', (WidgetTester tester) async { final PathProviderLinux provider = PathProviderLinux(); final String? result = await provider.getApplicationDocumentsPath(); _verifySampleFile(result, 'applicationDocuments'); }); testWidgets('getApplicationSupportDirectory', (WidgetTester tester) async { final PathProviderLinux provider = PathProviderLinux(); final String? result = await provider.getApplicationSupportPath(); _verifySampleFile(result, 'applicationSupport'); }); testWidgets('getApplicationCacheDirectory', (WidgetTester tester) async { final PathProviderLinux provider = PathProviderLinux(); final String? result = await provider.getApplicationCachePath(); _verifySampleFile(result, 'applicationCache'); }); } /// Verify a file called [name] in [directoryPath] by recreating it with test /// contents when necessary. void _verifySampleFile(String? directoryPath, String name) { expect(directoryPath, isNotNull); if (directoryPath == null) { return; } final Directory directory = Directory(directoryPath); final File file = File('${directory.path}${Platform.pathSeparator}$name'); if (file.existsSync()) { file.deleteSync(); expect(file.existsSync(), isFalse); } file.writeAsStringSync('Hello world!'); expect(file.readAsStringSync(), 'Hello world!'); expect(directory.listSync(), isNotEmpty); file.deleteSync(); }
packages/packages/path_provider/path_provider_linux/example/integration_test/path_provider_test.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_linux/example/integration_test/path_provider_test.dart", "repo_id": "packages", "token_count": 710 }
1,087
name: path_provider_linux description: Linux implementation of the path_provider plugin repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_linux issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 version: 2.2.1 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: path_provider platforms: linux: dartPluginClass: PathProviderLinux dependencies: ffi: ">=1.1.2 <3.0.0" flutter: sdk: flutter path: ^1.8.0 path_provider_platform_interface: ^2.1.0 xdg_directories: ">=0.2.0 <2.0.0" dev_dependencies: flutter_test: sdk: flutter topics: - files - path-provider - paths
packages/packages/path_provider/path_provider_linux/pubspec.yaml/0
{ "file_path": "packages/packages/path_provider/path_provider_linux/pubspec.yaml", "repo_id": "packages", "token_count": 323 }
1,088
name: path_provider_windows description: Windows implementation of the path_provider plugin repository: https://github.com/flutter/packages/tree/main/packages/path_provider/path_provider_windows issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+path_provider%22 version: 2.2.1 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: path_provider platforms: windows: dartPluginClass: PathProviderWindows dependencies: ffi: ^2.0.0 flutter: sdk: flutter path: ^1.8.0 path_provider_platform_interface: ^2.1.0 win32: ">=2.1.0 <6.0.0" dev_dependencies: flutter_test: sdk: flutter topics: - files - path-provider - paths
packages/packages/path_provider/path_provider_windows/pubspec.yaml/0
{ "file_path": "packages/packages/path_provider/path_provider_windows/pubspec.yaml", "repo_id": "packages", "token_count": 310 }
1,089
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #else #error("Unsupported platform.") #endif private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: Any) -> [Any?] { if let flutterError = error as? FlutterError { return [ flutterError.code, flutterError.message, flutterError.details, ] } return [ "\(error)", "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } private func createConnectionError(withChannelName channelName: String) -> FlutterError { return FlutterError( code: "channel-error", message: "Unable to establish connection on channel: '\(channelName)'.", details: "") } private func isNullish(_ value: Any?) -> Bool { return value is NSNull || value == nil } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return value as! T? } enum Code: Int { case one = 0 case two = 1 } /// Generated class from Pigeon that represents data sent in messages. struct MessageData { var name: String? = nil var description: String? = nil var code: Code var data: [String?: String?] static func fromList(_ list: [Any?]) -> MessageData? { let name: String? = nilOrValue(list[0]) let description: String? = nilOrValue(list[1]) let code = Code(rawValue: list[2] as! Int)! let data = list[3] as! [String?: String?] return MessageData( name: name, description: description, code: code, data: data ) } func toList() -> [Any?] { return [ name, description, code.rawValue, data, ] } } private class ExampleHostApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: return MessageData.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } } } private class ExampleHostApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { if let value = value as? MessageData { super.writeByte(128) super.writeValue(value.toList()) } else { super.writeValue(value) } } } private class ExampleHostApiCodecReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { return ExampleHostApiCodecReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { return ExampleHostApiCodecWriter(data: data) } } class ExampleHostApiCodec: FlutterStandardMessageCodec { static let shared = ExampleHostApiCodec(readerWriter: ExampleHostApiCodecReaderWriter()) } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol ExampleHostApi { func getHostLanguage() throws -> String func add(_ a: Int64, to b: Int64) throws -> Int64 func sendMessage(message: MessageData, completion: @escaping (Result<Bool, Error>) -> Void) } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class ExampleHostApiSetup { /// The codec used by ExampleHostApi. static var codec: FlutterStandardMessageCodec { ExampleHostApiCodec.shared } /// Sets up an instance of `ExampleHostApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: ExampleHostApi?) { let getHostLanguageChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage", binaryMessenger: binaryMessenger, codec: codec) if let api = api { getHostLanguageChannel.setMessageHandler { _, reply in do { let result = try api.getHostLanguage() reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { getHostLanguageChannel.setMessageHandler(nil) } let addChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add", binaryMessenger: binaryMessenger, codec: codec) if let api = api { addChannel.setMessageHandler { message, reply in let args = message as! [Any?] let aArg = args[0] is Int64 ? args[0] as! Int64 : Int64(args[0] as! Int32) let bArg = args[1] is Int64 ? args[1] as! Int64 : Int64(args[1] as! Int32) do { let result = try api.add(aArg, to: bArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { addChannel.setMessageHandler(nil) } let sendMessageChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage", binaryMessenger: binaryMessenger, codec: codec) if let api = api { sendMessageChannel.setMessageHandler { message, reply in let args = message as! [Any?] let messageArg = args[0] as! MessageData api.sendMessage(message: messageArg) { result in switch result { case .success(let res): reply(wrapResult(res)) case .failure(let error): reply(wrapError(error)) } } } } else { sendMessageChannel.setMessageHandler(nil) } } } /// Generated protocol from Pigeon that represents Flutter messages that can be called from Swift. protocol MessageFlutterApiProtocol { func flutterMethod( aString aStringArg: String?, completion: @escaping (Result<String, FlutterError>) -> Void) } class MessageFlutterApi: MessageFlutterApiProtocol { private let binaryMessenger: FlutterBinaryMessenger init(binaryMessenger: FlutterBinaryMessenger) { self.binaryMessenger = binaryMessenger } func flutterMethod( aString aStringArg: String?, completion: @escaping (Result<String, FlutterError>) -> Void ) { let channelName: String = "dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod" let channel = FlutterBasicMessageChannel(name: channelName, binaryMessenger: binaryMessenger) channel.sendMessage([aStringArg] as [Any?]) { response in guard let listResponse = response as? [Any?] else { completion(.failure(createConnectionError(withChannelName: channelName))) return } if listResponse.count > 1 { let code: String = listResponse[0] as! String let message: String? = nilOrValue(listResponse[1]) let details: String? = nilOrValue(listResponse[2]) completion(.failure(FlutterError(code: code, message: message, details: details))) } else if listResponse[0] == nil { completion( .failure( FlutterError( code: "null-error", message: "Flutter api returned null value for non-null return value.", details: ""))) } else { let result = listResponse[0] as! String completion(.success(result)) } } } }
packages/packages/pigeon/example/app/ios/Runner/Messages.g.swift/0
{ "file_path": "packages/packages/pigeon/example/app/ios/Runner/Messages.g.swift", "repo_id": "packages", "token_count": 2684 }
1,090
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon #import "messages.g.h" #if TARGET_OS_OSX #import <FlutterMacOS/FlutterMacOS.h> #else #import <Flutter/Flutter.h> #endif #if !__has_feature(objc_arc) #error File requires ARC to be enabled. #endif static NSArray *wrapResult(id result, FlutterError *error) { if (error) { return @[ error.code ?: [NSNull null], error.message ?: [NSNull null], error.details ?: [NSNull null] ]; } return @[ result ?: [NSNull null] ]; } static FlutterError *createConnectionError(NSString *channelName) { return [FlutterError errorWithCode:@"channel-error" message:[NSString stringWithFormat:@"%@/%@/%@", @"Unable to establish connection on channel: '", channelName, @"'."] details:@""]; } static id GetNullableObjectAtIndex(NSArray *array, NSInteger key) { id result = array[key]; return (result == [NSNull null]) ? nil : result; } @implementation PGNCodeBox - (instancetype)initWithValue:(PGNCode)value { self = [super init]; if (self) { _value = value; } return self; } @end @interface PGNMessageData () + (PGNMessageData *)fromList:(NSArray *)list; + (nullable PGNMessageData *)nullableFromList:(NSArray *)list; - (NSArray *)toList; @end @implementation PGNMessageData + (instancetype)makeWithName:(nullable NSString *)name description:(nullable NSString *)description code:(PGNCode)code data:(NSDictionary<NSString *, NSString *> *)data { PGNMessageData *pigeonResult = [[PGNMessageData alloc] init]; pigeonResult.name = name; pigeonResult.description = description; pigeonResult.code = code; pigeonResult.data = data; return pigeonResult; } + (PGNMessageData *)fromList:(NSArray *)list { PGNMessageData *pigeonResult = [[PGNMessageData alloc] init]; pigeonResult.name = GetNullableObjectAtIndex(list, 0); pigeonResult.description = GetNullableObjectAtIndex(list, 1); pigeonResult.code = [GetNullableObjectAtIndex(list, 2) integerValue]; pigeonResult.data = GetNullableObjectAtIndex(list, 3); return pigeonResult; } + (nullable PGNMessageData *)nullableFromList:(NSArray *)list { return (list) ? [PGNMessageData fromList:list] : nil; } - (NSArray *)toList { return @[ self.name ?: [NSNull null], self.description ?: [NSNull null], @(self.code), self.data ?: [NSNull null], ]; } @end @interface PGNExampleHostApiCodecReader : FlutterStandardReader @end @implementation PGNExampleHostApiCodecReader - (nullable id)readValueOfType:(UInt8)type { switch (type) { case 128: return [PGNMessageData fromList:[self readValue]]; default: return [super readValueOfType:type]; } } @end @interface PGNExampleHostApiCodecWriter : FlutterStandardWriter @end @implementation PGNExampleHostApiCodecWriter - (void)writeValue:(id)value { if ([value isKindOfClass:[PGNMessageData class]]) { [self writeByte:128]; [self writeValue:[value toList]]; } else { [super writeValue:value]; } } @end @interface PGNExampleHostApiCodecReaderWriter : FlutterStandardReaderWriter @end @implementation PGNExampleHostApiCodecReaderWriter - (FlutterStandardWriter *)writerWithData:(NSMutableData *)data { return [[PGNExampleHostApiCodecWriter alloc] initWithData:data]; } - (FlutterStandardReader *)readerWithData:(NSData *)data { return [[PGNExampleHostApiCodecReader alloc] initWithData:data]; } @end NSObject<FlutterMessageCodec> *PGNExampleHostApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; static dispatch_once_t sPred = 0; dispatch_once(&sPred, ^{ PGNExampleHostApiCodecReaderWriter *readerWriter = [[PGNExampleHostApiCodecReaderWriter alloc] init]; sSharedObject = [FlutterStandardMessageCodec codecWithReaderWriter:readerWriter]; }); return sSharedObject; } void SetUpPGNExampleHostApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<PGNExampleHostApi> *api) { { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.getHostLanguage" binaryMessenger:binaryMessenger codec:PGNExampleHostApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(getHostLanguageWithError:)], @"PGNExampleHostApi api (%@) doesn't respond to @selector(getHostLanguageWithError:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { FlutterError *error; NSString *output = [api getHostLanguageWithError:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.add" binaryMessenger:binaryMessenger codec:PGNExampleHostApiGetCodec()]; if (api) { NSCAssert( [api respondsToSelector:@selector(addNumber:toNumber:error:)], @"PGNExampleHostApi api (%@) doesn't respond to @selector(addNumber:toNumber:error:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; NSInteger arg_a = [GetNullableObjectAtIndex(args, 0) integerValue]; NSInteger arg_b = [GetNullableObjectAtIndex(args, 1) integerValue]; FlutterError *error; NSNumber *output = [api addNumber:arg_a toNumber:arg_b error:&error]; callback(wrapResult(output, error)); }]; } else { [channel setMessageHandler:nil]; } } { FlutterBasicMessageChannel *channel = [[FlutterBasicMessageChannel alloc] initWithName:@"dev.flutter.pigeon.pigeon_example_package.ExampleHostApi.sendMessage" binaryMessenger:binaryMessenger codec:PGNExampleHostApiGetCodec()]; if (api) { NSCAssert([api respondsToSelector:@selector(sendMessageMessage:completion:)], @"PGNExampleHostApi api (%@) doesn't respond to " @"@selector(sendMessageMessage:completion:)", api); [channel setMessageHandler:^(id _Nullable message, FlutterReply callback) { NSArray *args = message; PGNMessageData *arg_message = GetNullableObjectAtIndex(args, 0); [api sendMessageMessage:arg_message completion:^(NSNumber *_Nullable output, FlutterError *_Nullable error) { callback(wrapResult(output, error)); }]; }]; } else { [channel setMessageHandler:nil]; } } } NSObject<FlutterMessageCodec> *PGNMessageFlutterApiGetCodec(void) { static FlutterStandardMessageCodec *sSharedObject = nil; sSharedObject = [FlutterStandardMessageCodec sharedInstance]; return sSharedObject; } @interface PGNMessageFlutterApi () @property(nonatomic, strong) NSObject<FlutterBinaryMessenger> *binaryMessenger; @end @implementation PGNMessageFlutterApi - (instancetype)initWithBinaryMessenger:(NSObject<FlutterBinaryMessenger> *)binaryMessenger { self = [super init]; if (self) { _binaryMessenger = binaryMessenger; } return self; } - (void)flutterMethodAString:(nullable NSString *)arg_aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { NSString *channelName = @"dev.flutter.pigeon.pigeon_example_package.MessageFlutterApi.flutterMethod"; FlutterBasicMessageChannel *channel = [FlutterBasicMessageChannel messageChannelWithName:channelName binaryMessenger:self.binaryMessenger codec:PGNMessageFlutterApiGetCodec()]; [channel sendMessage:@[ arg_aString ?: [NSNull null] ] reply:^(NSArray<id> *reply) { if (reply != nil) { if (reply.count > 1) { completion(nil, [FlutterError errorWithCode:reply[0] message:reply[1] details:reply[2]]); } else { NSString *output = reply[0] == [NSNull null] ? nil : reply[0]; completion(output, nil); } } else { completion(nil, createConnectionError(channelName)); } }]; } @end
packages/packages/pigeon/example/app/macos/Runner/messages.g.m/0
{ "file_path": "packages/packages/pigeon/example/app/macos/Runner/messages.g.m", "repo_id": "packages", "token_count": 3739 }
1,091
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'dart:mirrors'; import 'package:yaml/yaml.dart' as yaml; import 'ast.dart'; /// The current version of pigeon. /// /// This must match the version in pubspec.yaml. const String pigeonVersion = '17.2.0'; /// Read all the content from [stdin] to a String. String readStdin() { final List<int> bytes = <int>[]; int byte = stdin.readByteSync(); while (byte >= 0) { bytes.add(byte); byte = stdin.readByteSync(); } return utf8.decode(bytes); } /// True if the generator line number should be printed out at the end of newlines. bool debugGenerators = false; /// A helper class for managing indentation, wrapping a [StringSink]. class Indent { /// Constructor which takes a [StringSink] [Ident] will wrap. Indent(this._sink); int _count = 0; final StringSink _sink; /// String used for newlines (ex "\n"). String get newline { if (debugGenerators) { final List<String> frames = StackTrace.current.toString().split('\n'); return ' //${frames.firstWhere((String x) => x.contains('_generator.dart'))}\n'; } else { return '\n'; } } /// String used to represent a tab. final String tab = ' '; /// Increase the indentation level. void inc([int level = 1]) { _count += level; } /// Decrement the indentation level. void dec([int level = 1]) { _count -= level; } /// Returns the String representing the current indentation. String str() { String result = ''; for (int i = 0; i < _count; i++) { result += tab; } return result; } /// Replaces the newlines and tabs of input and adds it to the stream. void format(String input, {bool leadingSpace = true, bool trailingNewline = true}) { final List<String> lines = input.split('\n'); for (int i = 0; i < lines.length; ++i) { final String line = lines[i]; if (i == 0 && !leadingSpace) { add(line.replaceAll('\t', tab)); } else if (line.isNotEmpty) { write(line.replaceAll('\t', tab)); } if (trailingNewline || i < lines.length - 1) { addln(''); } } } /// Scoped increase of the indent level. /// /// For the execution of [func] the indentation will be incremented. void addScoped( String? begin, String? end, Function func, { bool addTrailingNewline = true, int nestCount = 1, }) { assert(begin != '' || end != '', 'Use nest for indentation without any decoration'); if (begin != null) { _sink.write(begin + newline); } nest(nestCount, func); if (end != null) { _sink.write(str() + end); if (addTrailingNewline) { _sink.write(newline); } } } /// Like `addScoped` but writes the current indentation level. void writeScoped( String? begin, String end, Function func, { bool addTrailingNewline = true, }) { assert(begin != '' || end != '', 'Use nest for indentation without any decoration'); addScoped(str() + (begin ?? ''), end, func, addTrailingNewline: addTrailingNewline); } /// Scoped increase of the indent level. /// /// For the execution of [func] the indentation will be incremented by the given amount. void nest(int count, Function func) { inc(count); func(); // ignore: avoid_dynamic_calls dec(count); } /// Add [text] with indentation and a newline. void writeln(String text) { if (text.isEmpty) { _sink.write(newline); } else { _sink.write(str() + text + newline); } } /// Add [text] with indentation. void write(String text) { _sink.write(str() + text); } /// Add [text] with a newline. void addln(String text) { _sink.write(text + newline); } /// Just adds [text]. void add(String text) { _sink.write(text); } /// Adds [lines] number of newlines. void newln([int lines = 1]) { for (; lines > 0; lines--) { _sink.write(newline); } } } /// Create the generated channel name for a [method] on an [api]. String makeChannelName(Api api, Method method, String dartPackageName) { return makeChannelNameWithStrings( apiName: api.name, methodName: method.name, dartPackageName: dartPackageName, ); } /// Create the generated channel name for a method on an api. String makeChannelNameWithStrings({ required String apiName, required String methodName, required String dartPackageName, }) { return 'dev.flutter.pigeon.$dartPackageName.$apiName.$methodName'; } // TODO(tarrinneal): Determine whether HostDataType is needed. /// Represents the mapping of a Dart datatype to a Host datatype. class HostDatatype { /// Parametric constructor for HostDatatype. HostDatatype({ required this.datatype, required this.isBuiltin, required this.isNullable, required this.isEnum, }); /// The [String] that can be printed into host code to represent the type. final String datatype; /// `true` if the host datatype is something builtin. final bool isBuiltin; /// `true` if the type corresponds to a nullable Dart datatype. final bool isNullable; /// `true if the type is a custom enum. final bool isEnum; } /// Calculates the [HostDatatype] for the provided [NamedType]. /// /// It will check the field against [classes], the list of custom classes, to /// check if it is a builtin type. [builtinResolver] will return the host /// datatype for the Dart datatype for builtin types. /// /// [customResolver] can modify the datatype of custom types. HostDatatype getFieldHostDatatype( NamedType field, String? Function(TypeDeclaration) builtinResolver, {String Function(String)? customResolver}) { return _getHostDatatype(field.type, builtinResolver, customResolver: customResolver, fieldName: field.name); } /// Calculates the [HostDatatype] for the provided [TypeDeclaration]. /// /// It will check the field against [classes], the list of custom classes, to /// check if it is a builtin type. [builtinResolver] will return the host /// datatype for the Dart datatype for builtin types. /// /// [customResolver] can modify the datatype of custom types. HostDatatype getHostDatatype( TypeDeclaration type, String? Function(TypeDeclaration) builtinResolver, {String Function(String)? customResolver}) { return _getHostDatatype(type, builtinResolver, customResolver: customResolver); } HostDatatype _getHostDatatype( TypeDeclaration type, String? Function(TypeDeclaration) builtinResolver, {String Function(String)? customResolver, String? fieldName}) { final String? datatype = builtinResolver(type); if (datatype == null) { if (type.isClass) { final String customName = customResolver != null ? customResolver(type.baseName) : type.baseName; return HostDatatype( datatype: customName, isBuiltin: false, isNullable: type.isNullable, isEnum: false, ); } else if (type.isEnum) { final String customName = customResolver != null ? customResolver(type.baseName) : type.baseName; return HostDatatype( datatype: customName, isBuiltin: false, isNullable: type.isNullable, isEnum: true, ); } else { throw Exception( 'unrecognized datatype ${fieldName == null ? '' : 'for field:"$fieldName" '}of type:"${type.baseName}"'); } } else { return HostDatatype( datatype: datatype, isBuiltin: true, isNullable: type.isNullable, isEnum: false, ); } } /// Whether or not to include the version in the generated warning. /// /// This is a global rather than an option because it's only intended to be /// used internally, to avoid churn in Pigeon test files. bool includeVersionInGeneratedWarning = true; /// Warning printed at the top of all generated code. @Deprecated('Use getGeneratedCodeWarning() instead') const String generatedCodeWarning = 'Autogenerated from Pigeon (v$pigeonVersion), do not edit directly.'; /// Warning printed at the top of all generated code. String getGeneratedCodeWarning() { final String versionString = includeVersionInGeneratedWarning ? ' (v$pigeonVersion)' : ''; return 'Autogenerated from Pigeon$versionString, do not edit directly.'; } /// String to be printed after `getGeneratedCodeWarning()'s warning`. const String seeAlsoWarning = 'See also: https://pub.dev/packages/pigeon'; /// Prefix for utility classes generated for ProxyApis. /// /// This lowers the chances of variable name collisions with user defined /// parameters. const String classNamePrefix = 'Pigeon'; /// Name for the generated InstanceManager for ProxyApis. /// /// This lowers the chances of variable name collisions with user defined /// parameters. const String instanceManagerClassName = '${classNamePrefix}InstanceManager'; /// Prefix for class member names not defined by the user. /// /// This lowers the chances of variable name collisions with user defined /// parameters. const String classMemberNamePrefix = 'pigeon_'; /// Collection of keys used in dictionaries across generators. class Keys { /// The key in the result hash for the 'result' value. static const String result = 'result'; /// The key in the result hash for the 'error' value. static const String error = 'error'; /// The key in an error hash for the 'code' value. static const String errorCode = 'code'; /// The key in an error hash for the 'message' value. static const String errorMessage = 'message'; /// The key in an error hash for the 'details' value. static const String errorDetails = 'details'; } /// Returns true if `type` represents 'void'. bool isVoid(TypeMirror type) { return MirrorSystem.getName(type.simpleName) == 'void'; } /// Adds the [lines] to [indent]. void addLines(Indent indent, Iterable<String> lines, {String? linePrefix}) { final String prefix = linePrefix ?? ''; for (final String line in lines) { indent.writeln(line.isNotEmpty ? '$prefix$line' : prefix.trimRight()); } } /// Recursively merges [modification] into [base]. /// /// In other words, whenever there is a conflict over the value of a key path, /// [modification]'s value for that key path is selected. Map<String, Object> mergeMaps( Map<String, Object> base, Map<String, Object> modification, ) { final Map<String, Object> result = <String, Object>{}; for (final MapEntry<String, Object> entry in modification.entries) { if (base.containsKey(entry.key)) { final Object entryValue = entry.value; if (entryValue is Map<String, Object>) { assert(base[entry.key] is Map<String, Object>); result[entry.key] = mergeMaps((base[entry.key] as Map<String, Object>?)!, entryValue); } else { result[entry.key] = entry.value; } } else { result[entry.key] = entry.value; } } for (final MapEntry<String, Object> entry in base.entries) { if (!result.containsKey(entry.key)) { result[entry.key] = entry.value; } } return result; } /// A class name that is enumerated. class EnumeratedClass { /// Constructor. EnumeratedClass(this.name, this.enumeration); /// The name of the class. final String name; /// The enumeration of the class. final int enumeration; } /// Supported basic datatypes. const List<String> validTypes = <String>[ 'String', 'bool', 'int', 'double', 'Uint8List', 'Int32List', 'Int64List', 'Float64List', 'List', 'Map', 'Object', ]; /// Custom codecs' custom types are enumerated from 255 down to this number to /// avoid collisions with the StandardMessageCodec. const int _minimumCodecFieldKey = 128; Iterable<TypeDeclaration> _getTypeArguments(TypeDeclaration type) sync* { for (final TypeDeclaration typeArg in type.typeArguments) { yield* _getTypeArguments(typeArg); } yield type; } bool _isUnseenCustomType( TypeDeclaration type, Set<String> referencedTypeNames) { return !referencedTypeNames.contains(type.baseName) && !validTypes.contains(type.baseName); } class _Bag<Key, Value> { Map<Key, List<Value>> map = <Key, List<Value>>{}; void add(Key key, Value? value) { if (!map.containsKey(key)) { map[key] = value == null ? <Value>[] : <Value>[value]; } else { if (value != null) { map[key]!.add(value); } } } void addMany(Iterable<Key> keys, Value? value) { for (final Key key in keys) { add(key, value); } } } /// Recurses into a list of [Api]s and produces a list of all referenced types /// and an associated [List] of the offsets where they are found. Map<TypeDeclaration, List<int>> getReferencedTypes( List<Api> apis, List<Class> classes) { final _Bag<TypeDeclaration, int> references = _Bag<TypeDeclaration, int>(); for (final Api api in apis) { for (final Method method in api.methods) { for (final NamedType field in method.parameters) { references.addMany(_getTypeArguments(field.type), field.offset); } references.addMany(_getTypeArguments(method.returnType), method.offset); } if (api is AstProxyApi) { for (final Constructor constructor in api.constructors) { for (final NamedType parameter in constructor.parameters) { references.addMany( _getTypeArguments(parameter.type), parameter.offset, ); } } for (final ApiField field in api.fields) { references.addMany(_getTypeArguments(field.type), field.offset); } } } final Set<String> referencedTypeNames = references.map.keys.map((TypeDeclaration e) => e.baseName).toSet(); final List<String> classesToCheck = List<String>.from(referencedTypeNames); while (classesToCheck.isNotEmpty) { final String next = classesToCheck.removeLast(); final Class aClass = classes.firstWhere((Class x) => x.name == next, orElse: () => Class(name: '', fields: <NamedType>[])); for (final NamedType field in aClass.fields) { if (_isUnseenCustomType(field.type, referencedTypeNames)) { references.add(field.type, field.offset); classesToCheck.add(field.type.baseName); } for (final TypeDeclaration typeArg in field.type.typeArguments) { if (_isUnseenCustomType(typeArg, referencedTypeNames)) { references.add(typeArg, field.offset); classesToCheck.add(typeArg.baseName); } } } } return references.map; } /// Returns true if the concrete type cannot be determined at compile-time. bool _isConcreteTypeAmbiguous(TypeDeclaration type) { return (type.baseName == 'List' && type.typeArguments.isEmpty) || (type.baseName == 'Map' && type.typeArguments.isEmpty) || type.baseName == 'Object'; } /// Given an [Api], return the enumerated classes that must exist in the codec /// where the enumeration should be the key used in the buffer. Iterable<EnumeratedClass> getCodecClasses(Api api, Root root) sync* { final Set<String> enumNames = root.enums.map((Enum e) => e.name).toSet(); final Map<TypeDeclaration, List<int>> referencedTypes = getReferencedTypes(<Api>[api], root.classes); final Iterable<String> allTypeNames = referencedTypes.keys.any(_isConcreteTypeAmbiguous) ? root.classes.map((Class aClass) => aClass.name) : referencedTypes.keys.map((TypeDeclaration e) => e.baseName); final List<String> sortedNames = allTypeNames .where((String element) => element != 'void' && !validTypes.contains(element) && !enumNames.contains(element)) .toList(); sortedNames.sort(); int enumeration = _minimumCodecFieldKey; const int maxCustomClassesPerApi = 255 - _minimumCodecFieldKey; if (sortedNames.length > maxCustomClassesPerApi) { throw Exception( "Pigeon doesn't support more than $maxCustomClassesPerApi referenced custom classes per API, try splitting up your APIs."); } for (final String name in sortedNames) { yield EnumeratedClass(name, enumeration); enumeration += 1; } } /// Describes how to format a document comment. class DocumentCommentSpecification { /// Constructor for [DocumentationCommentSpecification] const DocumentCommentSpecification( this.openCommentToken, { this.closeCommentToken = '', this.blockContinuationToken = '', }); /// Token that represents the open symbol for a documentation comment. final String openCommentToken; /// Token that represents the closing symbol for a documentation comment. final String closeCommentToken; /// Token that represents the continuation symbol for a block of documentation comments. final String blockContinuationToken; } /// Formats documentation comments and adds them to current Indent. /// /// The [comments] list is meant for comments written in the input dart file. /// The [generatorComments] list is meant for comments added by the generators. /// Include white space for all tokens when called, no assumptions are made. void addDocumentationComments( Indent indent, List<String> comments, DocumentCommentSpecification commentSpec, { List<String> generatorComments = const <String>[], }) { asDocumentationComments( comments, commentSpec, generatorComments: generatorComments, ).forEach(indent.writeln); } /// Formats documentation comments and adds them to current Indent. /// /// The [comments] list is meant for comments written in the input dart file. /// The [generatorComments] list is meant for comments added by the generators. /// Include white space for all tokens when called, no assumptions are made. Iterable<String> asDocumentationComments( Iterable<String> comments, DocumentCommentSpecification commentSpec, { List<String> generatorComments = const <String>[], }) sync* { final List<String> allComments = <String>[ ...comments, if (comments.isNotEmpty && generatorComments.isNotEmpty) '', ...generatorComments, ]; String currentLineOpenToken = commentSpec.openCommentToken; if (allComments.length > 1) { if (commentSpec.closeCommentToken != '') { yield commentSpec.openCommentToken; currentLineOpenToken = commentSpec.blockContinuationToken; } for (String line in allComments) { if (line.isNotEmpty && line[0] != ' ') { line = ' $line'; } yield '$currentLineOpenToken$line'; } if (commentSpec.closeCommentToken != '') { yield commentSpec.closeCommentToken; } } else if (allComments.length == 1) { yield '$currentLineOpenToken${allComments.first}${commentSpec.closeCommentToken}'; } } /// Returns an ordered list of fields to provide consistent serialization order. Iterable<NamedType> getFieldsInSerializationOrder(Class classDefinition) { // This returns the fields in the order they are declared in the pigeon file. return classDefinition.fields; } /// Crawls up the path of [dartFilePath] until it finds a pubspec.yaml in a /// parent directory and returns its path. String? _findPubspecPath(String dartFilePath) { try { Directory dir = File(dartFilePath).parent; String? pubspecPath; while (pubspecPath == null) { if (dir.existsSync()) { final Iterable<String> pubspecPaths = dir .listSync() .map((FileSystemEntity e) => e.path) .where((String path) => path.endsWith('pubspec.yaml')); if (pubspecPaths.isNotEmpty) { pubspecPath = pubspecPaths.first; } else { dir = dir.parent; } } else { break; } } return pubspecPath; } catch (ex) { return null; } } /// Given the path of a Dart file, [mainDartFile], the name of the package will /// be deduced by locating and parsing its associated pubspec.yaml. String? deducePackageName(String mainDartFile) { final String? pubspecPath = _findPubspecPath(mainDartFile); if (pubspecPath == null) { return null; } try { final String text = File(pubspecPath).readAsStringSync(); return (yaml.loadYaml(text) as Map<dynamic, dynamic>)['name'] as String?; } catch (_) { return null; } } /// Enum to specify api type when generating code. enum ApiType { /// Flutter api. flutter, /// Host api. host, } /// Enum to specify which file will be generated for multi-file generators enum FileType { /// header file. header, /// source file. source, /// file type is not applicable. na, } /// Options for [Generator]s that have multiple output file types. /// /// Specifies which file to write as well as wraps all language options. class OutputFileOptions<T> { /// Constructor. OutputFileOptions({required this.fileType, required this.languageOptions}); /// To specify which file type should be created. FileType fileType; /// Options for specified language across all file types. T languageOptions; }
packages/packages/pigeon/lib/generator_tools.dart/0
{ "file_path": "packages/packages/pigeon/lib/generator_tools.dart", "repo_id": "packages", "token_count": 7218 }
1,092
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is an example pigeon file that is used in compilation, unit, mock // handler, and e2e tests. import 'package:pigeon/pigeon.dart'; class NonNullFieldSearchRequest { NonNullFieldSearchRequest({required this.query}); String query; } class ExtraData { ExtraData({required this.detailA, required this.detailB}); String detailA; String detailB; } enum ReplyType { success, error } class NonNullFieldSearchReply { NonNullFieldSearchReply( this.result, this.error, this.indices, this.extraData, this.type); String result; String error; List<int?> indices; ExtraData extraData; ReplyType type; } @HostApi() abstract class NonNullFieldHostApi { NonNullFieldSearchReply search(NonNullFieldSearchRequest nested); } @FlutterApi() abstract class NonNullFieldFlutterApi { NonNullFieldSearchReply search(NonNullFieldSearchRequest request); }
packages/packages/pigeon/pigeons/non_null_fields.dart/0
{ "file_path": "packages/packages/pigeon/pigeons/non_null_fields.dart", "repo_id": "packages", "token_count": 316 }
1,093
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.alternate_language_test_plugin; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.example.alternate_language_test_plugin.CoreTests.AllNullableTypes; import com.example.alternate_language_test_plugin.CoreTests.AllTypes; import com.example.alternate_language_test_plugin.CoreTests.FlutterIntegrationCoreApi; import io.flutter.plugin.common.BinaryMessenger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import org.junit.Test; public class AllDatatypesTest { void compareAllTypes(AllTypes firstTypes, AllTypes secondTypes) { assertEquals(firstTypes == null, secondTypes == null); if (firstTypes == null || secondTypes == null) { return; } assertEquals(firstTypes.getABool(), secondTypes.getABool()); assertEquals(firstTypes.getAnInt(), secondTypes.getAnInt()); assertEquals(firstTypes.getAnInt64(), secondTypes.getAnInt64()); assertEquals(firstTypes.getADouble(), secondTypes.getADouble()); assertArrayEquals(firstTypes.getAByteArray(), secondTypes.getAByteArray()); assertArrayEquals(firstTypes.getA4ByteArray(), secondTypes.getA4ByteArray()); assertArrayEquals(firstTypes.getA8ByteArray(), secondTypes.getA8ByteArray()); assertTrue(floatArraysEqual(firstTypes.getAFloatArray(), secondTypes.getAFloatArray())); assertArrayEquals(firstTypes.getAList().toArray(), secondTypes.getAList().toArray()); assertArrayEquals( firstTypes.getAMap().keySet().toArray(), secondTypes.getAMap().keySet().toArray()); assertArrayEquals( firstTypes.getAMap().values().toArray(), secondTypes.getAMap().values().toArray()); assertEquals(firstTypes.getAnEnum(), secondTypes.getAnEnum()); assertEquals(firstTypes.getAnObject(), secondTypes.getAnObject()); } void compareAllNullableTypes(AllNullableTypes firstTypes, AllNullableTypes secondTypes) { assertEquals(firstTypes == null, secondTypes == null); if (firstTypes == null || secondTypes == null) { return; } assertEquals(firstTypes.getANullableBool(), secondTypes.getANullableBool()); assertEquals(firstTypes.getANullableInt(), secondTypes.getANullableInt()); assertEquals(firstTypes.getANullableDouble(), secondTypes.getANullableDouble()); assertEquals(firstTypes.getANullableString(), secondTypes.getANullableString()); assertArrayEquals(firstTypes.getANullableByteArray(), secondTypes.getANullableByteArray()); assertArrayEquals(firstTypes.getANullable4ByteArray(), secondTypes.getANullable4ByteArray()); assertArrayEquals(firstTypes.getANullable8ByteArray(), secondTypes.getANullable8ByteArray()); assertTrue( floatArraysEqual( firstTypes.getANullableFloatArray(), secondTypes.getANullableFloatArray())); assertArrayEquals( firstTypes.getANullableList().toArray(), secondTypes.getANullableList().toArray()); assertArrayEquals( firstTypes.getANullableMap().keySet().toArray(), secondTypes.getANullableMap().keySet().toArray()); assertArrayEquals( firstTypes.getANullableMap().values().toArray(), secondTypes.getANullableMap().values().toArray()); assertArrayEquals( firstTypes.getNullableMapWithObject().values().toArray(), secondTypes.getNullableMapWithObject().values().toArray()); assertEquals(firstTypes.getANullableObject(), secondTypes.getANullableObject()); } @Test public void nullValues() { AllNullableTypes everything = new AllNullableTypes(); BinaryMessenger binaryMessenger = mock(BinaryMessenger.class); doAnswer( invocation -> { ByteBuffer message = invocation.getArgument(1); BinaryMessenger.BinaryReply reply = invocation.getArgument(2); message.position(0); @SuppressWarnings("unchecked") ArrayList<Object> args = (ArrayList<Object>) FlutterIntegrationCoreApi.getCodec().decodeMessage(message); ByteBuffer replyData = FlutterIntegrationCoreApi.getCodec().encodeMessage(args); replyData.position(0); reply.reply(replyData); return null; }) .when(binaryMessenger) .send(anyString(), any(), any()); FlutterIntegrationCoreApi api = new FlutterIntegrationCoreApi(binaryMessenger); boolean[] didCall = {false}; api.echoAllNullableTypes( everything, new CoreTests.NullableResult<AllNullableTypes>() { public void success(AllNullableTypes result) { didCall[0] = true; assertNull(everything.getANullableBool()); assertNull(everything.getANullableInt()); assertNull(everything.getANullableDouble()); assertNull(everything.getANullableString()); assertNull(everything.getANullableByteArray()); assertNull(everything.getANullable4ByteArray()); assertNull(everything.getANullable8ByteArray()); assertNull(everything.getANullableFloatArray()); assertNull(everything.getANullableList()); assertNull(everything.getANullableMap()); assertNull(everything.getNullableMapWithObject()); } public void error(Throwable error) { assertEquals(error, null); } }); assertTrue(didCall[0]); } private static HashMap<Object, Object> makeMap(String key, Integer value) { HashMap<Object, Object> result = new HashMap<Object, Object>(); result.put(key, value); return result; } private static HashMap<String, Object> makeStringMap(String key, Integer value) { HashMap<String, Object> result = new HashMap<String, Object>(); result.put(key, value); return result; } private static boolean floatArraysEqual(double[] x, double[] y) { if (x.length != y.length) { return false; } for (int i = 0; i < x.length; ++i) { if (x[i] != y[i]) { return false; } } return true; } @Test public void hasValues() { AllTypes allEverything = new AllTypes.Builder() .setABool(false) .setAnInt(1234L) .setAnInt64(4321L) .setADouble(2.0) .setAString("hello") .setAByteArray(new byte[] {1, 2, 3, 4}) .setA4ByteArray(new int[] {1, 2, 3, 4}) .setA8ByteArray(new long[] {1, 2, 3, 4}) .setAFloatArray(new double[] {0.5, 0.25, 1.5, 1.25}) .setAList(Arrays.asList(new int[] {1, 2, 3})) .setAMap(makeMap("hello", 1234)) .setAnEnum(CoreTests.AnEnum.ONE) .setAnObject(0) .build(); AllNullableTypes everything = new AllNullableTypes.Builder() .setANullableBool(false) .setANullableInt(1234L) .setANullableDouble(2.0) .setANullableString("hello") .setANullableByteArray(new byte[] {1, 2, 3, 4}) .setANullable4ByteArray(new int[] {1, 2, 3, 4}) .setANullable8ByteArray(new long[] {1, 2, 3, 4}) .setANullableFloatArray(new double[] {0.5, 0.25, 1.5, 1.25}) .setANullableList(Arrays.asList(new int[] {1, 2, 3})) .setANullableMap(makeMap("hello", 1234)) .setNullableMapWithObject(makeStringMap("hello", 1234)) .setANullableObject(0) .build(); BinaryMessenger binaryMessenger = mock(BinaryMessenger.class); doAnswer( invocation -> { ByteBuffer message = invocation.getArgument(1); BinaryMessenger.BinaryReply reply = invocation.getArgument(2); message.position(0); @SuppressWarnings("unchecked") ArrayList<Object> args = (ArrayList<Object>) FlutterIntegrationCoreApi.getCodec().decodeMessage(message); ByteBuffer replyData = FlutterIntegrationCoreApi.getCodec().encodeMessage(args); replyData.position(0); reply.reply(replyData); return null; }) .when(binaryMessenger) .send(anyString(), any(), any()); FlutterIntegrationCoreApi api = new FlutterIntegrationCoreApi(binaryMessenger); boolean[] didCall = {false}; api.echoAllNullableTypes( everything, new CoreTests.NullableResult<AllNullableTypes>() { public void success(AllNullableTypes result) { didCall[0] = true; compareAllNullableTypes(everything, result); } public void error(Throwable error) { assertEquals(error, null); } }); assertTrue(didCall[0]); } @Test public void integerToLong() { AllNullableTypes everything = new AllNullableTypes(); everything.setANullableInt(123L); ArrayList<Object> list = everything.toList(); assertNotNull(list); assertNull(list.get(0)); assertNotNull(list.get(1)); list.set(1, 123); AllNullableTypes readEverything = AllNullableTypes.fromList(list); assertEquals(readEverything.getANullableInt(), everything.getANullableInt()); } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AllDatatypesTest.java/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AllDatatypesTest.java", "repo_id": "packages", "token_count": 3824 }
1,094
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "MockBinaryMessenger.h" @implementation MockBinaryMessenger - (instancetype)initWithCodec:(NSObject<FlutterMessageCodec> *)codec { self = [super init]; if (self) { _codec = codec; _handlers = [[NSMutableDictionary alloc] init]; } return self; } - (void)cleanupConnection:(FlutterBinaryMessengerConnection)connection { } - (void)sendOnChannel:(nonnull NSString *)channel message:(NSData *_Nullable)message { } - (void)sendOnChannel:(nonnull NSString *)channel message:(NSData *_Nullable)message binaryReply:(FlutterBinaryReply _Nullable)callback { if (self.result) { callback([_codec encode:@[ self.result ]]); } } - (FlutterBinaryMessengerConnection)setMessageHandlerOnChannel:(nonnull NSString *)channel binaryMessageHandler: (FlutterBinaryMessageHandler _Nullable)handler { _handlers[channel] = [handler copy]; return _handlers.count; } - (void)cleanUpConnection:(FlutterBinaryMessengerConnection)connection { } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/MockBinaryMessenger.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/MockBinaryMessenger.m", "repo_id": "packages", "token_count": 471 }
1,095
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; PlatformException _createConnectionError(String channelName) { return PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel: "$channelName".', ); } List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } /// This comment is to test enum documentation comments. /// /// This comment also tests multiple line comments. /// /// //////////////////////// /// This comment also tests comments that start with '/' /// //////////////////////// enum MessageRequestState { pending, success, failure, } /// This comment is to test class documentation comments. /// /// This comment also tests multiple line comments. class MessageSearchRequest { MessageSearchRequest({ this.query, this.anInt, this.aBool, }); /// This comment is to test field documentation comments. String? query; /// This comment is to test field documentation comments. int? anInt; /// This comment is to test field documentation comments. bool? aBool; Object encode() { return <Object?>[ query, anInt, aBool, ]; } static MessageSearchRequest decode(Object result) { result as List<Object?>; return MessageSearchRequest( query: result[0] as String?, anInt: result[1] as int?, aBool: result[2] as bool?, ); } } /// This comment is to test class documentation comments. class MessageSearchReply { MessageSearchReply({ this.result, this.error, this.state, }); /// This comment is to test field documentation comments. /// /// This comment also tests multiple line comments. String? result; /// This comment is to test field documentation comments. String? error; /// This comment is to test field documentation comments. MessageRequestState? state; Object encode() { return <Object?>[ result, error, state?.index, ]; } static MessageSearchReply decode(Object result) { result as List<Object?>; return MessageSearchReply( result: result[0] as String?, error: result[1] as String?, state: result[2] != null ? MessageRequestState.values[result[2]! as int] : null, ); } } /// This comment is to test class documentation comments. class MessageNested { MessageNested({ this.request, }); /// This comment is to test field documentation comments. MessageSearchRequest? request; Object encode() { return <Object?>[ request?.encode(), ]; } static MessageNested decode(Object result) { result as List<Object?>; return MessageNested( request: result[0] != null ? MessageSearchRequest.decode(result[0]! as List<Object?>) : null, ); } } class _MessageApiCodec extends StandardMessageCodec { const _MessageApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MessageSearchReply) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is MessageSearchRequest) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MessageSearchReply.decode(readValue(buffer)!); case 129: return MessageSearchRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// This comment is to test api documentation comments. /// /// This comment also tests multiple line comments. class MessageApi { /// Constructor for [MessageApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. MessageApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = _MessageApiCodec(); /// This comment is to test documentation comments. /// /// This comment also tests multiple line comments. Future<void> initialize() async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.initialize'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(null) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else { return; } } /// This comment is to test method documentation comments. Future<MessageSearchReply> search(MessageSearchRequest request) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MessageApi.search'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[request]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as MessageSearchReply?)!; } } } class _MessageNestedApiCodec extends StandardMessageCodec { const _MessageNestedApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MessageNested) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is MessageSearchReply) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is MessageSearchRequest) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MessageNested.decode(readValue(buffer)!); case 129: return MessageSearchReply.decode(readValue(buffer)!); case 130: return MessageSearchRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// This comment is to test api documentation comments. class MessageNestedApi { /// Constructor for [MessageNestedApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. MessageNestedApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = _MessageNestedApiCodec(); /// This comment is to test method documentation comments. /// /// This comment also tests multiple line comments. Future<MessageSearchReply> search(MessageNested nested) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MessageNestedApi.search'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[nested]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as MessageSearchReply?)!; } } } class _MessageFlutterSearchApiCodec extends StandardMessageCodec { const _MessageFlutterSearchApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is MessageSearchReply) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is MessageSearchRequest) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return MessageSearchReply.decode(readValue(buffer)!); case 129: return MessageSearchRequest.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } /// This comment is to test api documentation comments. abstract class MessageFlutterSearchApi { static const MessageCodec<Object?> pigeonChannelCodec = _MessageFlutterSearchApiCodec(); /// This comment is to test method documentation comments. MessageSearchReply search(MessageSearchRequest request); static void setup(MessageFlutterSearchApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null.'); final List<Object?> args = (message as List<Object?>?)!; final MessageSearchRequest? arg_request = (args[0] as MessageSearchRequest?); assert(arg_request != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MessageFlutterSearchApi.search was null, expected non-null MessageSearchRequest.'); try { final MessageSearchReply output = api.search(arg_request!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/message.gen.dart", "repo_id": "packages", "token_count": 4538 }
1,096
// Mocks generated by Mockito 5.4.1 from annotations // in shared_test_plugin_code/test/null_safe_test.dart. // Do not manually edit this file. // @dart=2.19 // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'dart:typed_data' as _i4; import 'dart:ui' as _i5; import 'package:flutter/services.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; import 'package:shared_test_plugin_code/src/generated/nullable_returns.gen.dart' as _i6; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class /// A class which mocks [BinaryMessenger]. /// /// See the documentation for Mockito's code generation for more information. class MockBinaryMessenger extends _i1.Mock implements _i2.BinaryMessenger { MockBinaryMessenger() { _i1.throwOnMissingStub(this); } @override _i3.Future<void> handlePlatformMessage( String? channel, _i4.ByteData? data, _i5.PlatformMessageResponseCallback? callback, ) => (super.noSuchMethod( Invocation.method( #handlePlatformMessage, [ channel, data, callback, ], ), returnValue: _i3.Future<void>.value(), returnValueForMissingStub: _i3.Future<void>.value(), ) as _i3.Future<void>); @override _i3.Future<_i4.ByteData?>? send( String? channel, _i4.ByteData? message, ) => (super.noSuchMethod(Invocation.method( #send, [ channel, message, ], )) as _i3.Future<_i4.ByteData?>?); @override void setMessageHandler( String? channel, _i2.MessageHandler? handler, ) => super.noSuchMethod( Invocation.method( #setMessageHandler, [ channel, handler, ], ), returnValueForMissingStub: null, ); } /// A class which mocks [NullableArgFlutterApi]. /// /// See the documentation for Mockito's code generation for more information. class MockNullableArgFlutterApi extends _i1.Mock implements _i6.NullableArgFlutterApi { MockNullableArgFlutterApi() { _i1.throwOnMissingStub(this); } @override int doit(int? x) => (super.noSuchMethod( Invocation.method( #doit, [x], ), returnValue: 0, ) as int); } /// A class which mocks [NullableReturnFlutterApi]. /// /// See the documentation for Mockito's code generation for more information. class MockNullableReturnFlutterApi extends _i1.Mock implements _i6.NullableReturnFlutterApi { MockNullableReturnFlutterApi() { _i1.throwOnMissingStub(this); } } /// A class which mocks [NullableCollectionArgFlutterApi]. /// /// See the documentation for Mockito's code generation for more information. class MockNullableCollectionArgFlutterApi extends _i1.Mock implements _i6.NullableCollectionArgFlutterApi { MockNullableCollectionArgFlutterApi() { _i1.throwOnMissingStub(this); } @override List<String?> doit(List<String?>? x) => (super.noSuchMethod( Invocation.method( #doit, [x], ), returnValue: <String?>[], ) as List<String?>); } /// A class which mocks [NullableCollectionReturnFlutterApi]. /// /// See the documentation for Mockito's code generation for more information. class MockNullableCollectionReturnFlutterApi extends _i1.Mock implements _i6.NullableCollectionReturnFlutterApi { MockNullableCollectionReturnFlutterApi() { _i1.throwOnMissingStub(this); } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.mocks.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/null_safe_test.mocks.dart", "repo_id": "packages", "token_count": 1589 }
1,097
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package com.example.test_plugin import io.flutter.plugin.common.BinaryMessenger import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import java.nio.ByteBuffer import junit.framework.TestCase import org.junit.Test internal class AsyncHandlersTest : TestCase() { @Test fun testAsyncHost2Flutter() { val binaryMessenger = mockk<BinaryMessenger>() val api = FlutterIntegrationCoreApi(binaryMessenger) val value = "Test" every { binaryMessenger.send(any(), any(), any()) } answers { val codec = FlutterIntegrationCoreApi.codec val message = arg<ByteBuffer>(1) val reply = arg<BinaryMessenger.BinaryReply>(2) message.position(0) val replyData = codec.encodeMessage(listOf(value)) replyData?.position(0) reply.reply(replyData) } var didCall = false api.echoAsyncString(value) { didCall = true assertEquals(it.getOrNull(), value) } assertTrue(didCall) verify { binaryMessenger.send( "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi.echoAsyncString", any(), any()) } } @Test fun testAsyncFlutter2HostEcho() { val binaryMessenger = mockk<BinaryMessenger>() val api = mockk<HostSmallApi>() val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>() val input = "Test" val output = input val channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo" every { binaryMessenger.setMessageHandler( "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid", any()) } returns Unit every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit every { api.echo(any(), any()) } answers { val callback = arg<(Result<String>) -> Unit>(1) callback(Result.success(output)) } HostSmallApi.setUp(binaryMessenger, api) val codec = HostSmallApi.codec val message = codec.encodeMessage(listOf(input)) message?.rewind() handlerSlot.captured.onMessage(message) { assertNotNull(it) it?.rewind() @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as MutableList<Any>? assertNotNull(wrapped) wrapped?.let { assertEquals(output, wrapped.first()) } } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { api.echo(input, any()) } } @Test fun asyncFlutter2HostVoidVoid() { val binaryMessenger = mockk<BinaryMessenger>() val api = mockk<HostSmallApi>() val handlerSlot = slot<BinaryMessenger.BinaryMessageHandler>() val channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid" every { binaryMessenger.setMessageHandler(channelName, capture(handlerSlot)) } returns Unit every { binaryMessenger.setMessageHandler( "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo", any()) } returns Unit every { api.voidVoid(any()) } answers { val callback = arg<() -> Unit>(0) callback() } HostSmallApi.setUp(binaryMessenger, api) val codec = HostSmallApi.codec val message = codec.encodeMessage(null) handlerSlot.captured.onMessage(message) { it?.rewind() @Suppress("UNCHECKED_CAST") val wrapped = codec.decodeMessage(it) as MutableList<Any>? assertNull(wrapped) } verify { binaryMessenger.setMessageHandler(channelName, handlerSlot.captured) } verify { api.voidVoid(any()) } } }
packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AsyncHandlersTest.kt/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/AsyncHandlersTest.kt", "repo_id": "packages", "token_count": 1494 }
1,098
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Flutter import Foundation import XCTest @testable import test_plugin class RunnerTests: XCTestCase { func testToListAndBack() throws { let reply = MessageSearchReply(result: "foobar") let dict = reply.toList() let copy = MessageSearchReply.fromList(dict) XCTAssertEqual(reply.result, copy?.result) } func testHandlesNull() throws { let reply = MessageSearchReply() let dict = reply.toList() let copy = MessageSearchReply.fromList(dict) XCTAssertNil(copy?.result) } func testHandlesNullFirst() throws { let reply = MessageSearchReply(error: "foobar") let dict = reply.toList() let copy = MessageSearchReply.fromList(dict) XCTAssertEqual(reply.error, copy?.error) } /// This validates that pigeon clients can easily write tests that mock out Flutter API /// calls using a pigeon-generated protocol. func testEchoStringFromProtocol() throws { let api: FlutterApiFromProtocol = FlutterApiFromProtocol() let aString = "aString" api.echo(aString) { response in switch response { case .success(let res): XCTAssertEqual(aString, res) case .failure(let error): XCTFail(error.code) } } } } class FlutterApiFromProtocol: FlutterSmallApiProtocol { func echo(_ aStringArg: String, completion: @escaping (Result<String, FlutterError>) -> Void) { completion(.success(aStringArg)) } func echo( _ msgArg: test_plugin.TestMessage, completion: @escaping (Result<test_plugin.TestMessage, FlutterError>) -> Void ) { completion(.success(msgArg)) } }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/RunnerTests.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/RunnerTests.swift", "repo_id": "packages", "token_count": 612 }
1,099
name: test_plugin_example description: Pigeon test harness for primary plugin languages. publish_to: 'none' environment: sdk: ^3.1.0 dependencies: flutter: sdk: flutter shared_test_plugin_code: path: ../../shared_test_plugin_code test_plugin: path: ../ dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: true
packages/packages/pigeon/platform_tests/test_plugin/example/pubspec.yaml/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/pubspec.yaml", "repo_id": "packages", "token_count": 156 }
1,100
name: pigeon description: Code generator tool to make communication between Flutter and the host platform type-safe and easier. repository: https://github.com/flutter/packages/tree/main/packages/pigeon issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+pigeon%22 version: 17.2.0 # This must match the version in lib/generator_tools.dart environment: sdk: ^3.1.0 dependencies: analyzer: ">=5.13.0 <7.0.0" args: ^2.1.0 code_builder: ^4.10.0 collection: ^1.15.0 dart_style: ^2.3.4 meta: ^1.9.0 path: ^1.8.0 yaml: ^3.1.1 dev_dependencies: test: ^1.11.1 topics: - codegen - interop - platform-channels - plugin-development
packages/packages/pigeon/pubspec.yaml/0
{ "file_path": "packages/packages/pigeon/pubspec.yaml", "repo_id": "packages", "token_count": 285 }
1,101
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; String getFlutterCommand() => Platform.isWindows ? 'flutter.bat' : 'flutter'; /// Returns the first device listed by `flutter devices` that targets /// [platform], or null if there is no such device. Future<String?> getDeviceForPlatform(String platform) async { final ProcessResult result = await Process.run( getFlutterCommand(), <String>['devices', '--machine'], stdoutEncoding: utf8, ); if (result.exitCode != 0) { return null; } String output = result.stdout as String; // --machine doesn't currently prevent the tool from printing banners; // see https://github.com/flutter/flutter/issues/86055. This workaround // can be removed once that is fixed. output = output.substring(output.indexOf('[')); final List<Map<String, dynamic>> devices = (jsonDecode(output) as List<dynamic>).cast<Map<String, dynamic>>(); for (final Map<String, dynamic> deviceInfo in devices) { final String targetPlatform = (deviceInfo['targetPlatform'] as String?) ?? ''; if (targetPlatform.startsWith(platform)) { final String? deviceId = deviceInfo['id'] as String?; if (deviceId != null) { return deviceId; } } } return null; }
packages/packages/pigeon/tool/shared/flutter_utils.dart/0
{ "file_path": "packages/packages/pigeon/tool/shared/flutter_utils.dart", "repo_id": "packages", "token_count": 456 }
1,102
plugins { id "com.android.application" id "kotlin-android" id "dev.flutter.flutter-gradle-plugin" } def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } android { namespace "dev.flutter.plaform_example" compileSdk flutter.compileSdkVersion ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { applicationId "dev.flutter.plaform_example" minSdkVersion flutter.minSdkVersion targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName } buildTypes { release { signingConfig signingConfigs.debug } } } flutter { source '../..' } dependencies {}
packages/packages/platform/example/android/app/build.gradle/0
{ "file_path": "packages/packages/platform/example/android/app/build.gradle", "repo_id": "packages", "token_count": 567 }
1,103
name: platform description: A pluggable, mockable platform information abstraction for Dart. repository: https://github.com/flutter/packages/tree/main/packages/platform issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+platform%22 version: 3.1.4 environment: sdk: ^3.1.0 dev_dependencies: test: ^1.16.8 topics: - information - platform
packages/packages/platform/pubspec.yaml/0
{ "file_path": "packages/packages/platform/pubspec.yaml", "repo_id": "packages", "token_count": 144 }
1,104
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import XCTest final class RunnerUITests: XCTestCase { override func setUp() { continueAfterFailure = false } func testPointerInterceptorBlocksGesturesFromFlutter() { let app = XCUIApplication() app.launch() let fabInitial = app.buttons["Initial"] if !(fabInitial.waitForExistence(timeout: 30)) { print(app.debugDescription) XCTFail("Could not find Flutter button to click on") return } fabInitial.tap() let fabAfter = app.buttons["Tapped"] if !(fabAfter.waitForExistence(timeout: 30)) { print(app.debugDescription) XCTFail("Flutter button did not change on tap") return } let exp = expectation(description: "Check platform view not clicked after 3 seconds") let result = XCTWaiter.wait(for: [exp], timeout: 3.0) if result == XCTWaiter.Result.timedOut { let dummyButton = app.staticTexts["Not Clicked"] if !(dummyButton.waitForExistence(timeout: 30)) { print(app.debugDescription) XCTFail("Pointer interceptor did not block gesture from hitting platform view") return } } } }
packages/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerUITests/RunnerUITests.swift/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/example/ios/RunnerUITests/RunnerUITests.swift", "repo_id": "packages", "token_count": 461 }
1,105
def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterRoot = localProperties.getProperty('flutter.sdk') if (flutterRoot == null) { throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } apply plugin: 'com.android.application' apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { namespace 'io.flutter.plugins.quickactionsexample' compileSdk flutter.compileSdkVersion defaultConfig { applicationId "io.flutter.plugins.quickactionsexample" minSdkVersion 21 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { signingConfig signingConfigs.debug } } lint { disable 'InvalidPackage' } } flutter { source '../..' } dependencies { testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test:runner:1.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' api 'androidx.test:core:1.2.0' }
packages/packages/quick_actions/quick_actions/example/android/app/build.gradle/0
{ "file_path": "packages/packages/quick_actions/quick_actions/example/android/app/build.gradle", "repo_id": "packages", "token_count": 620 }
1,106
rootProject.name = 'quick_actions'
packages/packages/quick_actions/quick_actions_android/android/settings.gradle/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/android/settings.gradle", "repo_id": "packages", "token_count": 11 }
1,107
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; /// Home screen quick-action shortcut item. class ShortcutItemMessage { ShortcutItemMessage({ required this.type, required this.localizedTitle, this.icon, }); /// The identifier of this item; should be unique within the app. String type; /// Localized title of the item. String localizedTitle; /// Name of native resource to be displayed as the icon for this item. String? icon; Object encode() { return <Object?>[ type, localizedTitle, icon, ]; } static ShortcutItemMessage decode(Object result) { result as List<Object?>; return ShortcutItemMessage( type: result[0]! as String, localizedTitle: result[1]! as String, icon: result[2] as String?, ); } } class _AndroidQuickActionsApiCodec extends StandardMessageCodec { const _AndroidQuickActionsApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is ShortcutItemMessage) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return ShortcutItemMessage.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } class AndroidQuickActionsApi { /// Constructor for [AndroidQuickActionsApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. AndroidQuickActionsApi({BinaryMessenger? binaryMessenger}) : _binaryMessenger = binaryMessenger; final BinaryMessenger? _binaryMessenger; static const MessageCodec<Object?> codec = _AndroidQuickActionsApiCodec(); /// Checks for, and returns the action that launched the app. Future<String?> getLaunchAction() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.getLaunchAction', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return (replyList[0] as String?); } } /// Sets the dynamic shortcuts for the app. Future<void> setShortcutItems( List<ShortcutItemMessage?> arg_itemsList) async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.setShortcutItems', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(<Object?>[arg_itemsList]) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } /// Removes all dynamic shortcuts. Future<void> clearShortcutItems() async { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsApi.clearShortcutItems', codec, binaryMessenger: _binaryMessenger); final List<Object?>? replyList = await channel.send(null) as List<Object?>?; if (replyList == null) { throw PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel.', ); } else if (replyList.length > 1) { throw PlatformException( code: replyList[0]! as String, message: replyList[1] as String?, details: replyList[2], ); } else { return; } } } abstract class AndroidQuickActionsFlutterApi { static const MessageCodec<Object?> codec = StandardMessageCodec(); /// Sends a string representing a shortcut from the native platform to the app. void launchAction(String action); static void setup(AndroidQuickActionsFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction', codec, binaryMessenger: binaryMessenger); if (api == null) { channel.setMessageHandler(null); } else { channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_action = (args[0] as String?); assert(arg_action != null, 'Argument for dev.flutter.pigeon.quick_actions_android.AndroidQuickActionsFlutterApi.launchAction was null, expected non-null String.'); api.launchAction(arg_action!); return; }); } } } }
packages/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/lib/src/messages.g.dart", "repo_id": "packages", "token_count": 2307 }
1,108
# Remote Flutter Widgets This package provides a mechanism for rendering widgets based on declarative UI descriptions that can be obtained at runtime. ## Status This package is relatively stable. We plan to keep the format and supported widget set backwards compatible, so that once a file works, it will keep working. _However_, this is best-effort only. To guarantee that files keep working as you expect, submit tests to this package (e.g. the binary file and the corresponding screenshot, as a golden test). The set of widgets supported by this package is somewhat arbitrary. PRs that add new widgets from Flutter's default widget libraries (`widgets`, `material`, and`'cupertino`) are welcome. There are some known theoretical performance limitations with the package's current implementation, but so far nobody has reported experiencing them in production. Please [file issues](https://github.com/flutter/flutter/issues/new?labels=p:%20rfw,package,P2) if you run into them. ## Feedback We would love to hear your experiences using this package, whether positive or negative. In particular, stories of uses of this package in production would be very interesting. Please add comments to [issue 90218](https://github.com/flutter/flutter/issues/90218). ## Limitations Once you realize that you can ship UI (and maybe logic, e.g. using Wasm; see the example below) you will slowly be tempted to move your whole application to this model. This won't work. Flutter proper lets you create widgets for compelling UIs with gestures and animations and so forth. With RFW you can use those widgets, but it doesn't let you _create_ those widgets. For example, you don't want to use RFW to create a UI that involves page transitions. You don't want to use RFW to create new widgets that involve drag and drop. You don't want to use RFW to create widgets that involve custom painters. Rather, RFW is best suited for interfaces made out of prebuilt components. For example, a database front-end could use this to describe bespoke UIs for editing different types of objects in the database. Message-of-the-day announcements could be built using this mechanism. Search interfaces could use this mechanism for rich result cards. RFW is well-suited for describing custom UIs from a potentially infinite set of UIs that could not possibly have been known when the application was created. On the other hand, updating the application's look and feel, changing how navigation works in an application, or adding new features, are all changes that are best made in Flutter itself, creating a new application and shipping that through normal update channels. ## Using Remote Flutter Widgets ### Introduction The Remote Flutter Widgets (RFW) package combines widget descriptions obtained at runtime, data obtained at runtime, some predefined widgets provided at compile time, and some app logic provided at compile time (possibly combined with other packages to enable new logic to be obtained at runtime), to generate arbitrary widget trees at runtime. The widget descriptions obtained at runtime (e.g. over the network) are called _remote widget libraries_. These are normally transported in a binary format with the file extension `.rfw`. They can be written in a text format (file extension `.rfwtxt`), and either used directly or converted into the binary format for transport. The `rfw` package provides APIs for parsing and encoding these formats. The [parts of the package](https://pub.dev/documentation/rfw/latest/formats/formats-library.html) that only deal with these formats can be imported directly and have no dependency on Flutter's `dart:ui` library, which means they can be used on the server or in command-line applications. The data obtained at runtime is known as _configuration data_ and is represented by `DynamicContent` objects. It uses a data structure similar to JSON (but it distinguishes `int` and `double` and does not support `null`). The `rfw` package provides both binary and text formats to carry this data; JSON can also be used directly (with some caution), and the data can be created directly in Dart. This is discussed in more detail in the [DynamicContent](https://pub.dev/documentation/rfw/latest/rfw/DynamicContent-class.html) API documentation. Remote widget libraries can use the configuration data to define how the widgets are built. Remote widget libraries all eventually bottom out in the predefined widgets that are compiled into the application. These are called _local widget libraries_. The `rfw` package ships with two local widget libraries, the [core widgets](https://pub.dev/documentation/rfw/latest/rfw/createCoreWidgets.html) from the `widgets` library (such as `Text`, `Center`, `Row`, etc), and some of the [material widgets](https://pub.dev/documentation/rfw/latest/rfw/createMaterialWidgets.html). Programs can define their own local widget libraries, to provide more widgets for remote widget libraries to use. These components are combined using a [`RemoteWidget`](https://pub.dev/documentation/rfw/latest/rfw/RemoteWidget-class.html) widget and a [`Runtime`](https://pub.dev/documentation/rfw/latest/rfw/Runtime-class.html) object. The remote widget libraries can specify _events_ that trigger in response to callbacks. For example, the `OutlinedButton` widget defined in the [Material](https://pub.dev/documentation/rfw/latest/rfw/createMaterialWidgets.html) local widget library has an `onPressed` property which the remote widget library can define as triggering an event. Events can contain data (either hardcoded or obtained from the configuration data). These events result in a callback on the `RemoteWidget` being invoked. Events can either have hardcoded results, or the `rfw` package can be combined with other packages such as [`wasm_run_flutter`](https://pub.dev/packages/wasm_run_flutter) so that events trigger code obtained at runtime. That code typically changes the configuration data, resulting in an update to the rendered widgets. _See also: [API documentation](https://pub.dev/documentation/rfw/latest/rfw/rfw-library.html)_ ### Getting started A Flutter application can render remote widgets using the `RemoteWidget` widget, as in the following snippet: <?code-excerpt "example/hello/lib/main.dart (Example)"?> ```dart class Example extends StatefulWidget { const Example({super.key}); @override State<Example> createState() => _ExampleState(); } class _ExampleState extends State<Example> { final Runtime _runtime = Runtime(); final DynamicContent _data = DynamicContent(); // Normally this would be obtained dynamically, but for this example // we hard-code the "remote" widgets into the app. // // Also, normally we would decode this with [decodeLibraryBlob] rather than // parsing the text version using [parseLibraryFile]. However, to make it // easier to demo, this uses the slower text format. static final RemoteWidgetLibrary _remoteWidgets = parseLibraryFile(''' // The "import" keyword is used to specify dependencies, in this case, // the built-in widgets that are added by initState below. import core.widgets; // The "widget" keyword is used to define a new widget constructor. // The "root" widget is specified as the one to render in the build // method below. widget root = Container( color: 0xFF002211, child: Center( child: Text(text: ["Hello, ", data.greet.name, "!"], textDirection: "ltr"), ), ); '''); static const LibraryName coreName = LibraryName(<String>['core', 'widgets']); static const LibraryName mainName = LibraryName(<String>['main']); @override void initState() { super.initState(); // Local widget library: _runtime.update(coreName, createCoreWidgets()); // Remote widget library: _runtime.update(mainName, _remoteWidgets); // Configuration data: _data.update('greet', <String, Object>{'name': 'World'}); } @override Widget build(BuildContext context) { return RemoteWidget( runtime: _runtime, data: _data, widget: const FullyQualifiedWidgetName(mainName, 'root'), onEvent: (String name, DynamicMap arguments) { // The example above does not have any way to trigger events, but if it // did, they would result in this callback being invoked. debugPrint('user triggered event "$name" with data: $arguments'); }, ); } } ``` In this example, the "remote" widgets are hardcoded into the application (`_remoteWidgets`), the configuration data is hardcoded and unchanging (`_data`), and the event handler merely prints a message to the console. In typical usage, the remote widgets come from a server at runtime, either through HTTP or some other network transport. Separately, the `DynamicContent` data would be updated, either from the server or based on local data. Similarly, events that are signalled by the user's interactions with the remote widgets (`RemoteWidget.onEvent`) would typically be sent to the server for the server to update the data, or would cause the data to be updated directly, on the user's device, according to some predefined logic. It is recommended that servers send binary data, decoded using `decodeLibraryBlob` and `decodeDataBlob`, when providing updates for the remote widget libraries and data. ### Applying these concepts to typical use cases #### Message of the day, advertising, announcements When `rfw` is used for displaying content that is largely static in presentation and updated only occasionally, the simplest approach is to encode everything into the remote widget library, download that to the client, and render it, with only minimal data provided in the configuration data (e.g. the user's dark mode preference, their username, the current date or time) and with a few predefined events (such as one to signal the message should be closed and another to signal the user checking a "do not show this again" checkbox, or similar). #### Dynamic data editors A more elaborate use case might involve remote widget libraries being used to describe the UI for editing structured data in a database. In this case, the data may be more important, containing the current data being edited, and the events may signal to the application how to update the data on the backend. #### Search results A general search engine could have dedicated remote widgets defined for different kinds of results, allowing the data to be formatted and made interactive in ways that are specific to the query and in ways that could not have been predicted when the application was created. For example, new kinds of search results for current events could be created on the fly and sent to the client without needing to update the client application. ### Developing new local widget libraries A "local" widget library is one that describes the built-in widgets that your "remote" widgets are built out of. The RFW package comes with some preprepared libraries, available through [createCoreWidgets](https://pub.dev/documentation/rfw/latest/rfw/createCoreWidgets.html) and [createMaterialWidgets](https://pub.dev/documentation/rfw/latest/rfw/createMaterialWidgets.html). You can also create your own. When developing new local widget libraries, it is convenient to hook into the `reassemble` method to update the local widgets. That way, changes can be seen in real time when hot reloading. <?code-excerpt "example/local/lib/main.dart (Example)"?> ```dart class Example extends StatefulWidget { const Example({super.key}); @override State<Example> createState() => _ExampleState(); } class _ExampleState extends State<Example> { final Runtime _runtime = Runtime(); final DynamicContent _data = DynamicContent(); @override void initState() { super.initState(); _update(); } @override void reassemble() { // This function causes the Runtime to be updated any time the app is // hot reloaded, so that changes to _createLocalWidgets can be seen // during development. This function has no effect in production. super.reassemble(); _update(); } static WidgetLibrary _createLocalWidgets() { return LocalWidgetLibrary(<String, LocalWidgetBuilder>{ 'GreenBox': (BuildContext context, DataSource source) { return ColoredBox( color: const Color(0xFF002211), child: source.child(<Object>['child']), ); }, 'Hello': (BuildContext context, DataSource source) { return Center( child: Text( 'Hello, ${source.v<String>(<Object>["name"])}!', textDirection: TextDirection.ltr, ), ); }, }); } static const LibraryName localName = LibraryName(<String>['local']); static const LibraryName remoteName = LibraryName(<String>['remote']); void _update() { _runtime.update(localName, _createLocalWidgets()); // Normally we would obtain the remote widget library in binary form from a // server, and decode it with [decodeLibraryBlob] rather than parsing the // text version using [parseLibraryFile]. However, to make it easier to // play with this sample, this uses the slower text format. _runtime.update(remoteName, parseLibraryFile(''' import local; widget root = GreenBox( child: Hello(name: "World"), ); ''')); } @override Widget build(BuildContext context) { return RemoteWidget( runtime: _runtime, data: _data, widget: const FullyQualifiedWidgetName(remoteName, 'root'), onEvent: (String name, DynamicMap arguments) { debugPrint('user triggered event "$name" with data: $arguments'); }, ); } } ``` Widgets in local widget libraries are represented by closures that are invoked by the runtime whenever a local widget is referenced. The closure uses the [LocalWidgetBuilder](https://pub.dev/documentation/rfw/latest/rfw/LocalWidgetBuilder.html) signature. Like any builder in Flutter, it takes a [`BuildContext`](https://api.flutter.dev/flutter/widgets/BuildContext-class.html), which can be used to look up inherited widgets. > For example, widgets that need the current text direction might > defer to `Directionality.of(context)`, with the given `BuildContext` > as the context argument. The other argument is a [`DataSource`](https://pub.dev/documentation/rfw/latest/rfw/DataSource-class.html). This gives access to the arguments that were provided to the widget in the remote widget library. For example, consider the example above, where the remote widget library is: <?code-excerpt "test/readme_test.dart (root)"?> ```rfwtxt import local; widget root = GreenBox( child: Hello(name: "World"), ); ``` The `GreenBox` widget is invoked with one argument (`child`), and the `Hello` widget is invoked with one argument (`name`). In the definitions of `GreenBox` and `Hello`, the data source is used to pull out these arguments. ### Obtaining arguments from the `DataSource` The arguments are a tree of maps and lists with leaves that are Dart scalar values (`int`, `double`, `bool`, or `String`), further widgets, or event handlers. #### Scalars Here is an example of a more elaborate widget argument: <?code-excerpt "test/readme_test.dart (fruit)"?> ```rfwtxt widget fruit = Foo( bar: { quux: [ 'apple', 'banana', 'cherry' ] }, ); ``` To obtain a scalar value from the arguments, the [DataSource.v](https://pub.dev/documentation/rfw/latest/rfw/DataSource/v.html) method is used. This method takes a list of keys (strings or integers) that denote the path to scalar in question. For instance, to obtain "cherry" from the example above, the keys would be `bar`, `quux`, and 2, as in: <?code-excerpt "test/readme_test.dart (v)"?> ```dart 'Foo': (BuildContext context, DataSource source) { return Text(source.v<String>(<Object>['bar', 'quux', 2])!); }, ``` The `v` method is generic, with a type argument that specifies the expected type (one of `int`, `double`, `bool`, or `String`). When the value of the argument in the remote widget library does not match the specified (or inferred) type given to `v`, or if the specified keys don't lead to a value at all, it returns null instead. #### Maps and lists The `LocalWidgetBuilder` callback can inspect keys to see if they are maps or lists before attempting to use them. For example, before accessing a dozen fields from a map, one might use `isMap` to check if the map is present at all. If it is not, then all the fields will be null, and it is inefficient to fetch each one individually. The [`DataSource.isMap`](https://pub.dev/documentation/rfw/latest/rfw/DataSource/isMap.html) method is takes a list of keys (like `v`) and reports if the key identifies a map. For example, in this case the `bar` argument can be treated either as a map with a `name` subkey, or a scalar String: <?code-excerpt "test/readme_test.dart (isMap)"?> ```dart 'Foo': (BuildContext context, DataSource source) { if (source.isMap(<Object>['bar'])) { return Text('${source.v<String>(<Object>['bar', 'name'])}', textDirection: TextDirection.ltr); } return Text('${source.v<String>(<Object>['bar'])}', textDirection: TextDirection.ltr); }, ``` Thus either of the following would have the same result: <?code-excerpt "test/readme_test.dart (example1)"?> ```rfwtxt widget example1 = GreenBox( child: Foo( bar: 'Jean', ), ); ``` <?code-excerpt "test/readme_test.dart (example2)"?> ```rfwtxt widget example2 = GreenBox( child: Foo( bar: { name: 'Jean' }, ), ); ``` The [`DataSource.isList`](https://pub.dev/documentation/rfw/latest/rfw/DataSource/isList.html) method is similar but reports on whether the specified key identifies a list: <?code-excerpt "test/readme_test.dart (isList)"?> ```dart 'Foo': (BuildContext context, DataSource source) { if (source.isList(<Object>['bar', 'quux'])) { return Text('${source.v<String>(<Object>['bar', 'quux', 2])}', textDirection: TextDirection.ltr); } return Text('${source.v<String>(<Object>['baz'])}', textDirection: TextDirection.ltr); }, ``` For lists, a `LocalWidgetBuilder` callback can iterate over the items in the list using the [`length`](https://pub.dev/documentation/rfw/latest/rfw/DataSource/length.html) method, which returns the length of the list (or zero if the key does not identify a list): <?code-excerpt "test/readme_test.dart (length)"?> ```dart 'Foo': (BuildContext context, DataSource source) { final int length = source.length(<Object>['text']); if (length > 0) { final StringBuffer text = StringBuffer(); for (int index = 0; index < length; index += 1) { text.write(source.v<String>(<Object>['text', index])); } return Text(text.toString(), textDirection: TextDirection.ltr); } return const Text('<empty>', textDirection: TextDirection.ltr); }, ``` This could be used like this: <?code-excerpt "test/readme_test.dart (example3)"?> ```rfwtxt widget example3 = GreenBox( child: Foo( text: ['apple', 'banana'] ), ); ``` #### Widgets The `GreenBox` widget has a child widget, which is itself specified by the remote widget. This is common, for example, `Row` and `Column` widgets have children, `Center` has a child, and so on. Indeed, most widgets have children, except for those like `Text`, `Image`, and `Spacer`. The `GreenBox` definition uses [`DataSource.child`](https://pub.dev/documentation/rfw/latest/rfw/DataSource/child.html) to obtain the widget, in a manner similar to the `v` method: <?code-excerpt "test/readme_test.dart (child)"?> ```rfwtxt 'GreenBox': (BuildContext context, DataSource source) { return ColoredBox(color: const Color(0xFF002211), child: source.child(<Object>['child'])); }, ``` Rather than returning `null` when the specified key points to an argument that isn't a widget, the `child` method returns an `ErrorWidget`. For cases where having `null` is acceptable, the [`optionalChild`](https://pub.dev/documentation/rfw/latest/rfw/DataSource/optionalChild.html) method can be used: <?code-excerpt "test/readme_test.dart (optionalChild)"?> ```rfwtxt 'GreenBox': (BuildContext context, DataSource source) { return ColoredBox(color: const Color(0xFF002211), child: source.optionalChild(<Object>['child'])); }, ``` It returns `null` when the specified key does not point to a widget. For widgets that take lists of children, the [`childList`](https://pub.dev/documentation/rfw/latest/rfw/DataSource/childList.html) method can be used. For example, this is how `Row` is defined in `createCoreWidgets` (see in particular the `children` line): <?code-excerpt "lib/src/flutter/core_widgets.dart (Row)"?> ```rfwtxt 'Row': (BuildContext context, DataSource source) { return Row( mainAxisAlignment: ArgumentDecoders.enumValue<MainAxisAlignment>(MainAxisAlignment.values, source, ['mainAxisAlignment']) ?? MainAxisAlignment.start, mainAxisSize: ArgumentDecoders.enumValue<MainAxisSize>(MainAxisSize.values, source, ['mainAxisSize']) ?? MainAxisSize.max, crossAxisAlignment: ArgumentDecoders.enumValue<CrossAxisAlignment>(CrossAxisAlignment.values, source, ['crossAxisAlignment']) ?? CrossAxisAlignment.center, textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), verticalDirection: ArgumentDecoders.enumValue<VerticalDirection>(VerticalDirection.values, source, ['verticalDirection']) ?? VerticalDirection.down, textBaseline: ArgumentDecoders.enumValue<TextBaseline>(TextBaseline.values, source, ['textBaseline']), children: source.childList(['children']), ); }, ``` #### `ArgumentDecoders` It is common to need to decode types that are more structured than merely `int`, `double`, `bool`, or `String` scalars, for example, enums, `Color`s, or `Paint`s. The [`ArgumentDecoders`](https://pub.dev/documentation/rfw/latest/rfw/ArgumentDecoders-class.html) namespace offers some utility functions to make the decoding of such values consistent. For example, the `Row` definition above has some cases of enums. To decode them, it uses the [`ArgumentDecoders.enumValue`](https://pub.dev/documentation/rfw/latest/rfw/ArgumentDecoders/enumValue.html) method. #### Handlers The last kind of argument that widgets can have is callbacks. Since remote widget libraries are declarative and not code, they cannot represent executable closures. Instead, they are represented as events. For example, here is how the "7" button from the [calculator example](https://github.com/flutter/packages/blob/main/packages/rfw/example/wasm/logic/calculator.rfwtxt) is represented: <?code-excerpt "example/wasm/logic/calculator.rfwtxt (button7)"?> ```rfwtxt CalculatorButton(label: "7", onPressed: event "digit" { arguments: [7] }), ``` This creates a `CalculatorButton` widget with two arguments, `label`, a string, and `onPressed`, an event, whose name is "digit" and whose arguments are a map with one key, "arguments", whose value is a list with one value 7. In that example, `CalculatorButton` is itself a remote widget that is defined in terms of a `Button`, and the `onPressed` argument is passed to the `onPressed` of the `Button`, like this: <?code-excerpt "example/wasm/logic/calculator.rfwtxt (CalculatorButton)"?> ```rfwtxt widget CalculatorButton = Padding( padding: [8.0], child: SizedBox( width: 100.0, height: 100.0, child: Button( child: FittedBox(child: Text(text: args.label)), onPressed: args.onPressed, ), ), ); ``` Subsequently, `Button` is defined in terms of a `GestureDetector` local widget (which is defined in terms of the `GestureDetector` widget from the Flutter framework), and the `args.onPressed` is passed to the `onTap` argument of that `GestureDetector` local widget (and from there subsequently to the Flutter framework widget). When all is said and done, and the button is pressed, an event with the name "digit" and the given arguments is reported to the `RemoteWidget`'s `onEvent` callback. That callback takes two arguments, the event name and the event arguments. On the implementation side, in local widget libraries, arguments like the `onTap` of the `GestureDetector` local widget must be turned into a Dart closure that is passed to the actual Flutter widget called `GestureDetector` as the value of its `onTap` callback. The simplest kind of callback closure is a `VoidCallback` (no arguments, no return value). To turn an `event` value in a local widget's arguments in the local widget library into a `VoidCallback` in Dart that reports the event as described above, the `DataSource.voidHandler` method is used. For example, here is a simplified `GestureDetector` local widget that just implements `onTap` (when implementing similar local widgets, you may use a similar technique): <?code-excerpt "test/readme_test.dart (onTap)"?> ```dart return <WidgetLibrary>[ LocalWidgetLibrary(<String, LocalWidgetBuilder>{ // The local widget is called `GestureDetector`... 'GestureDetector': (BuildContext context, DataSource source) { // The local widget is implemented using the `GestureDetector` // widget from the Flutter framework. return GestureDetector( onTap: source.voidHandler(<Object>['onTap']), // A full implementation of a `GestureDetector` local widget // would have more arguments here, like `onTapDown`, etc. child: source.optionalChild(<Object>['child']), ); }, }), ]; ``` Sometimes, a callback has a different signature, in particular, it may provide arguments. To convert the `event` value into a Dart callback closure that reports an event as described above, the `DataSource.handler` method is used. In addition to the list of keys that identify the `event` value, the method itself takes a callback closure. That callback's purpose is to convert the given `trigger` (a function which, when called, reports the event) into the kind of callback closure the `Widget` expects. This is usually written something like the following: <?code-excerpt "test/readme_test.dart (onTapDown)"?> ```dart return GestureDetector( onTapDown: source.handler(<Object>['onTapDown'], (HandlerTrigger trigger) => (TapDownDetails details) => trigger()), child: source.optionalChild(<Object>['child']), ); ``` To break this down more clearly: <?code-excerpt "test/readme_test.dart (onTapDown-long)"?> ```dart return GestureDetector( // onTapDown expects a function that takes a TapDownDetails onTapDown: source.handler<GestureTapDownCallback>( // this returns a function that takes a TapDownDetails <Object>['onTapDown'], (HandlerTrigger trigger) { // "trigger" is the function that will send the event to RemoteWidget.onEvent return (TapDownDetails details) { // this is the function that is returned by handler() above trigger(); // the function calls "trigger" }; }, ), child: source.optionalChild(<Object>['child']), ); ``` In some cases, the arguments sent to the callback (the `TapDownDetails` in this case) are useful and should be passed to the `RemoteWidget.onEvent` as part of its arguments. This can be done by passing some values to the `trigger` method, as in: <?code-excerpt "test/readme_test.dart (onTapDown-position)"?> ```dart return GestureDetector( onTapDown: source.handler(<Object>['onTapDown'], (HandlerTrigger trigger) { return (TapDownDetails details) => trigger(<String, Object>{ 'x': details.globalPosition.dx, 'y': details.globalPosition.dy, }); }), child: source.optionalChild(<Object>['child']), ); ``` Any arguments in the `event` get merged with the arguments passed to the trigger. #### Animations The `rfw` package introduces a new Flutter widget called [`AnimationDefaults`](https://pub.dev/documentation/rfw/latest/rfw/AnimationDefaults-class.html). This widget is exposed by `createCoreWidgets` under the same name, and can be exposed in other local widget libraries as desired. This allows remote widget libraries to configure the animation speed and curves of entire subtrees more conveniently than repeating the details for each widget. To support this widget, implement curve arguments using [`ArgumentDecoders.curve`](https://pub.dev/documentation/rfw/latest/rfw/ArgumentDecoders/curve.html) and duration arguments using [`ArgumentDecoders.duration`](https://pub.dev/documentation/rfw/latest/rfw/ArgumentDecoders/duration.html). This automatically defers to the defaults provided by `AnimationDefaults`. Alternatively, the [`AnimationDefaults.curveOf`](https://pub.dev/documentation/rfw/latest/rfw/AnimationDefaults/curveOf.html) and [`AnimationDefaults.durationOf`](https://pub.dev/documentation/rfw/latest/rfw/AnimationDefaults/durationOf.html) methods can be used with a `BuildContext` directly to get curve and duration settings for animations. The settings default to 200ms and the [`Curves.fastOutSlowIn`](https://api.flutter.dev/flutter/animation/Curves/fastOutSlowIn-constant.html) curve. ### Developing remote widget libraries Remote widget libraries are usually defined using a Remote Flutter Widgets text library file (`rfwtxt` extension), which is then compiled into a binary library file (`rfw` extension) on the server before being sent to the client. The format of text library files is defined in detail in the API documentation of the [`parseLibraryFile`](https://pub.dev/documentation/rfw/latest/formats/parseLibraryFile.html) function. Compiling a text `rfwtxt` file to the binary `rfw` format can be done by calling [`encodeLibraryBlob`](https://pub.dev/documentation/rfw/latest/formats/encodeLibraryBlob.html) on the results of calling `parseLibraryFile`. The example in `example/wasm` has some [elaborate remote widgets](https://github.com/flutter/packages/blob/main/packages/rfw/example/wasm/logic/calculator.rfwtxt), including some that manipulate state (`Button`). #### State The canonical example of a state-manipulating widget is a button. Buttons must react immediately (in milliseconds) and cannot wait for logic that's possibly running on a remote server (maybe many hundreds of milliseconds away). The aforementioned `Button` widget in the `wasm` example tracks a local "down" state, manipulates it in reaction to `onTapDown`/`onTapUp` events, and changes the shadow and margins of the button based on its state: <?code-excerpt "example/wasm/logic/calculator.rfwtxt (Button)"?> ```rfwtxt widget Button { down: false } = GestureDetector( onTap: args.onPressed, onTapDown: set state.down = true, onTapUp: set state.down = false, onTapCancel: set state.down = false, child: Container( duration: 50, margin: switch state.down { false: [ 0.0, 0.0, 2.0, 2.0 ], true: [ 2.0, 2.0, 0.0, 0.0 ], }, padding: [ 12.0, 8.0 ], decoration: { type: "shape", shape: { type: "stadium", side: { width: 1.0 }, }, gradient: { type: "linear", begin: { x: -0.5, y: -0.25 }, end: { x: 0.0, y: 0.5 }, colors: [ 0xFFFFFF99, 0xFFEEDD00 ], stops: [ 0.0, 1.0 ], tileMode: "mirror", }, shadows: switch state.down { false: [ { blurRadius: 4.0, spreadRadius: 0.5, offset: { x: 1.0, y: 1.0, } } ], default: [], }, }, child: DefaultTextStyle( style: { color: 0xFF000000, fontSize: 32.0, }, child: args.child, ), ), ); ``` Because `Container` is implemented in `createCoreWidgets` using the `AnimatedContainer` widget, changing the fields causes the button to animate. The `duration: 50` argument sets the animation speed to 50ms. #### Lists Let us consider a remote widget library that is used to render data in this form: <?code-excerpt "test/readme_test.dart (game-data)"?> ```json { "games": [ {"rating": 8.219, "users-rated": 16860, "name": "Twilight Struggle", "rank": 1, "link": "/boardgame/12333/twilight-struggle", "id": 12333}, {"rating": 8.093, "users-rated": 11750, "name": "Through the Ages: A Story of Civilization", "rank": 2, "link": "/boardgame/25613/through-ages-story-civilization", "id": 25613}, {"rating": 8.088, "users-rated": 34745, "name": "Agricola", "rank": 3, "link": "/boardgame/31260/agricola", "id": 31260}, {"rating": 8.082, "users-rated": 8913, "name": "Terra Mystica", "rank": 4, "link": "/boardgame/120677/terra-mystica", "id": 120677}, // ··· ``` For the sake of this example, let us assume this data is registered with the `DynamicContent` under the name `server`. > This configuration data is both valid JSON and a valid RFW data file, > which shows how similar the two syntaxes are. > > This data is parsed by calling > [`parseDataFile`](https://pub.dev/documentation/rfw/latest/formats/parseDataFile.html), > which turns it into > [`DynamicMap`](https://pub.dev/documentation/rfw/latest/formats/DynamicMap.html). > That object is then passed to a > [`DynamicContent`](https://pub.dev/documentation/rfw/latest/rfw/DynamicContent-class.html), > using > [`DynamicContent.update`](https://pub.dev/documentation/rfw/latest/rfw/DynamicContent/update.html) > (this is where the name `server` would be specified) which is passed > to a > [`RemoteWidget`](https://pub.dev/documentation/rfw/latest/rfw/RemoteWidget-class.html) > via the > [`data`](https://pub.dev/documentation/rfw/latest/rfw/RemoteWidget/data.html) > property. > > Ideally, rather than dealing with this text form on the client, the > data would be turned into a binary form using > [`encodeDataBlob`](https://pub.dev/documentation/rfw/latest/formats/encodeDataBlob.html) > on the server, and then parsed on the client using > [`decodeDataBlob`](https://pub.dev/documentation/rfw/latest/formats/decodeDataBlob.html). First, let's render a plain Flutter `ListView` with the name of each product. The `Shop` widget below achieves this: <?code-excerpt "test/readme_test.dart (Shop)"?> ```rfwtxt import core; widget Shop = ListView( children: [ Text(text: "Products:"), ...for product in data.server.games: Product(product: product) ], ); widget Product = Text(text: args.product.name, softWrap: false, overflow: "fade"); ``` The `Product` widget here is not strictly necessary, it could be inlined into the `Shop`. However, as with Flutter itself, it can be easier to develop widgets when logically separate components are separated into separate widgets. We can elaborate on this example, introducing a Material `AppBar`, using a `ListTile` for the list items, and making them interactive (at least in principle; the logic in the app would need to know how to handle the "shop.productSelect" event): <?code-excerpt "test/readme_test.dart (MaterialShop)"?> ```rfwtxt import core; import material; widget MaterialShop = Scaffold( appBar: AppBar( title: Text(text: ['Products']), ), body: ListView( children: [ ...for product in data.server.games: Product(product: product) ], ), ); widget Product = ListTile( title: Text(text: args.product.name), onTap: event 'shop.productSelect' { name: args.product.name, path: args.product.link }, ); ``` ### Fetching remote widget libraries remotely The example in `example/remote` shows how a program could fetch different user interfaces at runtime. In this example, the interface used on startup is the one last cached locally. Each time the program is run, after displaying the currently-cached interface, the application fetches a new interface over the network, overwriting the one in the cache, so that a different interface is used the next time the app is run. This example also shows how an application can implement custom local code for events; in this case, incrementing a counter (both of the "remote" widgets are just different ways of implementing a counter). ### Integrating with scripting language runtimes The example in `example/wasm` shows how a program could fetch logic in addition to UI, in this case using Wasm compiled from C (and let us briefly appreciate the absurdity of using C as a scripting language for an application written in Dart). In this example, as written, the Dart client could support any application whose data model consisted of a single integer and whose logic could be expressed in C without external dependencies. This example could be extended to have the C program export data in the Remote Flutter Widgets binary data blob format which could be parsed using `decodeDataBlob` and passed to `DynamicContent.update` (thus allowing any structured data supported by RFW), and similarly arguments could be passed to the Wasm code using the same format (encoding using `encodeDataBlob`) to allow arbitrary structured data to be communicated from the interface to the Wasm logic. In addition, the Wasm logic could be provided with WASI interface bindings or with custom bindings that expose platform capabilities (e.g. from Flutter plugins), greatly extending the scope of what could be implemented in the Wasm logic. As of the time of writing, `package:wasm` does not support Android, iOS, or web, so this demo is limited to desktop environments. The underlying Wasmer runtime supports Android and iOS already, and obviously Wasm in general is supported by web browsers, so it is expected that these limitations are only temporary (modulo policy concerns on iOS, anyway). ## Contributing See [CONTRIBUTING.md](https://github.com/flutter/packages/blob/main/packages/rfw/CONTRIBUTING.md)
packages/packages/rfw/README.md/0
{ "file_path": "packages/packages/rfw/README.md", "repo_id": "packages", "token_count": 11302 }
1,109
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/rfw/example/local/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/rfw/example/local/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
1,110
name: remote description: Example of fetching remote widgets for RFW publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: sdk: ^3.2.0 flutter: ">=3.16.0" dependencies: flutter: sdk: flutter path: ^1.8.0 path_provider: ^2.0.2 rfw: path: ../../ flutter: uses-material-design: true
packages/packages/rfw/example/remote/pubspec.yaml/0
{ "file_path": "packages/packages/rfw/example/remote/pubspec.yaml", "repo_id": "packages", "token_count": 147 }
1,111
buildFlags: global: - "--no-tree-shake-icons"
packages/packages/rfw/example/wasm/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/rfw/example/wasm/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 23 }
1,112
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is hand-formatted. // This file must not import `dart:ui`, directly or indirectly, as it is // intended to function even in pure Dart server or CLI environments. import 'dart:convert'; import 'dart:typed_data'; import 'model.dart'; /// The first four bytes of a Remote Flutter Widgets binary data blob. /// /// This signature is automatically added by [encodeDataBlob] and is checked in /// [decodeDataBlob]. /// /// See also: /// /// * [libraryBlobSignature], which is the signature for binary library blobs. const List<int> dataBlobSignature = <int>[0xFE, 0x52, 0x57, 0x44]; /// The first four bytes of a Remote Flutter Widgets binary library blob. /// /// This signature is automatically added by [encodeLibraryBlob] and is checked /// in [decodeLibraryBlob]. /// /// See also: /// /// * [dataBlobSignature], which is the signature for binary data blobs. const List<int> libraryBlobSignature = <int>[0xFE, 0x52, 0x46, 0x57]; /// Encode data as a Remote Flutter Widgets binary data blob. /// /// See also: /// /// * [decodeDataBlob], which decodes this format. /// * [encodeLibraryBlob], which uses a superset of this format to encode /// Remote Flutter Widgets binary library blobs. Uint8List encodeDataBlob(Object value) { final _BlobEncoder encoder = _BlobEncoder(); encoder.writeSignature(dataBlobSignature); encoder.writeValue(value); return encoder.bytes.toBytes(); } /// Decode a Remote Flutter Widgets binary data blob. /// /// This data is usually used in conjunction with [DynamicContent]. /// /// This method supports a subset of the format supported by /// [decodeLibraryBlob]; specifically, it reads a _value_ from that format /// (rather than a _library_), and disallows values other than maps, lists, /// ints, doubles, booleans, and strings. See [decodeLibraryBlob] for a /// description of the format. /// /// The first four bytes of the file (in hex) are FE 52 57 44; see /// [dataBlobSignature]. /// /// See also: /// /// * [encodeDataBlob], which encodes this format. /// * [decodeLibraryBlob], which uses a superset of this format to decode /// Remote Flutter Widgets binary library blobs. /// * [parseDataFile], which parses the text variant of this format. Object decodeDataBlob(Uint8List bytes) { final _BlobDecoder decoder = _BlobDecoder(bytes.buffer.asByteData(bytes.offsetInBytes, bytes.lengthInBytes)); decoder.expectSignature(dataBlobSignature); final Object result = decoder.readValue(); if (!decoder.finished) { throw const FormatException('Unexpected trailing bytes after value.'); } return result; } /// Encode data as a Remote Flutter Widgets binary library blob. /// /// See also: /// /// * [decodeLibraryBlob], which decodes this format. /// * [encodeDataBlob], which uses a subset of this format to decode /// Remote Flutter Widgets binary data blobs. /// * [parseLibraryFile], which parses the text variant of this format. Uint8List encodeLibraryBlob(RemoteWidgetLibrary value) { final _BlobEncoder encoder = _BlobEncoder(); encoder.writeSignature(libraryBlobSignature); encoder.writeLibrary(value); return encoder.bytes.toBytes(); } /// Decode a Remote Flutter Widgets binary library blob. /// /// Remote widget libraries are usually used in conjunction with a [Runtime]. /// /// ## Format /// /// This format is a depth-first serialization of the in-memory data structures, /// using a one-byte tag to identify types when necessary, and using 64 bit /// integers to encode lengths when necessary. /// /// The first four bytes of the file (in hex) are FE 52 46 57; see /// [libraryBlobSignature]. /// /// Primitives in this format are as follows: /// /// * Integers are encoded as little-endian two's complement 64 bit integers. /// For example, the number 513 (0x0000000000000201) is encoded as a 0x01 /// byte, a 0x02 byte, and six 0x00 bytes, in that order. /// /// * Doubles are encoded as little-endian IEEE binary64 numbers. /// /// * Strings are encoded as an integer length followed by that many UTF-8 /// encoded bytes. /// /// For example, the string "Hello" would be encoded as: /// /// 05 00 00 00 00 00 00 00 48 65 6C 6C 6F /// /// * Lists are encoded as an integer length, followed by that many values /// back to back. When lists are of specific types (e.g. lists of imports), /// each value in the list is encoded directly (untagged lists); when the list /// can have multiple types, each value is prefixed by a tag giving the type, /// followed by the value (tagged lists). For example, a list of integers with /// the values 1 and 2 in that order would be encoded as: /// /// 02 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 /// 02 00 00 00 00 00 00 00 /// /// A list of arbitrary values that happens to contain one string "Hello" /// would be encoded as follows; 0x04 is the tag for "String" (the full list /// of tags is described below): /// /// 01 00 00 00 00 00 00 00 04 05 00 00 00 00 00 00 /// 00 48 65 6C 6C 6F /// /// A list of length zero is eight zero bytes with no additional payload. /// /// * Maps are encoded as an integer length, followed by key/value pairs. For /// maps where all the keys are strings (e.g. when encoding a [DynamicMap]), /// the keys are given without tags (an untagged map). For maps where the keys /// are of arbitrary values, the keys are prefixed by a tag byte (a tagged /// map; this is only used when encoding [Switch]es). The _values_ are always /// prefixed by a tag byte (all maps are over values of arbitrary types). /// /// For example, the map `{ a: 15 }` (when the keys are known to always be /// strings, so they are untagged) is encoded as follows (0x02 is the tag for /// integers): /// /// 01 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 /// 61 02 0F 00 00 00 00 00 00 00 /// /// Objects are encoded as follows: /// /// * [RemoteWidgetLibrary] objects are encoded as an untagged list of /// imports and an untagged list of widget declarations. /// /// * Imports are encoded as an untagged list of strings, each of which is /// one of the subparts of the imported library name. For example, `import /// a.b` is encoded as: /// /// 02 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 /// 61 01 00 00 00 00 00 00 00 62 /// /// * Widget declarations are encoded as a string giving the declaration name, /// an untagged map for the initial state, and finally the value that /// represents the root of the widget declaration ([WidgetDeclaration.root], /// which is always either a [Switch] or a [ConstructorCall]). /// /// When the widget's initial state is null, it is encoded as an empty map. By /// extension, this means no distinction is made between a "stateless" remote /// widget and a "stateful" remote widget whose initial state is empty. (This /// is reasonable since if the initial state is empty, no state can ever be /// changed, so the widget is in fact _de facto_ stateless.) /// /// Values are encoded as a tag byte followed by their data, as follows: /// /// * Booleans are encoded as just a tag, with the tag being 0x00 for false and /// 0x01 for true. /// /// * Integers have the tag 0x02, and are encoded as described above (two's /// complement, little-endian, 64 bit). /// /// * Doubles have the tag 0x03, and are encoded as described above /// (little-endian binary64). /// /// * Strings have the tag 0x04, and are encoded as described above (length /// followed by UTF-8 bytes). /// /// * Lists ([DynamicList]) have the tag 0x05, are encoded as described above /// (length followed by tagged values). (Lists of untagged values are never /// found in a "value" context.) /// /// * Maps ([DynamicMap]) have the tag 0x07, are encoded as described above /// (length followed by pairs of strings and tagged values). (Tagged maps, /// i.e. those with tagged keys, are never found in a "value" context.) /// /// * Loops ([Loop]) have the tag 0x08. They are encoded as two tagged values, /// the [Loop.input] and the [Loop.output]. /// /// * Constructor calls ([ConstructorCall]) have the tag 0x09. They are encoded /// as a string for the [ConstructorCall.name] followed by an untagged map /// describing the [ConstructorCall.arguments]. /// /// * Argument, data, and state references ([ArgsReference], [DataReference], /// and [StateReference] respectively) have tags 0x0A, 0x0B, and 0x0D /// respectively, and are encoded as tagged lists of strings or integers /// giving the [Reference.parts] of the reference. /// /// * Loop references ([LoopReference]) have the tag 0x0C, and are encoded as an /// integer giving the number of [Loop] objects between the reference and the /// loop being referenced (this is similar to a De Bruijn index), followed by /// a tagged list of strings or integers giving the [Reference.parts] of the /// reference. /// /// * Switches ([Switch]) have the tag 0x0F. They are encoded as a tagged value /// describing the control value ([Switch.input]), followed by a tagged map /// for the various case values ([Switch.outputs]). The default case is /// represented by a value with tag 0x10 (and no data). /// /// For example, this switch: /// /// ``` /// switch (args.a) { /// 0: 'z', /// 1: 'o', /// default: 'd', /// } /// ``` /// /// ...is encoded as follows (including the tag for the switch itself): /// /// 0F 0A 01 00 00 00 00 00 00 00 61 03 00 00 00 00 /// 00 00 00 02 00 00 00 00 00 00 00 00 04 01 00 00 /// 00 00 00 00 00 7A 02 01 00 00 00 00 00 00 00 04 /// 01 00 00 00 00 00 00 00 6F 10 04 01 00 00 00 00 /// 00 00 00 64 /// /// * Event handlers have the tag 0x0E, and are encoded as a string /// ([EventHandler.eventName]) and an untagged map /// ([EventHandler.eventArguments]). /// /// * State-setting handlers have the tag 0x11, and are encoded as a tagged list /// of strings or integers giving the [Reference.parts] of the state reference /// ([SetStateHandler.stateReference]), followed by the tagged value to which /// to set that state entry ([SetStateHandler.value]). /// /// ## Limitations /// /// JavaScript does not have a native integer type; all numbers are stored as /// [double]s. Data loss may therefore occur when handling integers that cannot /// be completely represented as a [binary64] floating point number. /// /// Integers are used for two purposes in this format; as a length, for which it /// is extremely unlikely that numbers above 2^53 would be practical anyway, and /// for representing integer literals. Thus, when using RFW with JavaScript /// environments, it is recommended to use [double]s instead of [int]s whenever /// possible, to avoid accidental data loss. /// /// See also: /// /// * [encodeLibraryBlob], which encodes this format. /// * [decodeDataBlob], which uses a subset of this format to decode /// Remote Flutter Widgets binary data blobs. /// * [parseDataFile], which parses the text variant of this format. RemoteWidgetLibrary decodeLibraryBlob(Uint8List bytes) { final _BlobDecoder decoder = _BlobDecoder(bytes.buffer.asByteData(bytes.offsetInBytes, bytes.lengthInBytes)); decoder.expectSignature(libraryBlobSignature); final RemoteWidgetLibrary result = decoder.readLibrary(); if (!decoder.finished) { throw const FormatException('Unexpected trailing bytes after constructors.'); } return result; } // endianess used by this format const Endian _blobEndian = Endian.little; // whether we can use 64 bit APIs on this platform // (on JS, we can only use 32 bit APIs and integers only go up to ~2^53) const bool _has64Bits = 0x1000000000000000 + 1 != 0x1000000000000000; // 2^60 // magic signatures const int _msFalse = 0x00; const int _msTrue = 0x01; const int _msInt64 = 0x02; const int _msBinary64 = 0x03; const int _msString = 0x04; const int _msList = 0x05; const int _msMap = 0x07; const int _msLoop = 0x08; const int _msWidget = 0x09; const int _msArgsReference = 0x0A; const int _msDataReference = 0x0B; const int _msLoopReference = 0x0C; const int _msStateReference = 0x0D; const int _msEvent = 0x0E; const int _msSwitch = 0x0F; const int _msDefault = 0x10; const int _msSetState = 0x11; const int _msWidgetBuilder = 0x12; const int _msWidgetBuilderArgReference = 0x13; /// API for decoding Remote Flutter Widgets binary blobs. /// /// Binary data blobs can be decoded by using [readValue]. /// /// Binary library blobs can be decoded by using [readLibrary]. /// /// In either case, if [finished] returns false after parsing the root token, /// then there is unexpected further data in the file. class _BlobDecoder { _BlobDecoder(this.bytes); final ByteData bytes; int _cursor = 0; bool get finished => _cursor >= bytes.lengthInBytes; void _advance(String context, int length) { if (_cursor + length > bytes.lengthInBytes) { throw FormatException('Could not read $context at offset $_cursor: unexpected end of file.'); } _cursor += length; } int _readByte() { final int byteOffset = _cursor; _advance('byte', 1); return bytes.getUint8(byteOffset); } int _readInt64() { final int byteOffset = _cursor; _advance('int64', 8); if (_has64Bits) { return bytes.getInt64(byteOffset, _blobEndian); } // We use multiplication rather than bit shifts because << truncates to 32 bits when compiled to JS: // https://dart.dev/guides/language/numbers#bitwise-operations final int a = bytes.getUint32(byteOffset, _blobEndian); // dead code on VM target final int b = bytes.getInt32(byteOffset + 4, _blobEndian); // dead code on VM target return a + (b * 0x100000000); // dead code on VM target } double _readBinary64() { final int byteOffset = _cursor; _advance('binary64', 8); return bytes.getFloat64(byteOffset, _blobEndian); } String _readString() { final int length = _readInt64(); final int byteOffset = _cursor; _advance('string', length); return utf8.decode(bytes.buffer.asUint8List(bytes.offsetInBytes + byteOffset, length)); } List<Object> _readPartList() { return List<Object>.generate(_readInt64(), (int index) { final int type = _readByte(); switch (type) { case _msString: return _readString(); case _msInt64: return _readInt64(); default: throw FormatException('Invalid reference type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding blob.'); } }); } Map<String, Object?>? _readMap(Object Function() readNode, { bool nullIfEmpty = false }) { final int count = _readInt64(); if (count == 0 && nullIfEmpty) { return null; } return DynamicMap.fromEntries( Iterable<MapEntry<String, Object>>.generate( count, (int index) => MapEntry<String, Object>( _readString(), readNode(), ), ), ); } Object? _readSwitchKey() { final int type = _readByte(); if (type == _msDefault) { return null; } return _parseArgument(type); } Switch _readSwitch() { final Object value = _readArgument(); final int count = _readInt64(); final Map<Object?, Object> cases = Map<Object?, Object>.fromEntries( Iterable<MapEntry<Object?, Object>>.generate( count, (int index) => MapEntry<Object?, Object>( _readSwitchKey(), _readArgument(), ), ), ); return Switch(value, cases); } Object _parseValue(int type, Object Function() readNode) { switch (type) { case _msFalse: return false; case _msTrue: return true; case _msInt64: return _readInt64(); case _msBinary64: return _readBinary64(); case _msString: return _readString(); case _msList: return DynamicList.generate(_readInt64(), (int index) => readNode()); case _msMap: return _readMap(readNode)!; default: throw FormatException('Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding blob.'); } } Object readValue() { final int type = _readByte(); return _parseValue(type, readValue); } Object _parseArgument(int type) { switch (type) { case _msLoop: return Loop(_readArgument(), _readArgument()); case _msWidget: return _readWidget(); case _msArgsReference: return ArgsReference(_readPartList()); case _msDataReference: return DataReference(_readPartList()); case _msLoopReference: return LoopReference(_readInt64(), _readPartList()); case _msStateReference: return StateReference(_readPartList()); case _msEvent: return EventHandler(_readString(), _readMap(_readArgument)!); case _msSwitch: return _readSwitch(); case _msSetState: return SetStateHandler(StateReference(_readPartList()), _readArgument()); case _msWidgetBuilder: return _readWidgetBuilder(); case _msWidgetBuilderArgReference: return WidgetBuilderArgReference(_readString(), _readPartList()); default: return _parseValue(type, _readArgument); } } Object _readArgument() { final int type = _readByte(); return _parseArgument(type); } ConstructorCall _readWidget() { final String name = _readString(); return ConstructorCall(name, _readMap(_readArgument)!); } WidgetBuilderDeclaration _readWidgetBuilder() { final String argumentName = _readString(); final int type = _readByte(); if (type != _msWidget && type != _msSwitch) { throw FormatException('Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding widget builder blob.'); } final BlobNode widget = type == _msWidget ? _readWidget() : _readSwitch(); return WidgetBuilderDeclaration(argumentName, widget); } WidgetDeclaration _readDeclaration() { final String name = _readString(); final DynamicMap? initialState = _readMap(readValue, nullIfEmpty: true); final int type = _readByte(); final BlobNode root; switch (type) { case _msSwitch: root = _readSwitch(); case _msWidget: root = _readWidget(); default: throw FormatException('Unrecognized data type 0x${type.toRadixString(16).toUpperCase().padLeft(2, "0")} while decoding widget declaration root.'); } return WidgetDeclaration(name, initialState, root); } List<WidgetDeclaration> _readDeclarationList() { return List<WidgetDeclaration>.generate(_readInt64(), (int index) => _readDeclaration()); } Import _readImport() { return Import(LibraryName(List<String>.generate(_readInt64(), (int index) => _readString()))); } List<Import> _readImportList() { return List<Import>.generate(_readInt64(), (int index) => _readImport()); } RemoteWidgetLibrary readLibrary() { return RemoteWidgetLibrary(_readImportList(), _readDeclarationList()); } void expectSignature(List<int> signature) { assert(signature.length == 4); final List<int> bytes = <int>[]; bool match = true; for (final int byte in signature) { final int read = _readByte(); bytes.add(read); if (read != byte) { match = false; } } if (!match) { throw FormatException( 'File signature mismatch. ' 'Expected ${signature.map<String>((int byte) => byte.toRadixString(16).toUpperCase().padLeft(2, "0")).join(" ")} ' 'but found ${bytes.map<String>((int byte) => byte.toRadixString(16).toUpperCase().padLeft(2, "0")).join(" ")}.' ); } } } /// API for encoding Remote Flutter Widgets binary blobs. /// /// Binary data blobs can be serialized using [writeValue]. /// /// Binary library blobs can be serialized using [writeLibrary]. /// /// The output is in [bytes], and can be cleared manually to reuse the [_BlobEncoder]. class _BlobEncoder { _BlobEncoder(); static final Uint8List _scratchOut = Uint8List(8); static final ByteData _scratchIn = _scratchOut.buffer.asByteData(_scratchOut.offsetInBytes, _scratchOut.lengthInBytes); final BytesBuilder bytes = BytesBuilder(); // copying builder -- we repeatedly add _scratchOut after changing it void _writeInt64(int value) { if (_has64Bits) { _scratchIn.setInt64(0, value, _blobEndian); } else { // We use division rather than bit shifts because >> truncates to 32 bits when compiled to JS: // https://dart.dev/guides/language/numbers#bitwise-operations if (value >= 0) { // dead code on VM target _scratchIn.setInt32(0, value, _blobEndian); // dead code on VM target _scratchIn.setInt32(4, value ~/ 0x100000000, _blobEndian); // dead code on VM target } else { _scratchIn.setInt32(0, value, _blobEndian); // dead code on VM target _scratchIn.setInt32(4, -((-value) ~/ 0x100000000 + 1), _blobEndian); // dead code on VM target } } bytes.add(_scratchOut); } void _writeString(String value) { final Uint8List buffer = const Utf8Encoder().convert(value); _writeInt64(buffer.length); bytes.add(buffer); } void _writeMap(DynamicMap value, void Function(Object? value) recurse) { _writeInt64(value.length); value.forEach((String key, Object? value) { _writeString(key); recurse(value); }); } void _writePart(Object? value) { if (value is int) { bytes.addByte(_msInt64); _writeInt64(value); } else if (value is String) { bytes.addByte(_msString); _writeString(value); } else { throw StateError('Unexpected type ${value.runtimeType} while encoding blob.'); } } void _writeValue(Object? value, void Function(Object? value) recurse) { if (value == false) { bytes.addByte(_msFalse); } else if (value == true) { bytes.addByte(_msTrue); } else if (value is double && value is! int) { // When compiled to JS, a Number can be both. bytes.addByte(_msBinary64); _scratchIn.setFloat64(0, value, _blobEndian); bytes.add(_scratchOut); } else if (value is DynamicList) { bytes.addByte(_msList); _writeInt64(value.length); value.forEach(recurse); } else if (value is DynamicMap) { bytes.addByte(_msMap); _writeMap(value, recurse); } else { _writePart(value); } } void writeValue(Object? value) { _writeValue(value, writeValue); } void _writeArgument(Object? value) { if (value is Loop) { bytes.addByte(_msLoop); _writeArgument(value.input); _writeArgument(value.output); } else if (value is ConstructorCall) { bytes.addByte(_msWidget); _writeString(value.name); _writeMap(value.arguments, _writeArgument); } else if (value is WidgetBuilderDeclaration) { bytes.addByte(_msWidgetBuilder); _writeString(value.argumentName); _writeArgument(value.widget); } else if (value is ArgsReference) { bytes.addByte(_msArgsReference); _writeInt64(value.parts.length); value.parts.forEach(_writePart); } else if (value is DataReference) { bytes.addByte(_msDataReference); _writeInt64(value.parts.length); value.parts.forEach(_writePart); } else if (value is WidgetBuilderArgReference) { bytes.addByte(_msWidgetBuilderArgReference); _writeString(value.argumentName); _writeInt64(value.parts.length); value.parts.forEach(_writePart); } else if (value is LoopReference) { bytes.addByte(_msLoopReference); _writeInt64(value.loop); _writeInt64(value.parts.length); value.parts.forEach(_writePart); } else if (value is StateReference) { bytes.addByte(_msStateReference); _writeInt64(value.parts.length); value.parts.forEach(_writePart); } else if (value is EventHandler) { bytes.addByte(_msEvent); _writeString(value.eventName); _writeMap(value.eventArguments, _writeArgument); } else if (value is Switch) { bytes.addByte(_msSwitch); _writeArgument(value.input); _writeInt64(value.outputs.length); value.outputs.forEach((Object? key, Object value) { if (key == null) { bytes.addByte(_msDefault); } else { _writeArgument(key); } _writeArgument(value); }); } else if (value is SetStateHandler) { bytes.addByte(_msSetState); final StateReference reference = value.stateReference as StateReference; _writeInt64(reference.parts.length); reference.parts.forEach(_writePart); _writeArgument(value.value); } else { assert(value is! BlobNode); _writeValue(value, _writeArgument); } } void _writeDeclarationList(List<WidgetDeclaration> value) { _writeInt64(value.length); for (final WidgetDeclaration declaration in value) { _writeString(declaration.name); if (declaration.initialState != null) { _writeMap(declaration.initialState!, _writeArgument); } else { _writeInt64(0); } _writeArgument(declaration.root); } } void _writeImportList(List<Import> value) { _writeInt64(value.length); for (final Import import in value) { _writeInt64(import.name.parts.length); import.name.parts.forEach(_writeString); } } void writeLibrary(RemoteWidgetLibrary library) { _writeImportList(library.imports); _writeDeclarationList(library.widgets); } void writeSignature(List<int> signature) { assert(signature.length == 4); bytes.add(signature); } }
packages/packages/rfw/lib/src/dart/binary.dart/0
{ "file_path": "packages/packages/rfw/lib/src/dart/binary.dart", "repo_id": "packages", "token_count": 8866 }
1,113
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is hand-formatted. // This file contains and briefly tests the snippets used in the README.md file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart'; import 'package:rfw/rfw.dart'; const Map<String, String> rawRemoteWidgetSnippets = <String, String>{ 'root': ''' // #docregion root import local; widget root = GreenBox( child: Hello(name: "World"), ); // #enddocregion root ''', 'fruit': ''' import local; // #docregion fruit widget fruit = Foo( bar: { quux: [ 'apple', 'banana', 'cherry' ] }, ); // #enddocregion fruit ''', 'example1': ''' import local; // #docregion example1 widget example1 = GreenBox( child: Foo( bar: 'Jean', ), ); // #enddocregion example1 ''', 'example2': ''' import local; // #docregion example2 widget example2 = GreenBox( child: Foo( bar: { name: 'Jean' }, ), ); // #enddocregion example2 ''', 'example3': ''' import local; // #docregion example3 widget example3 = GreenBox( child: Foo( text: ['apple', 'banana'] ), ); // #enddocregion example3 ''', 'tap': ''' import local; import core; widget tap = GestureDetector( onTap: event 'test' { }, child: SizedBox(), ); ''', 'tapDown': ''' import local; import core; widget tapDown = GestureDetector( onTapDown: event 'test' { }, child: SizedBox(), ); ''', 'Shop': ''' // #docregion Shop import core; widget Shop = ListView( children: [ Text(text: "Products:"), ...for product in data.server.games: Product(product: product) ], ); widget Product = Text(text: args.product.name, softWrap: false, overflow: "fade"); // #enddocregion Shop ''', 'MaterialShop': ''' // #docregion MaterialShop import core; import material; widget MaterialShop = Scaffold( appBar: AppBar( title: Text(text: ['Products']), ), body: ListView( children: [ ...for product in data.server.games: Product(product: product) ], ), ); widget Product = ListTile( title: Text(text: args.product.name), onTap: event 'shop.productSelect' { name: args.product.name, path: args.product.link }, ); // #enddocregion MaterialShop ''', }; // The empty docregion at the end of the following causes the snippet to end with "// ...". const String gameData = ''' // #docregion game-data { "games": [ {"rating": 8.219, "users-rated": 16860, "name": "Twilight Struggle", "rank": 1, "link": "/boardgame/12333/twilight-struggle", "id": 12333}, {"rating": 8.093, "users-rated": 11750, "name": "Through the Ages: A Story of Civilization", "rank": 2, "link": "/boardgame/25613/through-ages-story-civilization", "id": 25613}, {"rating": 8.088, "users-rated": 34745, "name": "Agricola", "rank": 3, "link": "/boardgame/31260/agricola", "id": 31260}, {"rating": 8.082, "users-rated": 8913, "name": "Terra Mystica", "rank": 4, "link": "/boardgame/120677/terra-mystica", "id": 120677}, // #enddocregion game-data // #docregion game-data // #enddocregion game-data ] } '''; List<WidgetLibrary> _createLocalWidgets(String region) { switch (region) { case 'root': return <WidgetLibrary>[LocalWidgetLibrary(<String, LocalWidgetBuilder>{ // #docregion defaultLocalWidgets 'GreenBox': (BuildContext context, DataSource source) { return ColoredBox(color: const Color(0xFF002211), child: source.child(<Object>['child'])); }, 'Hello': (BuildContext context, DataSource source) { return Center(child: Text('Hello, ${source.v<String>(<Object>["name"])}!', textDirection: TextDirection.ltr)); }, // #enddocregion defaultLocalWidgets })]; case 'fruit': return <WidgetLibrary>[ LocalWidgetLibrary(<String, LocalWidgetBuilder>{ // #docregion v 'Foo': (BuildContext context, DataSource source) { return Text(source.v<String>(<Object>['bar', 'quux', 2])!); }, // #enddocregion v }), LocalWidgetLibrary(<String, LocalWidgetBuilder>{ // #docregion isList 'Foo': (BuildContext context, DataSource source) { if (source.isList(<Object>['bar', 'quux'])) { return Text('${source.v<String>(<Object>['bar', 'quux', 2])}', textDirection: TextDirection.ltr); } return Text('${source.v<String>(<Object>['baz'])}', textDirection: TextDirection.ltr); }, // #enddocregion isList }), ]; case 'example1': case 'example2': return <WidgetLibrary>[LocalWidgetLibrary(<String, LocalWidgetBuilder>{ // #docregion child 'GreenBox': (BuildContext context, DataSource source) { return ColoredBox(color: const Color(0xFF002211), child: source.child(<Object>['child'])); }, // #enddocregion child // #docregion isMap 'Foo': (BuildContext context, DataSource source) { if (source.isMap(<Object>['bar'])) { return Text('${source.v<String>(<Object>['bar', 'name'])}', textDirection: TextDirection.ltr); } return Text('${source.v<String>(<Object>['bar'])}', textDirection: TextDirection.ltr); }, // #enddocregion isMap })]; case 'example3': return <WidgetLibrary>[LocalWidgetLibrary(<String, LocalWidgetBuilder>{ // #docregion optionalChild 'GreenBox': (BuildContext context, DataSource source) { return ColoredBox(color: const Color(0xFF002211), child: source.optionalChild(<Object>['child'])); }, // #enddocregion optionalChild // #docregion length 'Foo': (BuildContext context, DataSource source) { final int length = source.length(<Object>['text']); if (length > 0) { final StringBuffer text = StringBuffer(); for (int index = 0; index < length; index += 1) { text.write(source.v<String>(<Object>['text', index])); } return Text(text.toString(), textDirection: TextDirection.ltr); } return const Text('<empty>', textDirection: TextDirection.ltr); }, // #enddocregion length })]; case 'tap': // #docregion onTap return <WidgetLibrary>[ LocalWidgetLibrary(<String, LocalWidgetBuilder>{ // The local widget is called `GestureDetector`... 'GestureDetector': (BuildContext context, DataSource source) { // The local widget is implemented using the `GestureDetector` // widget from the Flutter framework. return GestureDetector( onTap: source.voidHandler(<Object>['onTap']), // A full implementation of a `GestureDetector` local widget // would have more arguments here, like `onTapDown`, etc. child: source.optionalChild(<Object>['child']), ); }, }), ]; // #enddocregion onTap case 'tapDown': return <WidgetLibrary>[ LocalWidgetLibrary(<String, LocalWidgetBuilder>{ 'GestureDetector': (BuildContext context, DataSource source) { // #docregion onTapDown return GestureDetector( onTapDown: source.handler(<Object>['onTapDown'], (HandlerTrigger trigger) => (TapDownDetails details) => trigger()), child: source.optionalChild(<Object>['child']), ); // #enddocregion onTapDown }, }), LocalWidgetLibrary(<String, LocalWidgetBuilder>{ 'GestureDetector': (BuildContext context, DataSource source) { // #docregion onTapDown-long return GestureDetector( // onTapDown expects a function that takes a TapDownDetails onTapDown: source.handler<GestureTapDownCallback>( // this returns a function that takes a TapDownDetails <Object>['onTapDown'], (HandlerTrigger trigger) { // "trigger" is the function that will send the event to RemoteWidget.onEvent return (TapDownDetails details) { // this is the function that is returned by handler() above trigger(); // the function calls "trigger" }; }, ), child: source.optionalChild(<Object>['child']), ); // #enddocregion onTapDown-long }, }), LocalWidgetLibrary(<String, LocalWidgetBuilder>{ 'GestureDetector': (BuildContext context, DataSource source) { // #docregion onTapDown-position return GestureDetector( onTapDown: source.handler(<Object>['onTapDown'], (HandlerTrigger trigger) { return (TapDownDetails details) => trigger(<String, Object>{ 'x': details.globalPosition.dx, 'y': details.globalPosition.dy, }); }), child: source.optionalChild(<Object>['child']), ); // #enddocregion onTapDown-position }, }), ]; case 'Shop': case 'MaterialShop': return <WidgetLibrary>[]; default: fail('test has no defined local widgets for root widget "$region"'); } } void main() { testWidgets('readme snippets', (WidgetTester tester) async { final Runtime runtime = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()) ..update(const LibraryName(<String>['material']), createMaterialWidgets()); final DynamicContent data = DynamicContent(parseDataFile(gameData)); for (final String region in rawRemoteWidgetSnippets.keys) { final String body = rawRemoteWidgetSnippets[region]!; runtime.update(LibraryName(<String>[region]), parseLibraryFile(body)); } for (final String region in rawRemoteWidgetSnippets.keys) { for (final WidgetLibrary localWidgets in _createLocalWidgets(region)) { await tester.pumpWidget( MaterialApp( home: RemoteWidget( runtime: runtime ..update(const LibraryName(<String>['local']), localWidgets), data: data, widget: FullyQualifiedWidgetName(LibraryName(<String>[region]), region), ), ), ); } } }); }
packages/packages/rfw/test/readme_test.dart/0
{ "file_path": "packages/packages/rfw/test/readme_test.dart", "repo_id": "packages", "token_count": 4300 }
1,114
name: shared_preferences description: Flutter plugin for reading and writing simple key-value pairs. Wraps NSUserDefaults on iOS and SharedPreferences on Android. repository: https://github.com/flutter/packages/tree/main/packages/shared_preferences/shared_preferences issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+shared_preferences%22 version: 2.2.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: platforms: android: default_package: shared_preferences_android ios: default_package: shared_preferences_foundation linux: default_package: shared_preferences_linux macos: default_package: shared_preferences_foundation web: default_package: shared_preferences_web windows: default_package: shared_preferences_windows dependencies: flutter: sdk: flutter shared_preferences_android: ^2.1.0 shared_preferences_foundation: ^2.2.0 shared_preferences_linux: ^2.2.0 shared_preferences_platform_interface: ^2.3.0 shared_preferences_web: ^2.1.0 shared_preferences_windows: ^2.2.0 dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter topics: - persistence - shared-preferences - storage
packages/packages/shared_preferences/shared_preferences/pubspec.yaml/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/pubspec.yaml", "repo_id": "packages", "token_count": 518 }
1,115
## NEXT * Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6. ## 2.3.5 * Adds privacy manifest. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 2.3.4 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.3.3 * Updates Pigeon-generated code to avoid conflicts with `shared_preferences_ios`. ## 2.3.2 * Updates to the latest version of `pigeon`. ## 2.3.1 * Fixes variable binding bug on older versions of Xcode. ## 2.3.0 * Adds `clearWithParameters` and `getAllWithParameters` methods. * Updates minimum supported macOS version to 10.14. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 2.2.2 * Updates minimum iOS version to 11. ## 2.2.1 * Updates pigeon for null value handling fixes. ## 2.2.0 * Adds `getAllWithPrefix` and `clearWithPrefix` methods. ## 2.1.5 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. ## 2.1.4 * Updates links for the merge of flutter/plugins into flutter/packages. ## 2.1.3 * Uses the new `sharedDarwinSource` flag when available. * Updates minimum Flutter version to 3.0. ## 2.1.2 * Updates code for stricter lint checks. ## 2.1.1 * Adds Swift runtime search paths in podspec to avoid crash in Objective-C apps. Convert example app to Objective-C to catch future Swift runtime issues. ## 2.1.0 * Renames the package previously published as [`shared_preferences_macos`](https://pub.dev/packages/shared_preferences_macos) * Adds iOS support.
packages/packages/shared_preferences/shared_preferences_foundation/CHANGELOG.md/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/CHANGELOG.md", "repo_id": "packages", "token_count": 510 }
1,116
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; import 'messages.g.dart'; typedef _Setter = Future<void> Function(String key, Object value); /// iOS and macOS implementation of shared_preferences. class SharedPreferencesFoundation extends SharedPreferencesStorePlatform { final UserDefaultsApi _api = UserDefaultsApi(); static const String _defaultPrefix = 'flutter.'; late final Map<String, _Setter> _setters = <String, _Setter>{ 'Bool': (String key, Object value) { return _api.setBool(key, value as bool); }, 'Double': (String key, Object value) { return _api.setDouble(key, value as double); }, 'Int': (String key, Object value) { return _api.setValue(key, value as int); }, 'String': (String key, Object value) { return _api.setValue(key, value as String); }, 'StringList': (String key, Object value) { return _api.setValue(key, value as List<String?>); }, }; /// Registers this class as the default instance of /// [SharedPreferencesStorePlatform]. static void registerWith() { SharedPreferencesStorePlatform.instance = SharedPreferencesFoundation(); } @override Future<bool> clear() async { return clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: _defaultPrefix), ), ); } @override Future<bool> clearWithPrefix(String prefix) async { return clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override Future<bool> clearWithParameters(ClearParameters parameters) async { final PreferencesFilter filter = parameters.filter; return _api.clear( filter.prefix, filter.allowList?.toList(), ); } @override Future<Map<String, Object>> getAll() async { return getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: _defaultPrefix), ), ); } @override Future<Map<String, Object>> getAllWithPrefix(String prefix) async { return getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final Map<String?, Object?> data = await _api.getAll(filter.prefix, filter.allowList?.toList()); return data.cast<String, Object>(); } @override Future<bool> remove(String key) async { await _api.remove(key); return true; } @override Future<bool> setValue(String valueType, String key, Object value) async { final _Setter? setter = _setters[valueType]; if (setter == null) { throw PlatformException( code: 'InvalidOperation', message: '"$valueType" is not a supported type.'); } await setter(key, value); return true; } }
packages/packages/shared_preferences/shared_preferences_foundation/lib/shared_preferences_foundation.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/lib/shared_preferences_foundation.dart", "repo_id": "packages", "token_count": 1093 }
1,117
name: standard_message_codec_examples description: Example code for standard message codec usage version: 0.0.1 publish_to: none environment: sdk: ^3.1.0 dependencies: standard_message_codec: path: ../ dev_dependencies: build_runner: ^2.1.10
packages/packages/standard_message_codec/example/pubspec.yaml/0
{ "file_path": "packages/packages/standard_message_codec/example/pubspec.yaml", "repo_id": "packages", "token_count": 93 }
1,118
#Wed Jul 31 20:16:04 BRT 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-all.zip
packages/packages/url_launcher/url_launcher/example/android/gradle/wrapper/gradle-wrapper.properties/0
{ "file_path": "packages/packages/url_launcher/url_launcher/example/android/gradle/wrapper/gradle-wrapper.properties", "repo_id": "packages", "token_count": 86 }
1,119
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:url_launcher_platform_interface/link.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; import 'types.dart'; import 'url_launcher_uri.dart'; /// The function used to push routes to the Flutter framework. @visibleForTesting Future<ByteData> Function(Object?, String) pushRouteToFrameworkFunction = pushRouteNameToFramework; /// A widget that renders a real link on the web, and uses WebViews in native /// platforms to open links. /// /// Example link to an external URL: /// /// ```dart /// Link( /// uri: Uri.parse('https://flutter.dev'), /// builder: (BuildContext context, FollowLink? followLink) => ElevatedButton( /// onPressed: followLink, /// // ... other properties here ... /// )}, /// ); /// ``` /// /// Example link to a route name within the app: /// /// ```dart /// Link( /// uri: Uri.parse('/home'), /// builder: (BuildContext context, FollowLink? followLink) => ElevatedButton( /// onPressed: followLink, /// // ... other properties here ... /// )}, /// ); /// ``` class Link extends StatelessWidget implements LinkInfo { /// Creates a widget that renders a real link on the web, and uses WebViews in /// native platforms to open links. const Link({ super.key, required this.uri, this.target = LinkTarget.defaultTarget, required this.builder, }); /// Called at build time to construct the widget tree under the link. @override final LinkWidgetBuilder builder; /// The destination that this link leads to. @override final Uri? uri; /// The target indicating where to open the link. @override final LinkTarget target; /// Whether the link is disabled or not. @override bool get isDisabled => uri == null; LinkDelegate get _effectiveDelegate { return UrlLauncherPlatform.instance.linkDelegate ?? DefaultLinkDelegate.create; } @override Widget build(BuildContext context) { return _effectiveDelegate(this); } } /// The default delegate used on non-web platforms. /// /// For external URIs, it uses url_launche APIs. For app route names, it uses /// event channel messages to instruct the framework to push the route name. class DefaultLinkDelegate extends StatelessWidget { /// Creates a delegate for the given [link]. const DefaultLinkDelegate(this.link, {super.key}); /// Given a [link], creates an instance of [DefaultLinkDelegate]. /// /// This is a static method so it can be used as a tear-off. static DefaultLinkDelegate create(LinkInfo link) { return DefaultLinkDelegate(link); } /// Information about the link built by the app. final LinkInfo link; bool get _useWebView { if (link.target == LinkTarget.self) { return true; } if (link.target == LinkTarget.blank) { return false; } return false; } Future<void> _followLink(BuildContext context) async { final Uri url = link.uri!; if (!url.hasScheme) { // A uri that doesn't have a scheme is an internal route name. In this // case, we push it via Flutter's navigation system instead of letting the // browser handle it. final String routeName = link.uri.toString(); await pushRouteToFrameworkFunction(context, routeName); return; } // At this point, we know that the link is external. So we use the // `launchUrl` API to open the link. bool success; try { success = await launchUrl( url, mode: _useWebView ? LaunchMode.inAppBrowserView : LaunchMode.externalApplication, ); } on PlatformException { success = false; } if (!success) { FlutterError.reportError(FlutterErrorDetails( exception: 'Could not launch link $url', stack: StackTrace.current, library: 'url_launcher', context: ErrorDescription('during launching a link'), )); } } @override Widget build(BuildContext context) { return link.builder( context, link.isDisabled ? null : () => _followLink(context), ); } }
packages/packages/url_launcher/url_launcher/lib/src/link.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher/lib/src/link.dart", "repo_id": "packages", "token_count": 1439 }
1,120
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.urllauncherexample"> <!-- The INTERNET permission is required for development. Specifically, flutter needs it to communicate with the running application to allow setting breakpoints, to provide hot reload, etc. --> <uses-permission android:name="android.permission.INTERNET"/> <!-- Provide required visibility configuration for API level 30 and above --> <queries> <intent> <action android:name="android.intent.action.VIEW" /> <data android:scheme="https" /> </intent> <intent> <action android:name="android.intent.action.DIAL" /> <data android:scheme="tel" /> </intent> </queries> <application android:icon="@mipmap/ic_launcher" android:label="url_launcher_example"> <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection" android:hardwareAccelerated="true" android:name="io.flutter.embedding.android.FlutterActivity" android:theme="@android:style/Theme.Black.NoTitleBar" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <meta-data android:name="flutterEmbedding" android:value="2"/> </application> </manifest>
packages/packages/url_launcher/url_launcher_android/example/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/example/android/app/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 512 }
1,121
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import UIKit /// Protocol for UIApplication methods relating to launching URLs. /// /// This protocol exists to allow injecting an alternate implementation for testing. protocol Launcher { /// Returns a Boolean value that indicates whether an app is available to handle a URL scheme. func canOpenURL(_ url: URL) -> Bool /// Attempts to asynchronously open the resource at the specified URL. func open( _ url: URL, options: [UIApplication.OpenExternalURLOptionsKey: Any], completionHandler completion: ((Bool) -> Void)?) } /// Launcher is intentionally a direct passthroguh to UIApplication. extension UIApplication: Launcher {}
packages/packages/url_launcher/url_launcher_ios/ios/Classes/Launcher.swift/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/ios/Classes/Launcher.swift", "repo_id": "packages", "token_count": 213 }
1,122
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v10.1.3), do not edit directly. // See also: https://pub.dev/packages/pigeon import Foundation #if os(iOS) import Flutter #elseif os(macOS) import FlutterMacOS #else #error("Unsupported platform.") #endif private func wrapResult(_ result: Any?) -> [Any?] { return [result] } private func wrapError(_ error: Any) -> [Any?] { if let flutterError = error as? FlutterError { return [ flutterError.code, flutterError.message, flutterError.details, ] } return [ "\(error)", "\(type(of: error))", "Stacktrace: \(Thread.callStackSymbols)", ] } private func nilOrValue<T>(_ value: Any?) -> T? { if value is NSNull { return nil } return value as! T? } /// Possible error conditions for [UrlLauncherApi] calls. enum UrlLauncherError: Int { /// The URL could not be parsed as an NSURL. case invalidUrl = 0 } /// Possible results for a [UrlLauncherApi] call with a boolean outcome. /// /// Generated class from Pigeon that represents data sent in messages. struct UrlLauncherBoolResult { var value: Bool var error: UrlLauncherError? = nil static func fromList(_ list: [Any?]) -> UrlLauncherBoolResult? { let value = list[0] as! Bool var error: UrlLauncherError? = nil let errorEnumVal: Int? = nilOrValue(list[1]) if let errorRawValue = errorEnumVal { error = UrlLauncherError(rawValue: errorRawValue)! } return UrlLauncherBoolResult( value: value, error: error ) } func toList() -> [Any?] { return [ value, error?.rawValue, ] } } private class UrlLauncherApiCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { case 128: return UrlLauncherBoolResult.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } } } private class UrlLauncherApiCodecWriter: FlutterStandardWriter { override func writeValue(_ value: Any) { if let value = value as? UrlLauncherBoolResult { super.writeByte(128) super.writeValue(value.toList()) } else { super.writeValue(value) } } } private class UrlLauncherApiCodecReaderWriter: FlutterStandardReaderWriter { override func reader(with data: Data) -> FlutterStandardReader { return UrlLauncherApiCodecReader(data: data) } override func writer(with data: NSMutableData) -> FlutterStandardWriter { return UrlLauncherApiCodecWriter(data: data) } } class UrlLauncherApiCodec: FlutterStandardMessageCodec { static let shared = UrlLauncherApiCodec(readerWriter: UrlLauncherApiCodecReaderWriter()) } /// Generated protocol from Pigeon that represents a handler of messages from Flutter. protocol UrlLauncherApi { /// Returns a true result if the URL can definitely be launched. func canLaunch(url: String) throws -> UrlLauncherBoolResult /// Opens the URL externally, returning a true result if successful. func launch(url: String) throws -> UrlLauncherBoolResult } /// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. class UrlLauncherApiSetup { /// The codec used by UrlLauncherApi. static var codec: FlutterStandardMessageCodec { UrlLauncherApiCodec.shared } /// Sets up an instance of `UrlLauncherApi` to handle messages through the `binaryMessenger`. static func setUp(binaryMessenger: FlutterBinaryMessenger, api: UrlLauncherApi?) { /// Returns a true result if the URL can definitely be launched. let canLaunchUrlChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.UrlLauncherApi.canLaunchUrl", binaryMessenger: binaryMessenger, codec: codec) if let api = api { canLaunchUrlChannel.setMessageHandler { message, reply in let args = message as! [Any?] let urlArg = args[0] as! String do { let result = try api.canLaunch(url: urlArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { canLaunchUrlChannel.setMessageHandler(nil) } /// Opens the URL externally, returning a true result if successful. let launchUrlChannel = FlutterBasicMessageChannel( name: "dev.flutter.pigeon.UrlLauncherApi.launchUrl", binaryMessenger: binaryMessenger, codec: codec) if let api = api { launchUrlChannel.setMessageHandler { message, reply in let args = message as! [Any?] let urlArg = args[0] as! String do { let result = try api.launch(url: urlArg) reply(wrapResult(result)) } catch { reply(wrapError(error)) } } } else { launchUrlChannel.setMessageHandler(nil) } } }
packages/packages/url_launcher/url_launcher_macos/macos/Classes/messages.g.swift/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/macos/Classes/messages.g.swift", "repo_id": "packages", "token_count": 1774 }
1,123
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { test('InAppBrowserConfiguration defaults to showTitle false', () { expect(const InAppBrowserConfiguration().showTitle, false); }); test('InAppBrowserConfiguration showTitle can be set to true', () { expect(const InAppBrowserConfiguration(showTitle: true).showTitle, true); }); }
packages/packages/url_launcher/url_launcher_platform_interface/test/in_app_browser_configuration_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_platform_interface/test/in_app_browser_configuration_test.dart", "repo_id": "packages", "token_count": 173 }
1,124
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <windows.h> namespace url_launcher_windows { // An interface wrapping system APIs used by the plugin, for mocking. class SystemApis { public: SystemApis(); virtual ~SystemApis(); // Disallow copy and move. SystemApis(const SystemApis&) = delete; SystemApis& operator=(const SystemApis&) = delete; // Wrapper for RegCloseKey. virtual LSTATUS RegCloseKey(HKEY key) = 0; // Wrapper for RegQueryValueEx. virtual LSTATUS RegQueryValueExW(HKEY key, LPCWSTR value_name, LPDWORD type, LPBYTE data, LPDWORD data_size) = 0; // Wrapper for RegOpenKeyEx. virtual LSTATUS RegOpenKeyExW(HKEY key, LPCWSTR sub_key, DWORD options, REGSAM desired, PHKEY result) = 0; // Wrapper for ShellExecute. virtual HINSTANCE ShellExecuteW(HWND hwnd, LPCWSTR operation, LPCWSTR file, LPCWSTR parameters, LPCWSTR directory, int show_flags) = 0; }; // Implementation of SystemApis using the Win32 APIs. class SystemApisImpl : public SystemApis { public: SystemApisImpl(); virtual ~SystemApisImpl(); // Disallow copy and move. SystemApisImpl(const SystemApisImpl&) = delete; SystemApisImpl& operator=(const SystemApisImpl&) = delete; // SystemApis Implementation: virtual LSTATUS RegCloseKey(HKEY key); virtual LSTATUS RegOpenKeyExW(HKEY key, LPCWSTR sub_key, DWORD options, REGSAM desired, PHKEY result); virtual LSTATUS RegQueryValueExW(HKEY key, LPCWSTR value_name, LPDWORD type, LPBYTE data, LPDWORD data_size); virtual HINSTANCE ShellExecuteW(HWND hwnd, LPCWSTR operation, LPCWSTR file, LPCWSTR parameters, LPCWSTR directory, int show_flags); }; } // namespace url_launcher_windows
packages/packages/url_launcher/url_launcher_windows/windows/system_apis.h/0
{ "file_path": "packages/packages/url_launcher/url_launcher_windows/windows/system_apis.h", "repo_id": "packages", "token_count": 860 }
1,125
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/video_player/video_player/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/video_player/video_player/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
1,126
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:video_player/src/closed_caption_file.dart'; import 'package:video_player/video_player.dart'; void main() { test('Parses SubRip file', () { final SubRipCaptionFile parsedFile = SubRipCaptionFile(_validSubRip); expect(parsedFile.captions.length, 4); final Caption firstCaption = parsedFile.captions.first; expect(firstCaption.number, 1); expect(firstCaption.start, const Duration(seconds: 6)); expect(firstCaption.end, const Duration(seconds: 12, milliseconds: 74)); expect(firstCaption.text, 'This is a test file'); final Caption secondCaption = parsedFile.captions[1]; expect(secondCaption.number, 2); expect( secondCaption.start, const Duration(minutes: 1, seconds: 54, milliseconds: 724), ); expect( secondCaption.end, const Duration(minutes: 1, seconds: 56, milliseconds: 760), ); expect(secondCaption.text, '- Hello.\n- Yes?'); final Caption thirdCaption = parsedFile.captions[2]; expect(thirdCaption.number, 3); expect( thirdCaption.start, const Duration(minutes: 1, seconds: 56, milliseconds: 884), ); expect( thirdCaption.end, const Duration(minutes: 1, seconds: 58, milliseconds: 954), ); expect( thirdCaption.text, 'These are more test lines\nYes, these are more test lines.', ); final Caption fourthCaption = parsedFile.captions[3]; expect(fourthCaption.number, 4); expect( fourthCaption.start, const Duration(hours: 1, minutes: 1, seconds: 59, milliseconds: 84), ); expect( fourthCaption.end, const Duration(hours: 1, minutes: 2, seconds: 1, milliseconds: 552), ); expect( fourthCaption.text, "- [ Machinery Beeping ]\n- I'm not sure what that was,", ); }); test('Parses SubRip file with malformed input', () { final ClosedCaptionFile parsedFile = SubRipCaptionFile(_malformedSubRip); expect(parsedFile.captions.length, 1); final Caption firstCaption = parsedFile.captions.single; expect(firstCaption.number, 2); expect(firstCaption.start, const Duration(seconds: 15)); expect(firstCaption.end, const Duration(seconds: 17, milliseconds: 74)); expect(firstCaption.text, 'This one is valid'); }); } const String _validSubRip = ''' 1 00:00:06,000 --> 00:00:12,074 This is a test file 2 00:01:54,724 --> 00:01:56,760 - Hello. - Yes? 3 00:01:56,884 --> 00:01:58,954 These are more test lines Yes, these are more test lines. 4 01:01:59,084 --> 01:02:01,552 - [ Machinery Beeping ] - I'm not sure what that was, '''; const String _malformedSubRip = ''' 1 00:00:06,000--> 00:00:12,074 This one should be ignored because the arrow needs a space. 2 00:00:15,000 --> 00:00:17,074 This one is valid 3 00:01:54,724 --> 00:01:6,760 This one should be ignored because the ned time is missing a digit. ''';
packages/packages/video_player/video_player/test/sub_rip_file_test.dart/0
{ "file_path": "packages/packages/video_player/video_player/test/sub_rip_file_test.dart", "repo_id": "packages", "token_count": 1158 }
1,127
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import <Foundation/Foundation.h> #if TARGET_OS_OSX #import <FlutterMacOS/FlutterMacOS.h> #else #import <Flutter/Flutter.h> #endif // A cross-platform display link abstraction. @interface FVPDisplayLink : NSObject /// Whether the display link is currently running (i.e., firing events). /// /// Defaults to NO. @property(nonatomic, assign) BOOL running; /// Initializes a display link that calls the given callback when fired. /// /// The display link starts paused, so must be started, by setting 'running' to YES, before the /// callback will fire. - (instancetype)initWithRegistrar:(id<FlutterPluginRegistrar>)registrar callback:(void (^)(void))callback NS_DESIGNATED_INITIALIZER; - (instancetype)init NS_UNAVAILABLE; @end
packages/packages/video_player/video_player_avfoundation/darwin/Classes/FVPDisplayLink.h/0
{ "file_path": "packages/packages/video_player/video_player_avfoundation/darwin/Classes/FVPDisplayLink.h", "repo_id": "packages", "token_count": 303 }
1,128
# video_player_platform_interface A common platform interface for the [`video_player`][1] plugin. This interface allows platform-specific implementations of the `video_player` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `video_player`, extend [`VideoPlayerPlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `VideoPlayerPlatform` by calling `VideoPlayerPlatform.instance = MyPlatformVideoPlayer()`. # Note on breaking changes Strongly prefer non-breaking changes (such as adding a method to the interface) over breaking changes for this package. See https://flutter.dev/go/platform-interface-breaking-changes for a discussion on why a less-clean interface is preferable to a breaking change. [1]: ../video_player [2]: lib/video_player_platform_interface.dart
packages/packages/video_player/video_player_platform_interface/README.md/0
{ "file_path": "packages/packages/video_player/video_player_platform_interface/README.md", "repo_id": "packages", "token_count": 236 }
1,129
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:video_player_platform_interface/video_player_platform_interface.dart'; import 'package:video_player_web/video_player_web.dart'; import 'utils.dart'; // Use WebM to allow CI to run tests in Chromium. const String _videoAssetKey = 'assets/Butterfly-209.webm'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('VideoPlayerWeb plugin (hits network)', () { late Future<int> textureId; setUp(() { VideoPlayerPlatform.instance = VideoPlayerPlugin(); textureId = VideoPlayerPlatform.instance .create( DataSource( sourceType: DataSourceType.network, uri: getUrlForAssetAsNetworkSource(_videoAssetKey), ), ) .then((int? textureId) => textureId!); }); testWidgets('can init', (WidgetTester tester) async { expect(VideoPlayerPlatform.instance.init(), completes); }); testWidgets('can create from network', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.create( DataSource( sourceType: DataSourceType.network, uri: getUrlForAssetAsNetworkSource(_videoAssetKey), ), ), completion(isNonZero)); }); testWidgets('can create from asset', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.create( DataSource( sourceType: DataSourceType.asset, asset: 'videos/bee.mp4', package: 'bee_vids', ), ), completion(isNonZero)); }); testWidgets('cannot create from file', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.create( DataSource( sourceType: DataSourceType.file, uri: '/videos/bee.mp4', ), ), throwsUnimplementedError); }); testWidgets('cannot create from content URI', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.create( DataSource( sourceType: DataSourceType.contentUri, uri: 'content://video', ), ), throwsUnimplementedError); }); testWidgets('can dispose', (WidgetTester tester) async { expect(VideoPlayerPlatform.instance.dispose(await textureId), completes); }); testWidgets('can set looping', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.setLooping(await textureId, true), completes, ); }); testWidgets('can play', (WidgetTester tester) async { // Mute video to allow autoplay (See https://goo.gl/xX8pDD) await VideoPlayerPlatform.instance.setVolume(await textureId, 0); expect(VideoPlayerPlatform.instance.play(await textureId), completes); }); testWidgets('throws PlatformException when playing bad media', (WidgetTester tester) async { final int videoPlayerId = (await VideoPlayerPlatform.instance.create( DataSource( sourceType: DataSourceType.network, uri: getUrlForAssetAsNetworkSource('assets/__non_existent.webm'), ), ))!; final Stream<VideoEvent> eventStream = VideoPlayerPlatform.instance.videoEventsFor(videoPlayerId); // Mute video to allow autoplay (See https://goo.gl/xX8pDD) await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0); await VideoPlayerPlatform.instance.play(videoPlayerId); expect(() async { await eventStream.timeout(const Duration(seconds: 5)).last; }, throwsA(isA<PlatformException>())); }); testWidgets('can pause', (WidgetTester tester) async { expect(VideoPlayerPlatform.instance.pause(await textureId), completes); }); testWidgets('can set volume', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.setVolume(await textureId, 0.8), completes, ); }); testWidgets('can set playback speed', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.setPlaybackSpeed(await textureId, 2.0), completes, ); }); testWidgets('can seek to position', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.seekTo( await textureId, const Duration(seconds: 1), ), completes, ); }); testWidgets('can get position', (WidgetTester tester) async { expect(VideoPlayerPlatform.instance.getPosition(await textureId), completion(isInstanceOf<Duration>())); }); testWidgets('can get video event stream', (WidgetTester tester) async { expect(VideoPlayerPlatform.instance.videoEventsFor(await textureId), isInstanceOf<Stream<VideoEvent>>()); }); testWidgets('can build view', (WidgetTester tester) async { expect(VideoPlayerPlatform.instance.buildView(await textureId), isInstanceOf<Widget>()); }); testWidgets('ignores setting mixWithOthers', (WidgetTester tester) async { expect(VideoPlayerPlatform.instance.setMixWithOthers(true), completes); expect(VideoPlayerPlatform.instance.setMixWithOthers(false), completes); }); testWidgets( 'double call to play will emit a single isPlayingStateUpdate event', (WidgetTester tester) async { final int videoPlayerId = await textureId; final Stream<VideoEvent> eventStream = VideoPlayerPlatform.instance.videoEventsFor(videoPlayerId); final Future<List<VideoEvent>> stream = eventStream.timeout( const Duration(seconds: 2), onTimeout: (EventSink<VideoEvent> sink) { sink.close(); }, ).toList(); await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0); await VideoPlayerPlatform.instance.play(videoPlayerId); await VideoPlayerPlatform.instance.play(videoPlayerId); // Let the video play, until we stop seeing events for two seconds final List<VideoEvent> events = await stream; await VideoPlayerPlatform.instance.pause(videoPlayerId); expect( events.where((VideoEvent e) => e.eventType == VideoEventType.isPlayingStateUpdate), equals(<VideoEvent>[ VideoEvent( eventType: VideoEventType.isPlayingStateUpdate, isPlaying: true, ) ])); }); testWidgets('video playback lifecycle', (WidgetTester tester) async { final int videoPlayerId = await textureId; final Stream<VideoEvent> eventStream = VideoPlayerPlatform.instance.videoEventsFor(videoPlayerId); final Future<List<VideoEvent>> stream = eventStream.timeout( const Duration(seconds: 2), onTimeout: (EventSink<VideoEvent> sink) { sink.close(); }, ).toList(); await VideoPlayerPlatform.instance.setVolume(videoPlayerId, 0); await VideoPlayerPlatform.instance.play(videoPlayerId); // Let the video play, until we stop seeing events for two seconds final List<VideoEvent> events = await stream; await VideoPlayerPlatform.instance.pause(videoPlayerId); // The expected list of event types should look like this: // 1. isPlayingStateUpdate (videoElement.onPlaying) // 2. bufferingStart, // 3. bufferingUpdate (videoElement.onWaiting), // 4. initialized (videoElement.onCanPlay), // 5. bufferingEnd (videoElement.onCanPlayThrough), expect( events.map((VideoEvent e) => e.eventType), equals(<VideoEventType>[ VideoEventType.isPlayingStateUpdate, VideoEventType.bufferingStart, VideoEventType.bufferingUpdate, VideoEventType.initialized, VideoEventType.bufferingEnd, ])); }); testWidgets('can set web options', (WidgetTester tester) async { expect( VideoPlayerPlatform.instance.setWebOptions( await textureId, const VideoPlayerWebOptions(), ), completes, ); }); }); }
packages/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart/0
{ "file_path": "packages/packages/video_player/video_player_web/example/integration_test/video_player_web_test.dart", "repo_id": "packages", "token_count": 3386 }
1,130
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #docregion analyze import 'dart:convert'; import 'dart:io'; import 'package:web_benchmarks/analysis.dart'; void main() { final BenchmarkResults baselineResults = _benchmarkResultsFromFile('/path/to/benchmark_baseline.json'); final BenchmarkResults testResults1 = _benchmarkResultsFromFile('/path/to/benchmark_test_1.json'); final BenchmarkResults testResults2 = _benchmarkResultsFromFile('/path/to/benchmark_test_2.json'); // Compute the delta between [baselineResults] and [testResults1]. final BenchmarkResults delta = computeDelta(baselineResults, testResults1); stdout.writeln(delta.toJson()); // Compute the average of [testResults] and [testResults2]. final BenchmarkResults average = computeAverage(<BenchmarkResults>[testResults1, testResults2]); stdout.writeln(average.toJson()); } BenchmarkResults _benchmarkResultsFromFile(String path) { final File file = File.fromUri(Uri.parse(path)); final Map<String, Object?> fileContentAsJson = jsonDecode(file.readAsStringSync()) as Map<String, Object?>; return BenchmarkResults.parse(fileContentAsJson); } // #enddocregion analyze
packages/packages/web_benchmarks/example/analyze_example.dart/0
{ "file_path": "packages/packages/web_benchmarks/example/analyze_example.dart", "repo_id": "packages", "token_count": 414 }
1,131
# `testing` README ## How to run the `testing` directory tests The benchmarks contained in this directory use a client-server model, similar to what the integration_test package does. In order to run the tests inside `testing`, do the following: * Install Chrome in a way that [tests can find it](https://github.com/flutter/packages/blob/a5a4479e176c5e909dd5d961c2c79b61ce1bf1bd/packages/web_benchmarks/lib/src/browser.dart#L216). * Fetch dependencies for the `test_app` directory inside `testing`: ```bash flutter pub get --directory testing/test_app ``` * Fetch dependencies for the `web_benchmarks` directory: ```bash flutter pub get ``` * Run the tests with `flutter test`: ```bash $ flutter test testing 00:03 +0: Can run a web benchmark Launching Chrome. Launching Google Chrome 98.0.4758.102 Waiting for the benchmark to report benchmark profile. [CHROME]: [0215/133233.327761:ERROR:socket_posix.cc(150)] bind() failed: Address already in use (98) [CHROME]: [CHROME]: DevTools listening on ws://[::1]:10000/devtools/browser/4ef82be6-9b68-4fd3-ab90-cd603d25ceb1 Connecting to DevTools: ws://localhost:10000/devtools/page/21E7271507E9BC796B957E075515520F Connected to Chrome tab: (http://localhost:9999/index.html) Launching benchmark "scroll" Extracted 299 measured frames. Skipped 1 non-measured frames. Launching benchmark "page" [APP] Testing round 0... [APP] Testing round 1... [APP] Testing round 2... [APP] Testing round 3... [APP] Testing round 4... [APP] Testing round 5... [APP] Testing round 6... [APP] Testing round 7... [APP] Testing round 8... [APP] Testing round 9... Extracted 490 measured frames. Skipped 0 non-measured frames. Launching benchmark "tap" [APP] Testing round 0... [APP] Testing round 1... [APP] Testing round 2... [APP] Testing round 3... [APP] Testing round 4... [APP] Testing round 5... [APP] Testing round 6... [APP] Testing round 7... [APP] Testing round 8... [APP] Testing round 9... Extracted 299 measured frames. Skipped 0 non-measured frames. Received profile data 00:26 +1: All tests passed! ``` _(If the above stops working, take a look at what the [`web_benchmarks_test` Cirrus step](https://github.com/flutter/packages/blob/a5a4479e176c5e909dd5d961c2c79b61ce1bf1bd/.cirrus.yml#L102-L113) is currently doing, and update this document accordingly!)_
packages/packages/web_benchmarks/testing/README.md/0
{ "file_path": "packages/packages/web_benchmarks/testing/README.md", "repo_id": "packages", "token_count": 805 }
1,132
## 3.16.0 * Adds onReceivedHttpError WebViewClient callback to support `PlatformNavigationDelegate.onHttpError`. * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. * Updates compileSdk to 34. ## 3.15.0 * Adds support for `setOnScrollPositionChange` method to the `AndroidWebViewController`. ## 3.14.0 * Adds support to show JavaScript dialog. See `AndroidWebViewController.setOnJavaScriptAlertDialog`, `AndroidWebViewController.setOnJavaScriptConfirmDialog` and `AndroidWebViewController.setOnJavaScriptTextInputDialog`. ## 3.13.2 * Fixes new lint warnings. ## 3.13.1 * Bumps androidx.annotation:annotation from 1.7.0 to 1.7.1. ## 3.13.0 * Adds support for `PlatformNavigationDelegate.setOnHttpAuthRequest`. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 3.12.1 * Fixes `use_build_context_synchronously` lint violations in the example app. ## 3.12.0 * Adds support for `PlatformWebViewController.getUserAgent`. ## 3.11.0 * Adds support to register a callback to receive JavaScript console messages. See `AndroidWebViewController.onConsoleMessage`. ## 3.10.1 * Bumps androidx.annotation:annotation from 1.5.0 to 1.7.0. ## 3.10.0 * Adds support for playing video in fullscreen. See `AndroidWebViewController.setCustomWidgetCallbacks`. ## 3.9.5 * Updates pigeon to 11 and removes unneeded enum wrappers. ## 3.9.4 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 3.9.3 * Fixes bug where the `PlatformWebViewWidget` was rebuilt unnecessarily. ## 3.9.2 * Fixes bug where `PlatformWebViewWidget` doesn't rebuild when the controller or PlatformView implementation flag changes. ## 3.9.1 * Adjusts SDK checks for better testability. ## 3.9.0 * Adds support for `WebResouceError.url`. ## 3.8.2 * Fixes unawaited_futures violations. ## 3.8.1 * Bumps androidx.webkit:webkit from 1.6.0 to 1.7.0. ## 3.8.0 * Adds support for handling geolocation permissions. See `AndroidWebViewController.setGeolocationPermissionsPromptCallbacks`. ## 3.7.1 * Removes obsolete null checks on non-nullable values. ## 3.7.0 * Adds support to accept third party cookies. See `AndroidWebViewCookieManager.setAcceptThirdPartyCookies`. ## 3.6.3 * Updates gradle, AGP and fixes some lint errors. ## 3.6.2 * Fixes compatibility with AGP versions older than 4.2. ## 3.6.1 * Adds a namespace for compatibility with AGP 8.0. ## 3.6.0 * Adds support for `PlatformWebViewController.setOnPlatformPermissionRequest`. ## 3.5.3 * Bumps gradle from 7.2.2 to 8.0.0. ## 3.5.2 * Updates internal Java InstanceManager to only stop finalization callbacks when stopped. ## 3.5.1 * Updates pigeon dev dependency to `9.2.4`. * Fixes Android lint warnings. ## 3.5.0 * Adds support for `PlatformNavigationDelegate.onUrlChange`. * Bumps androidx.webkit:webkit from 1.6.0 to 1.6.1. * Fixes common typos in tests and documentation. ## 3.4.5 * Removes unused internal `WebView` field and Java class. ## 3.4.4 * Fixes a bug where the native `WebView` wouldn't be traversed for autofill automatically. * Updates minimum Flutter version to 3.3. ## 3.4.3 * Updates internal Java InstanceManager to be cleared on hot restart. ## 3.4.2 * Clarifies explanation of endorsement in README. ## 3.4.1 * Fixes a potential bug where a `WebView` that was not added to the `InstanceManager` could be returned by a `WebViewClient` or `WebChromeClient`. ## 3.4.0 * Adds support to set text zoom of a page. See `AndroidWebViewController.setTextZoom`. * Aligns Dart and Flutter SDK constraints. ## 3.3.2 * Resolves compilations warnings. * Updates compileSdkVersion to 33. * Bumps androidx.webkit:webkit from 1.5.0 to 1.6.0. ## 3.3.1 * Updates links for the merge of flutter/plugins into flutter/packages. ## 3.3.0 * Adds support to access native `WebView`. ## 3.2.4 * Renames Pigeon output files. ## 3.2.3 * Fixes bug that prevented the web view from being garbage collected. * Fixes bug causing a `LateInitializationError` when a `PlatformNavigationDelegate` is not provided. ## 3.2.2 * Updates example code for `use_build_context_synchronously` lint. ## 3.2.1 * Updates code for stricter lint checks. ## 3.2.0 * Adds support for handling file selection. See `AndroidWebViewController.setOnShowFileSelector`. * Updates pigeon dev dependency to `4.2.14`. ## 3.1.3 * Fixes crash when the Java `InstanceManager` was used after plugin was removed from the engine. ## 3.1.2 * Fixes bug where an `AndroidWebViewController` couldn't be reused with a new `WebViewWidget`. ## 3.1.1 * Fixes bug where a `AndroidNavigationDelegate` was required to load a request. ## 3.1.0 * Adds support for selecting Hybrid Composition on versions 23+. Please use `AndroidWebViewControllerCreationParams.displayWithHybridComposition`. ## 3.0.0 * **BREAKING CHANGE** Updates platform implementation to `2.0.0` release of `webview_flutter_platform_interface`. See [webview_flutter](https://pub.dev/packages/webview_flutter/versions/4.0.0) for updated usage. ## 2.10.4 * Updates code for `no_leading_underscores_for_local_identifiers` lint. * Bumps androidx.annotation from 1.4.0 to 1.5.0. ## 2.10.3 * Updates imports for `prefer_relative_imports`. ## 2.10.2 * Adds a getter to expose the Java InstanceManager. ## 2.10.1 * Adds a method to the `WebView` wrapper to retrieve the X and Y positions simultaneously. * Removes reference to https://github.com/flutter/flutter/issues/97744 from `README`. ## 2.10.0 * Bumps webkit from 1.0.0 to 1.5.0. * Raises minimum `compileSdkVersion` to 32. ## 2.9.5 * Adds dispose methods for HostApi and FlutterApi of JavaObject. ## 2.9.4 * Fixes avoid_redundant_argument_values lint warnings and minor typos. * Bumps gradle from 7.2.1 to 7.2.2. ## 2.9.3 * Updates the Dart InstanceManager to take a listener for when an object is garbage collected. See https://github.com/flutter/flutter/issues/107199. ## 2.9.2 * Updates the Java InstanceManager to take a listener for when an object is garbage collected. See https://github.com/flutter/flutter/issues/107199. ## 2.9.1 * Updates Android WebView classes as Copyable. This is a part of moving the api to handle garbage collection automatically. See https://github.com/flutter/flutter/issues/107199. ## 2.9.0 * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/106316). * Fixes bug where `Directionality` from context didn't affect `SurfaceAndroidWebView`. * Fixes bug where default text direction was different for `SurfaceAndroidWebView` and `AndroidWebView`. Default is now `TextDirection.ltr` for both. * Fixes bug where setting WebView to a transparent background could cause visual errors when using `SurfaceAndroidWebView`. Hybrid composition is now used when the background color is not 100% opaque. * Raises minimum Flutter version to 3.0.0. ## 2.8.14 * Bumps androidx.annotation from 1.0.0 to 1.4.0. ## 2.8.13 * Fixes a bug which causes an exception when the `onNavigationRequestCallback` return `false`. ## 2.8.12 * Bumps mockito-inline from 3.11.1 to 4.6.1. ## 2.8.11 * Ignores unnecessary import warnings in preparation for [upcoming Flutter changes](https://github.com/flutter/flutter/pull/104231). ## 2.8.10 * Updates references to the obsolete master branch. ## 2.8.9 * Updates Gradle to 7.2.1. ## 2.8.8 * Minor fixes for new analysis options. ## 2.8.7 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 2.8.6 * Updates pigeon developer dependency to the latest version which adds support for null safety. ## 2.8.5 * Migrates deprecated `Scaffold.showSnackBar` to `ScaffoldMessenger` in example app. ## 2.8.4 * Fixes bug preventing `mockito` code generation for tests. * Fixes regression where local storage wasn't cleared when `WebViewController.clearCache` was called. ## 2.8.3 * Fixes a bug causing `debuggingEnabled` to always be set to true. * Fixes an integration test race condition. ## 2.8.2 * Adds the `WebSettings.setAllowFileAccess()` method and ensure that file access is allowed when the `WebViewAndroidWidget.loadFile()` method is executed. ## 2.8.1 * Fixes bug where the default user agent string was being set for every rebuild. See https://github.com/flutter/flutter/issues/94847. ## 2.8.0 * Implements new cookie manager for setting cookies and providing initial cookies. ## 2.7.0 * Adds support for the `loadRequest` method from the platform interface. ## 2.6.0 * Adds implementation of the `loadFlutterAsset` method from the platform interface. ## 2.5.0 * Adds an option to set the background color of the webview. ## 2.4.0 * Adds support for Android's `WebView.loadData` and `WebView.loadDataWithBaseUrl` methods and implements the `loadFile` and `loadHtmlString` methods from the platform interface. * Updates to webview_flutter_platform_interface version 1.5.2. ## 2.3.1 * Adds explanation on how to generate the pigeon communication layer and mockito mock objects. * Updates compileSdkVersion to 31. ## 2.3.0 * Replaces platform implementation with API built with pigeon. ## 2.2.1 * Fix `NullPointerException` from a race condition when changing focus. This only affects `WebView` when it is created without Hybrid Composition. ## 2.2.0 * Implemented new `runJavascript` and `runJavascriptReturningResult` methods in platform interface. ## 2.1.0 * Add `zoomEnabled` functionality. ## 2.0.15 * Added Overrides in FlutterWebView.java ## 2.0.14 * Update example App so navigation menu loads immediatly but only becomes available when `WebViewController` is available (same behavior as example App in webview_flutter package). ## 2.0.13 * Extract Android implementation from `webview_flutter`.
packages/packages/webview_flutter/webview_flutter_android/CHANGELOG.md/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/CHANGELOG.md", "repo_id": "packages", "token_count": 3154 }
1,133
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Autogenerated from Pigeon (v11.0.1), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.webviewflutter; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class GeneratedAndroidWebView { /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { /** The error code. */ public final String code; /** The error details. Must be a datatype supported by the api codec. */ public final Object details; public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) { super(message); this.code = code; this.details = details; } } @NonNull protected static ArrayList<Object> wrapError(@NonNull Throwable exception) { ArrayList<Object> errorList = new ArrayList<Object>(3); if (exception instanceof FlutterError) { FlutterError error = (FlutterError) exception; errorList.add(error.code); errorList.add(error.getMessage()); errorList.add(error.details); } else { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); } return errorList; } /** * Mode of how to select files for a file chooser. * * <p>See * https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams. */ public enum FileChooserMode { /** * Open single file and requires that the file exists before allowing the user to pick it. * * <p>See * https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN. */ OPEN(0), /** * Similar to [open] but allows multiple files to be selected. * * <p>See * https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_OPEN_MULTIPLE. */ OPEN_MULTIPLE(1), /** * Allows picking a nonexistent file and saving it. * * <p>See * https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams#MODE_SAVE. */ SAVE(2); final int index; private FileChooserMode(final int index) { this.index = index; } } /** * Indicates the type of message logged to the console. * * <p>See https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel. */ public enum ConsoleMessageLevel { /** * Indicates a message is logged for debugging. * * <p>See * https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#DEBUG. */ DEBUG(0), /** * Indicates a message is provided as an error. * * <p>See * https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#ERROR. */ ERROR(1), /** * Indicates a message is provided as a basic log message. * * <p>See * https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#LOG. */ LOG(2), /** * Indicates a message is provided as a tip. * * <p>See * https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#TIP. */ TIP(3), /** * Indicates a message is provided as a warning. * * <p>See * https://developer.android.com/reference/android/webkit/ConsoleMessage.MessageLevel#WARNING. */ WARNING(4), /** * Indicates a message with an unknown level. * * <p>This does not represent an actual value provided by the platform and only indicates a * value was provided that isn't currently supported. */ UNKNOWN(5); final int index; private ConsoleMessageLevel(final int index) { this.index = index; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class WebResourceRequestData { private @NonNull String url; public @NonNull String getUrl() { return url; } public void setUrl(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"url\" is null."); } this.url = setterArg; } private @NonNull Boolean isForMainFrame; public @NonNull Boolean getIsForMainFrame() { return isForMainFrame; } public void setIsForMainFrame(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"isForMainFrame\" is null."); } this.isForMainFrame = setterArg; } private @Nullable Boolean isRedirect; public @Nullable Boolean getIsRedirect() { return isRedirect; } public void setIsRedirect(@Nullable Boolean setterArg) { this.isRedirect = setterArg; } private @NonNull Boolean hasGesture; public @NonNull Boolean getHasGesture() { return hasGesture; } public void setHasGesture(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"hasGesture\" is null."); } this.hasGesture = setterArg; } private @NonNull String method; public @NonNull String getMethod() { return method; } public void setMethod(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"method\" is null."); } this.method = setterArg; } private @NonNull Map<String, String> requestHeaders; public @NonNull Map<String, String> getRequestHeaders() { return requestHeaders; } public void setRequestHeaders(@NonNull Map<String, String> setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"requestHeaders\" is null."); } this.requestHeaders = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ WebResourceRequestData() {} public static final class Builder { private @Nullable String url; public @NonNull Builder setUrl(@NonNull String setterArg) { this.url = setterArg; return this; } private @Nullable Boolean isForMainFrame; public @NonNull Builder setIsForMainFrame(@NonNull Boolean setterArg) { this.isForMainFrame = setterArg; return this; } private @Nullable Boolean isRedirect; public @NonNull Builder setIsRedirect(@Nullable Boolean setterArg) { this.isRedirect = setterArg; return this; } private @Nullable Boolean hasGesture; public @NonNull Builder setHasGesture(@NonNull Boolean setterArg) { this.hasGesture = setterArg; return this; } private @Nullable String method; public @NonNull Builder setMethod(@NonNull String setterArg) { this.method = setterArg; return this; } private @Nullable Map<String, String> requestHeaders; public @NonNull Builder setRequestHeaders(@NonNull Map<String, String> setterArg) { this.requestHeaders = setterArg; return this; } public @NonNull WebResourceRequestData build() { WebResourceRequestData pigeonReturn = new WebResourceRequestData(); pigeonReturn.setUrl(url); pigeonReturn.setIsForMainFrame(isForMainFrame); pigeonReturn.setIsRedirect(isRedirect); pigeonReturn.setHasGesture(hasGesture); pigeonReturn.setMethod(method); pigeonReturn.setRequestHeaders(requestHeaders); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(6); toListResult.add(url); toListResult.add(isForMainFrame); toListResult.add(isRedirect); toListResult.add(hasGesture); toListResult.add(method); toListResult.add(requestHeaders); return toListResult; } static @NonNull WebResourceRequestData fromList(@NonNull ArrayList<Object> list) { WebResourceRequestData pigeonResult = new WebResourceRequestData(); Object url = list.get(0); pigeonResult.setUrl((String) url); Object isForMainFrame = list.get(1); pigeonResult.setIsForMainFrame((Boolean) isForMainFrame); Object isRedirect = list.get(2); pigeonResult.setIsRedirect((Boolean) isRedirect); Object hasGesture = list.get(3); pigeonResult.setHasGesture((Boolean) hasGesture); Object method = list.get(4); pigeonResult.setMethod((String) method); Object requestHeaders = list.get(5); pigeonResult.setRequestHeaders((Map<String, String>) requestHeaders); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class WebResourceResponseData { private @NonNull Long statusCode; public @NonNull Long getStatusCode() { return statusCode; } public void setStatusCode(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"statusCode\" is null."); } this.statusCode = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ WebResourceResponseData() {} public static final class Builder { private @Nullable Long statusCode; public @NonNull Builder setStatusCode(@NonNull Long setterArg) { this.statusCode = setterArg; return this; } public @NonNull WebResourceResponseData build() { WebResourceResponseData pigeonReturn = new WebResourceResponseData(); pigeonReturn.setStatusCode(statusCode); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(1); toListResult.add(statusCode); return toListResult; } static @NonNull WebResourceResponseData fromList(@NonNull ArrayList<Object> list) { WebResourceResponseData pigeonResult = new WebResourceResponseData(); Object statusCode = list.get(0); pigeonResult.setStatusCode( (statusCode == null) ? null : ((statusCode instanceof Integer) ? (Integer) statusCode : (Long) statusCode)); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class WebResourceErrorData { private @NonNull Long errorCode; public @NonNull Long getErrorCode() { return errorCode; } public void setErrorCode(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"errorCode\" is null."); } this.errorCode = setterArg; } private @NonNull String description; public @NonNull String getDescription() { return description; } public void setDescription(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"description\" is null."); } this.description = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ WebResourceErrorData() {} public static final class Builder { private @Nullable Long errorCode; public @NonNull Builder setErrorCode(@NonNull Long setterArg) { this.errorCode = setterArg; return this; } private @Nullable String description; public @NonNull Builder setDescription(@NonNull String setterArg) { this.description = setterArg; return this; } public @NonNull WebResourceErrorData build() { WebResourceErrorData pigeonReturn = new WebResourceErrorData(); pigeonReturn.setErrorCode(errorCode); pigeonReturn.setDescription(description); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(errorCode); toListResult.add(description); return toListResult; } static @NonNull WebResourceErrorData fromList(@NonNull ArrayList<Object> list) { WebResourceErrorData pigeonResult = new WebResourceErrorData(); Object errorCode = list.get(0); pigeonResult.setErrorCode( (errorCode == null) ? null : ((errorCode instanceof Integer) ? (Integer) errorCode : (Long) errorCode)); Object description = list.get(1); pigeonResult.setDescription((String) description); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class WebViewPoint { private @NonNull Long x; public @NonNull Long getX() { return x; } public void setX(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"x\" is null."); } this.x = setterArg; } private @NonNull Long y; public @NonNull Long getY() { return y; } public void setY(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"y\" is null."); } this.y = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ WebViewPoint() {} public static final class Builder { private @Nullable Long x; public @NonNull Builder setX(@NonNull Long setterArg) { this.x = setterArg; return this; } private @Nullable Long y; public @NonNull Builder setY(@NonNull Long setterArg) { this.y = setterArg; return this; } public @NonNull WebViewPoint build() { WebViewPoint pigeonReturn = new WebViewPoint(); pigeonReturn.setX(x); pigeonReturn.setY(y); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(2); toListResult.add(x); toListResult.add(y); return toListResult; } static @NonNull WebViewPoint fromList(@NonNull ArrayList<Object> list) { WebViewPoint pigeonResult = new WebViewPoint(); Object x = list.get(0); pigeonResult.setX((x == null) ? null : ((x instanceof Integer) ? (Integer) x : (Long) x)); Object y = list.get(1); pigeonResult.setY((y == null) ? null : ((y instanceof Integer) ? (Integer) y : (Long) y)); return pigeonResult; } } /** * Represents a JavaScript console message from WebCore. * * <p>See https://developer.android.com/reference/android/webkit/ConsoleMessage * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class ConsoleMessage { private @NonNull Long lineNumber; public @NonNull Long getLineNumber() { return lineNumber; } public void setLineNumber(@NonNull Long setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"lineNumber\" is null."); } this.lineNumber = setterArg; } private @NonNull String message; public @NonNull String getMessage() { return message; } public void setMessage(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"message\" is null."); } this.message = setterArg; } private @NonNull ConsoleMessageLevel level; public @NonNull ConsoleMessageLevel getLevel() { return level; } public void setLevel(@NonNull ConsoleMessageLevel setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"level\" is null."); } this.level = setterArg; } private @NonNull String sourceId; public @NonNull String getSourceId() { return sourceId; } public void setSourceId(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"sourceId\" is null."); } this.sourceId = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ ConsoleMessage() {} public static final class Builder { private @Nullable Long lineNumber; public @NonNull Builder setLineNumber(@NonNull Long setterArg) { this.lineNumber = setterArg; return this; } private @Nullable String message; public @NonNull Builder setMessage(@NonNull String setterArg) { this.message = setterArg; return this; } private @Nullable ConsoleMessageLevel level; public @NonNull Builder setLevel(@NonNull ConsoleMessageLevel setterArg) { this.level = setterArg; return this; } private @Nullable String sourceId; public @NonNull Builder setSourceId(@NonNull String setterArg) { this.sourceId = setterArg; return this; } public @NonNull ConsoleMessage build() { ConsoleMessage pigeonReturn = new ConsoleMessage(); pigeonReturn.setLineNumber(lineNumber); pigeonReturn.setMessage(message); pigeonReturn.setLevel(level); pigeonReturn.setSourceId(sourceId); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(4); toListResult.add(lineNumber); toListResult.add(message); toListResult.add(level == null ? null : level.index); toListResult.add(sourceId); return toListResult; } static @NonNull ConsoleMessage fromList(@NonNull ArrayList<Object> list) { ConsoleMessage pigeonResult = new ConsoleMessage(); Object lineNumber = list.get(0); pigeonResult.setLineNumber( (lineNumber == null) ? null : ((lineNumber instanceof Integer) ? (Integer) lineNumber : (Long) lineNumber)); Object message = list.get(1); pigeonResult.setMessage((String) message); Object level = list.get(2); pigeonResult.setLevel(ConsoleMessageLevel.values()[(int) level]); Object sourceId = list.get(3); pigeonResult.setSourceId((String) sourceId); return pigeonResult; } } public interface Result<T> { @SuppressWarnings("UnknownNullness") void success(T result); void error(@NonNull Throwable error); } /** * Host API for managing the native `InstanceManager`. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface InstanceManagerHostApi { /** * Clear the native `InstanceManager`. * * <p>This is typically only used after a hot restart. */ void clear(); /** The codec used by InstanceManagerHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `InstanceManagerHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable InstanceManagerHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.InstanceManagerHostApi.clear", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { api.clear(); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Handles methods calls to the native Java Object class. * * <p>Also handles calls to remove the reference to an instance with `dispose`. * * <p>See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface JavaObjectHostApi { void dispose(@NonNull Long identifier); /** The codec used by JavaObjectHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `JavaObjectHostApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable JavaObjectHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.JavaObjectHostApi.dispose", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); try { api.dispose((identifierArg == null) ? null : identifierArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Handles callbacks methods for the native Java Object class. * * <p>See https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class JavaObjectFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public JavaObjectFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by JavaObjectFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } public void dispose(@NonNull Long identifierArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.JavaObjectFlutterApi.dispose", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(identifierArg)), channelReply -> callback.reply(null)); } } /** * Host API for `CookieManager`. * * <p>This class may handle instantiating and adding native object instances that are attached to * a Dart instance or handle method calls on the associated native class or an instance of the * class. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface CookieManagerHostApi { /** Handles attaching `CookieManager.instance` to a native instance. */ void attachInstance(@NonNull Long instanceIdentifier); /** Handles Dart method `CookieManager.setCookie`. */ void setCookie(@NonNull Long identifier, @NonNull String url, @NonNull String value); /** Handles Dart method `CookieManager.removeAllCookies`. */ void removeAllCookies(@NonNull Long identifier, @NonNull Result<Boolean> result); /** Handles Dart method `CookieManager.setAcceptThirdPartyCookies`. */ void setAcceptThirdPartyCookies( @NonNull Long identifier, @NonNull Long webViewIdentifier, @NonNull Boolean accept); /** The codec used by CookieManagerHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `CookieManagerHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable CookieManagerHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.attachInstance", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdentifierArg = (Number) args.get(0); try { api.attachInstance( (instanceIdentifierArg == null) ? null : instanceIdentifierArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setCookie", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); String urlArg = (String) args.get(1); String valueArg = (String) args.get(2); try { api.setCookie( (identifierArg == null) ? null : identifierArg.longValue(), urlArg, valueArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.removeAllCookies", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); Result<Boolean> resultCallback = new Result<Boolean>() { public void success(Boolean result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.removeAllCookies( (identifierArg == null) ? null : identifierArg.longValue(), resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.CookieManagerHostApi.setAcceptThirdPartyCookies", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); Number webViewIdentifierArg = (Number) args.get(1); Boolean acceptArg = (Boolean) args.get(2); try { api.setAcceptThirdPartyCookies( (identifierArg == null) ? null : identifierArg.longValue(), (webViewIdentifierArg == null) ? null : webViewIdentifierArg.longValue(), acceptArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class WebViewHostApiCodec extends StandardMessageCodec { public static final WebViewHostApiCodec INSTANCE = new WebViewHostApiCodec(); private WebViewHostApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return WebViewPoint.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof WebViewPoint) { stream.write(128); writeValue(stream, ((WebViewPoint) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface WebViewHostApi { void create(@NonNull Long instanceId); void loadData( @NonNull Long instanceId, @NonNull String data, @Nullable String mimeType, @Nullable String encoding); void loadDataWithBaseUrl( @NonNull Long instanceId, @Nullable String baseUrl, @NonNull String data, @Nullable String mimeType, @Nullable String encoding, @Nullable String historyUrl); void loadUrl( @NonNull Long instanceId, @NonNull String url, @NonNull Map<String, String> headers); void postUrl(@NonNull Long instanceId, @NonNull String url, @NonNull byte[] data); @Nullable String getUrl(@NonNull Long instanceId); @NonNull Boolean canGoBack(@NonNull Long instanceId); @NonNull Boolean canGoForward(@NonNull Long instanceId); void goBack(@NonNull Long instanceId); void goForward(@NonNull Long instanceId); void reload(@NonNull Long instanceId); void clearCache(@NonNull Long instanceId, @NonNull Boolean includeDiskFiles); void evaluateJavascript( @NonNull Long instanceId, @NonNull String javascriptString, @NonNull Result<String> result); @Nullable String getTitle(@NonNull Long instanceId); void scrollTo(@NonNull Long instanceId, @NonNull Long x, @NonNull Long y); void scrollBy(@NonNull Long instanceId, @NonNull Long x, @NonNull Long y); @NonNull Long getScrollX(@NonNull Long instanceId); @NonNull Long getScrollY(@NonNull Long instanceId); @NonNull WebViewPoint getScrollPosition(@NonNull Long instanceId); void setWebContentsDebuggingEnabled(@NonNull Boolean enabled); void setWebViewClient(@NonNull Long instanceId, @NonNull Long webViewClientInstanceId); void addJavaScriptChannel(@NonNull Long instanceId, @NonNull Long javaScriptChannelInstanceId); void removeJavaScriptChannel( @NonNull Long instanceId, @NonNull Long javaScriptChannelInstanceId); void setDownloadListener(@NonNull Long instanceId, @Nullable Long listenerInstanceId); void setWebChromeClient(@NonNull Long instanceId, @Nullable Long clientInstanceId); void setBackgroundColor(@NonNull Long instanceId, @NonNull Long color); /** The codec used by WebViewHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return WebViewHostApiCodec.INSTANCE; } /** Sets up an instance of `WebViewHostApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable WebViewHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.create((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadData", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String dataArg = (String) args.get(1); String mimeTypeArg = (String) args.get(2); String encodingArg = (String) args.get(3); try { api.loadData( (instanceIdArg == null) ? null : instanceIdArg.longValue(), dataArg, mimeTypeArg, encodingArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadDataWithBaseUrl", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String baseUrlArg = (String) args.get(1); String dataArg = (String) args.get(2); String mimeTypeArg = (String) args.get(3); String encodingArg = (String) args.get(4); String historyUrlArg = (String) args.get(5); try { api.loadDataWithBaseUrl( (instanceIdArg == null) ? null : instanceIdArg.longValue(), baseUrlArg, dataArg, mimeTypeArg, encodingArg, historyUrlArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.loadUrl", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String urlArg = (String) args.get(1); Map<String, String> headersArg = (Map<String, String>) args.get(2); try { api.loadUrl( (instanceIdArg == null) ? null : instanceIdArg.longValue(), urlArg, headersArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.postUrl", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String urlArg = (String) args.get(1); byte[] dataArg = (byte[]) args.get(2); try { api.postUrl( (instanceIdArg == null) ? null : instanceIdArg.longValue(), urlArg, dataArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getUrl", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { String output = api.getUrl((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoBack", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { Boolean output = api.canGoBack((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.canGoForward", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { Boolean output = api.canGoForward((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goBack", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.goBack((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.goForward", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.goForward((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.reload", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.reload((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.clearCache", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean includeDiskFilesArg = (Boolean) args.get(1); try { api.clearCache( (instanceIdArg == null) ? null : instanceIdArg.longValue(), includeDiskFilesArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.evaluateJavascript", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String javascriptStringArg = (String) args.get(1); Result<String> resultCallback = new Result<String>() { public void success(String result) { wrapped.add(0, result); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.evaluateJavascript( (instanceIdArg == null) ? null : instanceIdArg.longValue(), javascriptStringArg, resultCallback); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getTitle", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { String output = api.getTitle((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollTo", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number xArg = (Number) args.get(1); Number yArg = (Number) args.get(2); try { api.scrollTo( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (xArg == null) ? null : xArg.longValue(), (yArg == null) ? null : yArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.scrollBy", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number xArg = (Number) args.get(1); Number yArg = (Number) args.get(2); try { api.scrollBy( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (xArg == null) ? null : xArg.longValue(), (yArg == null) ? null : yArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollX", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { Long output = api.getScrollX((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollY", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { Long output = api.getScrollY((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.getScrollPosition", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { WebViewPoint output = api.getScrollPosition( (instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebContentsDebuggingEnabled", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Boolean enabledArg = (Boolean) args.get(0); try { api.setWebContentsDebuggingEnabled(enabledArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebViewClient", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number webViewClientInstanceIdArg = (Number) args.get(1); try { api.setWebViewClient( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (webViewClientInstanceIdArg == null) ? null : webViewClientInstanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.addJavaScriptChannel", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number javaScriptChannelInstanceIdArg = (Number) args.get(1); try { api.addJavaScriptChannel( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (javaScriptChannelInstanceIdArg == null) ? null : javaScriptChannelInstanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.removeJavaScriptChannel", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number javaScriptChannelInstanceIdArg = (Number) args.get(1); try { api.removeJavaScriptChannel( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (javaScriptChannelInstanceIdArg == null) ? null : javaScriptChannelInstanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setDownloadListener", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number listenerInstanceIdArg = (Number) args.get(1); try { api.setDownloadListener( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (listenerInstanceIdArg == null) ? null : listenerInstanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setWebChromeClient", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number clientInstanceIdArg = (Number) args.get(1); try { api.setWebChromeClient( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (clientInstanceIdArg == null) ? null : clientInstanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewHostApi.setBackgroundColor", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number colorArg = (Number) args.get(1); try { api.setBackgroundColor( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (colorArg == null) ? null : colorArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Flutter API for `WebView`. * * <p>This class may handle instantiating and adding Dart instances that are attached to a native * instance or receiving callback methods from an overridden native class. * * <p>See https://developer.android.com/reference/android/webkit/WebView. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class WebViewFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public WebViewFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by WebViewFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** Create a new Dart instance and add it to the `InstanceManager`. */ public void create(@NonNull Long identifierArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(identifierArg)), channelReply -> callback.reply(null)); } public void onScrollChanged( @NonNull Long webViewInstanceIdArg, @NonNull Long leftArg, @NonNull Long topArg, @NonNull Long oldLeftArg, @NonNull Long oldTopArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewFlutterApi.onScrollChanged", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList(webViewInstanceIdArg, leftArg, topArg, oldLeftArg, oldTopArg)), channelReply -> callback.reply(null)); } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface WebSettingsHostApi { void create(@NonNull Long instanceId, @NonNull Long webViewInstanceId); void setDomStorageEnabled(@NonNull Long instanceId, @NonNull Boolean flag); void setJavaScriptCanOpenWindowsAutomatically(@NonNull Long instanceId, @NonNull Boolean flag); void setSupportMultipleWindows(@NonNull Long instanceId, @NonNull Boolean support); void setJavaScriptEnabled(@NonNull Long instanceId, @NonNull Boolean flag); void setUserAgentString(@NonNull Long instanceId, @Nullable String userAgentString); void setMediaPlaybackRequiresUserGesture(@NonNull Long instanceId, @NonNull Boolean require); void setSupportZoom(@NonNull Long instanceId, @NonNull Boolean support); void setLoadWithOverviewMode(@NonNull Long instanceId, @NonNull Boolean overview); void setUseWideViewPort(@NonNull Long instanceId, @NonNull Boolean use); void setDisplayZoomControls(@NonNull Long instanceId, @NonNull Boolean enabled); void setBuiltInZoomControls(@NonNull Long instanceId, @NonNull Boolean enabled); void setAllowFileAccess(@NonNull Long instanceId, @NonNull Boolean enabled); void setTextZoom(@NonNull Long instanceId, @NonNull Long textZoom); @NonNull String getUserAgentString(@NonNull Long instanceId); /** The codec used by WebSettingsHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `WebSettingsHostApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable WebSettingsHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number webViewInstanceIdArg = (Number) args.get(1); try { api.create( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (webViewInstanceIdArg == null) ? null : webViewInstanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDomStorageEnabled", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean flagArg = (Boolean) args.get(1); try { api.setDomStorageEnabled( (instanceIdArg == null) ? null : instanceIdArg.longValue(), flagArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptCanOpenWindowsAutomatically", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean flagArg = (Boolean) args.get(1); try { api.setJavaScriptCanOpenWindowsAutomatically( (instanceIdArg == null) ? null : instanceIdArg.longValue(), flagArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportMultipleWindows", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean supportArg = (Boolean) args.get(1); try { api.setSupportMultipleWindows( (instanceIdArg == null) ? null : instanceIdArg.longValue(), supportArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setJavaScriptEnabled", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean flagArg = (Boolean) args.get(1); try { api.setJavaScriptEnabled( (instanceIdArg == null) ? null : instanceIdArg.longValue(), flagArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUserAgentString", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String userAgentStringArg = (String) args.get(1); try { api.setUserAgentString( (instanceIdArg == null) ? null : instanceIdArg.longValue(), userAgentStringArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setMediaPlaybackRequiresUserGesture", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean requireArg = (Boolean) args.get(1); try { api.setMediaPlaybackRequiresUserGesture( (instanceIdArg == null) ? null : instanceIdArg.longValue(), requireArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setSupportZoom", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean supportArg = (Boolean) args.get(1); try { api.setSupportZoom( (instanceIdArg == null) ? null : instanceIdArg.longValue(), supportArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setLoadWithOverviewMode", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean overviewArg = (Boolean) args.get(1); try { api.setLoadWithOverviewMode( (instanceIdArg == null) ? null : instanceIdArg.longValue(), overviewArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setUseWideViewPort", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean useArg = (Boolean) args.get(1); try { api.setUseWideViewPort( (instanceIdArg == null) ? null : instanceIdArg.longValue(), useArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setDisplayZoomControls", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean enabledArg = (Boolean) args.get(1); try { api.setDisplayZoomControls( (instanceIdArg == null) ? null : instanceIdArg.longValue(), enabledArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setBuiltInZoomControls", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean enabledArg = (Boolean) args.get(1); try { api.setBuiltInZoomControls( (instanceIdArg == null) ? null : instanceIdArg.longValue(), enabledArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setAllowFileAccess", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean enabledArg = (Boolean) args.get(1); try { api.setAllowFileAccess( (instanceIdArg == null) ? null : instanceIdArg.longValue(), enabledArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.setTextZoom", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Number textZoomArg = (Number) args.get(1); try { api.setTextZoom( (instanceIdArg == null) ? null : instanceIdArg.longValue(), (textZoomArg == null) ? null : textZoomArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebSettingsHostApi.getUserAgentString", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { String output = api.getUserAgentString( (instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface JavaScriptChannelHostApi { void create(@NonNull Long instanceId, @NonNull String channelName); /** The codec used by JavaScriptChannelHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `JavaScriptChannelHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable JavaScriptChannelHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String channelNameArg = (String) args.get(1); try { api.create( (instanceIdArg == null) ? null : instanceIdArg.longValue(), channelNameArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class JavaScriptChannelFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public JavaScriptChannelFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by JavaScriptChannelFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } public void postMessage( @NonNull Long instanceIdArg, @NonNull String messageArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.JavaScriptChannelFlutterApi.postMessage", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, messageArg)), channelReply -> callback.reply(null)); } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface WebViewClientHostApi { void create(@NonNull Long instanceId); void setSynchronousReturnValueForShouldOverrideUrlLoading( @NonNull Long instanceId, @NonNull Boolean value); /** The codec used by WebViewClientHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `WebViewClientHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable WebViewClientHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.create((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientHostApi.setSynchronousReturnValueForShouldOverrideUrlLoading", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean valueArg = (Boolean) args.get(1); try { api.setSynchronousReturnValueForShouldOverrideUrlLoading( (instanceIdArg == null) ? null : instanceIdArg.longValue(), valueArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class WebViewClientFlutterApiCodec extends StandardMessageCodec { public static final WebViewClientFlutterApiCodec INSTANCE = new WebViewClientFlutterApiCodec(); private WebViewClientFlutterApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return WebResourceErrorData.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 129: return WebResourceRequestData.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 130: return WebResourceResponseData.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof WebResourceErrorData) { stream.write(128); writeValue(stream, ((WebResourceErrorData) value).toList()); } else if (value instanceof WebResourceRequestData) { stream.write(129); writeValue(stream, ((WebResourceRequestData) value).toList()); } else if (value instanceof WebResourceResponseData) { stream.write(130); writeValue(stream, ((WebResourceResponseData) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class WebViewClientFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public WebViewClientFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by WebViewClientFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return WebViewClientFlutterApiCodec.INSTANCE; } public void onPageStarted( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull String urlArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageStarted", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, webViewInstanceIdArg, urlArg)), channelReply -> callback.reply(null)); } public void onPageFinished( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull String urlArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onPageFinished", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, webViewInstanceIdArg, urlArg)), channelReply -> callback.reply(null)); } public void onReceivedHttpError( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull WebResourceRequestData requestArg, @NonNull WebResourceResponseData responseArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpError", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList(instanceIdArg, webViewInstanceIdArg, requestArg, responseArg)), channelReply -> callback.reply(null)); } public void onReceivedRequestError( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull WebResourceRequestData requestArg, @NonNull WebResourceErrorData errorArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedRequestError", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList(instanceIdArg, webViewInstanceIdArg, requestArg, errorArg)), channelReply -> callback.reply(null)); } public void onReceivedError( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull Long errorCodeArg, @NonNull String descriptionArg, @NonNull String failingUrlArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedError", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList( instanceIdArg, webViewInstanceIdArg, errorCodeArg, descriptionArg, failingUrlArg)), channelReply -> callback.reply(null)); } public void requestLoading( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull WebResourceRequestData requestArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.requestLoading", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, webViewInstanceIdArg, requestArg)), channelReply -> callback.reply(null)); } public void urlLoading( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull String urlArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.urlLoading", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, webViewInstanceIdArg, urlArg)), channelReply -> callback.reply(null)); } public void doUpdateVisitedHistory( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull String urlArg, @NonNull Boolean isReloadArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.doUpdateVisitedHistory", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList(instanceIdArg, webViewInstanceIdArg, urlArg, isReloadArg)), channelReply -> callback.reply(null)); } public void onReceivedHttpAuthRequest( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull Long httpAuthHandlerInstanceIdArg, @NonNull String hostArg, @NonNull String realmArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebViewClientFlutterApi.onReceivedHttpAuthRequest", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList( instanceIdArg, webViewInstanceIdArg, httpAuthHandlerInstanceIdArg, hostArg, realmArg)), channelReply -> callback.reply(null)); } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface DownloadListenerHostApi { void create(@NonNull Long instanceId); /** The codec used by DownloadListenerHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `DownloadListenerHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable DownloadListenerHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.DownloadListenerHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.create((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class DownloadListenerFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public DownloadListenerFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by DownloadListenerFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } public void onDownloadStart( @NonNull Long instanceIdArg, @NonNull String urlArg, @NonNull String userAgentArg, @NonNull String contentDispositionArg, @NonNull String mimetypeArg, @NonNull Long contentLengthArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.DownloadListenerFlutterApi.onDownloadStart", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList( instanceIdArg, urlArg, userAgentArg, contentDispositionArg, mimetypeArg, contentLengthArg)), channelReply -> callback.reply(null)); } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface WebChromeClientHostApi { void create(@NonNull Long instanceId); void setSynchronousReturnValueForOnShowFileChooser( @NonNull Long instanceId, @NonNull Boolean value); void setSynchronousReturnValueForOnConsoleMessage( @NonNull Long instanceId, @NonNull Boolean value); void setSynchronousReturnValueForOnJsAlert(@NonNull Long instanceId, @NonNull Boolean value); void setSynchronousReturnValueForOnJsConfirm(@NonNull Long instanceId, @NonNull Boolean value); void setSynchronousReturnValueForOnJsPrompt(@NonNull Long instanceId, @NonNull Boolean value); /** The codec used by WebChromeClientHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `WebChromeClientHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable WebChromeClientHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.create((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnShowFileChooser", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean valueArg = (Boolean) args.get(1); try { api.setSynchronousReturnValueForOnShowFileChooser( (instanceIdArg == null) ? null : instanceIdArg.longValue(), valueArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnConsoleMessage", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean valueArg = (Boolean) args.get(1); try { api.setSynchronousReturnValueForOnConsoleMessage( (instanceIdArg == null) ? null : instanceIdArg.longValue(), valueArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsAlert", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean valueArg = (Boolean) args.get(1); try { api.setSynchronousReturnValueForOnJsAlert( (instanceIdArg == null) ? null : instanceIdArg.longValue(), valueArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsConfirm", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean valueArg = (Boolean) args.get(1); try { api.setSynchronousReturnValueForOnJsConfirm( (instanceIdArg == null) ? null : instanceIdArg.longValue(), valueArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientHostApi.setSynchronousReturnValueForOnJsPrompt", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); Boolean valueArg = (Boolean) args.get(1); try { api.setSynchronousReturnValueForOnJsPrompt( (instanceIdArg == null) ? null : instanceIdArg.longValue(), valueArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface FlutterAssetManagerHostApi { @NonNull List<String> list(@NonNull String path); @NonNull String getAssetFilePathByName(@NonNull String name); /** The codec used by FlutterAssetManagerHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `FlutterAssetManagerHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable FlutterAssetManagerHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.list", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String pathArg = (String) args.get(0); try { List<String> output = api.list(pathArg); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.FlutterAssetManagerHostApi.getAssetFilePathByName", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; String nameArg = (String) args.get(0); try { String output = api.getAssetFilePathByName(nameArg); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } private static class WebChromeClientFlutterApiCodec extends StandardMessageCodec { public static final WebChromeClientFlutterApiCodec INSTANCE = new WebChromeClientFlutterApiCodec(); private WebChromeClientFlutterApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return ConsoleMessage.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof ConsoleMessage) { stream.write(128); writeValue(stream, ((ConsoleMessage) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class WebChromeClientFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public WebChromeClientFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by WebChromeClientFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return WebChromeClientFlutterApiCodec.INSTANCE; } public void onProgressChanged( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull Long progressArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onProgressChanged", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, webViewInstanceIdArg, progressArg)), channelReply -> callback.reply(null)); } public void onShowFileChooser( @NonNull Long instanceIdArg, @NonNull Long webViewInstanceIdArg, @NonNull Long paramsInstanceIdArg, @NonNull Reply<List<String>> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowFileChooser", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList(instanceIdArg, webViewInstanceIdArg, paramsInstanceIdArg)), channelReply -> { @SuppressWarnings("ConstantConditions") List<String> output = (List<String>) channelReply; callback.reply(output); }); } /** Callback to Dart function `WebChromeClient.onPermissionRequest`. */ public void onPermissionRequest( @NonNull Long instanceIdArg, @NonNull Long requestInstanceIdArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onPermissionRequest", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, requestInstanceIdArg)), channelReply -> callback.reply(null)); } /** Callback to Dart function `WebChromeClient.onShowCustomView`. */ public void onShowCustomView( @NonNull Long instanceIdArg, @NonNull Long viewIdentifierArg, @NonNull Long callbackIdentifierArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onShowCustomView", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList(instanceIdArg, viewIdentifierArg, callbackIdentifierArg)), channelReply -> callback.reply(null)); } /** Callback to Dart function `WebChromeClient.onHideCustomView`. */ public void onHideCustomView(@NonNull Long instanceIdArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onHideCustomView", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(instanceIdArg)), channelReply -> callback.reply(null)); } /** Callback to Dart function `WebChromeClient.onGeolocationPermissionsShowPrompt`. */ public void onGeolocationPermissionsShowPrompt( @NonNull Long instanceIdArg, @NonNull Long paramsInstanceIdArg, @NonNull String originArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsShowPrompt", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, paramsInstanceIdArg, originArg)), channelReply -> callback.reply(null)); } /** Callback to Dart function `WebChromeClient.onGeolocationPermissionsHidePrompt`. */ public void onGeolocationPermissionsHidePrompt( @NonNull Long identifierArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onGeolocationPermissionsHidePrompt", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(identifierArg)), channelReply -> callback.reply(null)); } /** Callback to Dart function `WebChromeClient.onConsoleMessage`. */ public void onConsoleMessage( @NonNull Long instanceIdArg, @NonNull ConsoleMessage messageArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onConsoleMessage", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, messageArg)), channelReply -> callback.reply(null)); } public void onJsAlert( @NonNull Long instanceIdArg, @NonNull String urlArg, @NonNull String messageArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsAlert", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, urlArg, messageArg)), channelReply -> callback.reply(null)); } public void onJsConfirm( @NonNull Long instanceIdArg, @NonNull String urlArg, @NonNull String messageArg, @NonNull Reply<Boolean> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsConfirm", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, urlArg, messageArg)), channelReply -> { @SuppressWarnings("ConstantConditions") Boolean output = (Boolean) channelReply; callback.reply(output); }); } public void onJsPrompt( @NonNull Long instanceIdArg, @NonNull String urlArg, @NonNull String messageArg, @NonNull String defaultValueArg, @NonNull Reply<String> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebChromeClientFlutterApi.onJsPrompt", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, urlArg, messageArg, defaultValueArg)), channelReply -> { @SuppressWarnings("ConstantConditions") String output = (String) channelReply; callback.reply(output); }); } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface WebStorageHostApi { void create(@NonNull Long instanceId); void deleteAllData(@NonNull Long instanceId); /** The codec used by WebStorageHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `WebStorageHostApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable WebStorageHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.create", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.create((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.WebStorageHostApi.deleteAllData", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.deleteAllData((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Handles callbacks methods for the native Java FileChooserParams class. * * <p>See * https://developer.android.com/reference/android/webkit/WebChromeClient.FileChooserParams. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class FileChooserParamsFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public FileChooserParamsFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by FileChooserParamsFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } public void create( @NonNull Long instanceIdArg, @NonNull Boolean isCaptureEnabledArg, @NonNull List<String> acceptTypesArg, @NonNull FileChooserMode modeArg, @Nullable String filenameHintArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.FileChooserParamsFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>( Arrays.asList( instanceIdArg, isCaptureEnabledArg, acceptTypesArg, modeArg.index, filenameHintArg)), channelReply -> callback.reply(null)); } } /** * Host API for `PermissionRequest`. * * <p>This class may handle instantiating and adding native object instances that are attached to * a Dart instance or handle method calls on the associated native class or an instance of the * class. * * <p>See https://developer.android.com/reference/android/webkit/PermissionRequest. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface PermissionRequestHostApi { /** Handles Dart method `PermissionRequest.grant`. */ void grant(@NonNull Long instanceId, @NonNull List<String> resources); /** Handles Dart method `PermissionRequest.deny`. */ void deny(@NonNull Long instanceId); /** The codec used by PermissionRequestHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `PermissionRequestHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable PermissionRequestHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.grant", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); List<String> resourcesArg = (List<String>) args.get(1); try { api.grant( (instanceIdArg == null) ? null : instanceIdArg.longValue(), resourcesArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.PermissionRequestHostApi.deny", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.deny((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Flutter API for `PermissionRequest`. * * <p>This class may handle instantiating and adding Dart instances that are attached to a native * instance or receiving callback methods from an overridden native class. * * <p>See https://developer.android.com/reference/android/webkit/PermissionRequest. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class PermissionRequestFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public PermissionRequestFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by PermissionRequestFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** Create a new Dart instance and add it to the `InstanceManager`. */ public void create( @NonNull Long instanceIdArg, @NonNull List<String> resourcesArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.PermissionRequestFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Arrays.asList(instanceIdArg, resourcesArg)), channelReply -> callback.reply(null)); } } /** * Host API for `CustomViewCallback`. * * <p>This class may handle instantiating and adding native object instances that are attached to * a Dart instance or handle method calls on the associated native class or an instance of the * class. * * <p>See * https://developer.android.com/reference/android/webkit/WebChromeClient.CustomViewCallback. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface CustomViewCallbackHostApi { /** Handles Dart method `CustomViewCallback.onCustomViewHidden`. */ void onCustomViewHidden(@NonNull Long identifier); /** The codec used by CustomViewCallbackHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `CustomViewCallbackHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable CustomViewCallbackHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackHostApi.onCustomViewHidden", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number identifierArg = (Number) args.get(0); try { api.onCustomViewHidden( (identifierArg == null) ? null : identifierArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Flutter API for `CustomViewCallback`. * * <p>This class may handle instantiating and adding Dart instances that are attached to a native * instance or receiving callback methods from an overridden native class. * * <p>See * https://developer.android.com/reference/android/webkit/WebChromeClient.CustomViewCallback. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class CustomViewCallbackFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public CustomViewCallbackFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by CustomViewCallbackFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** Create a new Dart instance and add it to the `InstanceManager`. */ public void create(@NonNull Long identifierArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.CustomViewCallbackFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(identifierArg)), channelReply -> callback.reply(null)); } } /** * Flutter API for `View`. * * <p>This class may handle instantiating and adding Dart instances that are attached to a native * instance or receiving callback methods from an overridden native class. * * <p>See https://developer.android.com/reference/android/view/View. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class ViewFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public ViewFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by ViewFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** Create a new Dart instance and add it to the `InstanceManager`. */ public void create(@NonNull Long identifierArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.ViewFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(identifierArg)), channelReply -> callback.reply(null)); } } /** * Host API for `GeolocationPermissionsCallback`. * * <p>This class may handle instantiating and adding native object instances that are attached to * a Dart instance or handle method calls on the associated native class or an instance of the * class. * * <p>See https://developer.android.com/reference/android/webkit/GeolocationPermissions.Callback. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface GeolocationPermissionsCallbackHostApi { /** Handles Dart method `GeolocationPermissionsCallback.invoke`. */ void invoke( @NonNull Long instanceId, @NonNull String origin, @NonNull Boolean allow, @NonNull Boolean retain); /** The codec used by GeolocationPermissionsCallbackHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `GeolocationPermissionsCallbackHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable GeolocationPermissionsCallbackHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackHostApi.invoke", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String originArg = (String) args.get(1); Boolean allowArg = (Boolean) args.get(2); Boolean retainArg = (Boolean) args.get(3); try { api.invoke( (instanceIdArg == null) ? null : instanceIdArg.longValue(), originArg, allowArg, retainArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Flutter API for `GeolocationPermissionsCallback`. * * <p>This class may handle instantiating and adding Dart instances that are attached to a native * instance or receiving callback methods from an overridden native class. * * <p>See https://developer.android.com/reference/android/webkit/GeolocationPermissions.Callback. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class GeolocationPermissionsCallbackFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public GeolocationPermissionsCallbackFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by GeolocationPermissionsCallbackFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** Create a new Dart instance and add it to the `InstanceManager`. */ public void create(@NonNull Long instanceIdArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.GeolocationPermissionsCallbackFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(instanceIdArg)), channelReply -> callback.reply(null)); } } /** * Host API for `HttpAuthHandler`. * * <p>This class may handle instantiating and adding native object instances that are attached to * a Dart instance or handle method calls on the associated native class or an instance of the * class. * * <p>See https://developer.android.com/reference/android/webkit/HttpAuthHandler. * * <p>Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface HttpAuthHandlerHostApi { /** Handles Dart method `HttpAuthHandler.useHttpAuthUsernamePassword`. */ @NonNull Boolean useHttpAuthUsernamePassword(@NonNull Long instanceId); /** Handles Dart method `HttpAuthHandler.cancel`. */ void cancel(@NonNull Long instanceId); /** Handles Dart method `HttpAuthHandler.proceed`. */ void proceed(@NonNull Long instanceId, @NonNull String username, @NonNull String password); /** The codec used by HttpAuthHandlerHostApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** * Sets up an instance of `HttpAuthHandlerHostApi` to handle messages through the * `binaryMessenger`. */ static void setup( @NonNull BinaryMessenger binaryMessenger, @Nullable HttpAuthHandlerHostApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.useHttpAuthUsernamePassword", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { Boolean output = api.useHttpAuthUsernamePassword( (instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.cancel", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); try { api.cancel((instanceIdArg == null) ? null : instanceIdArg.longValue()); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerHostApi.proceed", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; Number instanceIdArg = (Number) args.get(0); String usernameArg = (String) args.get(1); String passwordArg = (String) args.get(2); try { api.proceed( (instanceIdArg == null) ? null : instanceIdArg.longValue(), usernameArg, passwordArg); wrapped.add(0, null); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } } } /** * Flutter API for `HttpAuthHandler`. * * <p>This class may handle instantiating and adding Dart instances that are attached to a native * instance or receiving callback methods from an overridden native class. * * <p>See https://developer.android.com/reference/android/webkit/HttpAuthHandler. * * <p>Generated class from Pigeon that represents Flutter messages that can be called from Java. */ public static class HttpAuthHandlerFlutterApi { private final @NonNull BinaryMessenger binaryMessenger; public HttpAuthHandlerFlutterApi(@NonNull BinaryMessenger argBinaryMessenger) { this.binaryMessenger = argBinaryMessenger; } /** Public interface for sending reply. */ @SuppressWarnings("UnknownNullness") public interface Reply<T> { void reply(T reply); } /** The codec used by HttpAuthHandlerFlutterApi. */ static @NonNull MessageCodec<Object> getCodec() { return new StandardMessageCodec(); } /** Create a new Dart instance and add it to the `InstanceManager`. */ public void create(@NonNull Long instanceIdArg, @NonNull Reply<Void> callback) { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.webview_flutter_android.HttpAuthHandlerFlutterApi.create", getCodec()); channel.send( new ArrayList<Object>(Collections.singletonList(instanceIdArg)), channelReply -> callback.reply(null)); } } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/GeneratedAndroidWebView.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/GeneratedAndroidWebView.java", "repo_id": "packages", "token_count": 66451 }
1,134
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package io.flutter.plugins.webviewflutter; import android.webkit.WebStorage; import androidx.annotation.NonNull; import io.flutter.plugins.webviewflutter.GeneratedAndroidWebView.WebStorageHostApi; import java.util.Objects; /** * Host api implementation for {@link WebStorage}. * * <p>Handles creating {@link WebStorage}s that intercommunicate with a paired Dart object. */ public class WebStorageHostApiImpl implements WebStorageHostApi { private final InstanceManager instanceManager; private final WebStorageCreator webStorageCreator; /** Handles creating {@link WebStorage} for a {@link WebStorageHostApiImpl}. */ public static class WebStorageCreator { /** * Creates a {@link WebStorage}. * * @return the created {@link WebStorage}. Defaults to {@link WebStorage#getInstance} */ @NonNull public WebStorage createWebStorage() { return WebStorage.getInstance(); } } /** * Creates a host API that handles creating {@link WebStorage} and invoke its methods. * * @param instanceManager maintains instances stored to communicate with Dart objects * @param webStorageCreator handles creating {@link WebStorage}s */ public WebStorageHostApiImpl( @NonNull InstanceManager instanceManager, @NonNull WebStorageCreator webStorageCreator) { this.instanceManager = instanceManager; this.webStorageCreator = webStorageCreator; } @Override public void create(@NonNull Long instanceId) { instanceManager.addDartCreatedInstance(webStorageCreator.createWebStorage(), instanceId); } @Override public void deleteAllData(@NonNull Long instanceId) { final WebStorage webStorage = Objects.requireNonNull(instanceManager.getInstance(instanceId)); webStorage.deleteAllData(); } }
packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebStorageHostApiImpl.java/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/android/src/main/java/io/flutter/plugins/webviewflutter/WebStorageHostApiImpl.java", "repo_id": "packages", "token_count": 575 }
1,135
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:typed_data'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:webview_flutter_android/src/android_webview.dart' as android_webview; import 'package:webview_flutter_android/src/android_webview_api_impls.dart'; import 'package:webview_flutter_android/src/instance_manager.dart'; import 'package:webview_flutter_android/src/legacy/webview_android_widget.dart'; import 'package:webview_flutter_platform_interface/src/webview_flutter_platform_interface_legacy.dart'; import '../android_webview_test.mocks.dart' show MockTestWebViewHostApi; import '../test_android_webview.g.dart'; import 'webview_android_widget_test.mocks.dart'; @GenerateMocks(<Type>[ android_webview.FlutterAssetManager, android_webview.WebSettings, android_webview.WebStorage, android_webview.WebView, android_webview.WebResourceRequest, android_webview.DownloadListener, WebViewAndroidJavaScriptChannel, android_webview.WebChromeClient, android_webview.WebViewClient, JavascriptChannelRegistry, WebViewPlatformCallbacksHandler, WebViewProxy, ]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('WebViewAndroidWidget', () { late MockFlutterAssetManager mockFlutterAssetManager; late MockWebView mockWebView; late MockWebSettings mockWebSettings; late MockWebStorage mockWebStorage; late MockWebViewProxy mockWebViewProxy; late MockWebViewPlatformCallbacksHandler mockCallbacksHandler; late MockWebViewClient mockWebViewClient; late android_webview.DownloadListener downloadListener; late android_webview.WebChromeClient webChromeClient; late MockJavascriptChannelRegistry mockJavascriptChannelRegistry; late WebViewAndroidPlatformController testController; setUp(() { mockFlutterAssetManager = MockFlutterAssetManager(); mockWebView = MockWebView(); mockWebSettings = MockWebSettings(); mockWebStorage = MockWebStorage(); mockWebViewClient = MockWebViewClient(); when(mockWebView.settings).thenReturn(mockWebSettings); mockWebViewProxy = MockWebViewProxy(); when(mockWebViewProxy.createWebView()).thenReturn(mockWebView); when(mockWebViewProxy.createWebViewClient( onPageStarted: anyNamed('onPageStarted'), onPageFinished: anyNamed('onPageFinished'), onReceivedError: anyNamed('onReceivedError'), onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), )).thenReturn(mockWebViewClient); mockCallbacksHandler = MockWebViewPlatformCallbacksHandler(); mockJavascriptChannelRegistry = MockJavascriptChannelRegistry(); }); // Builds a AndroidWebViewWidget with default parameters. Future<void> buildWidget( WidgetTester tester, { CreationParams? creationParams, bool hasNavigationDelegate = false, bool hasProgressTracking = false, bool useHybridComposition = false, }) async { await tester.pumpWidget(WebViewAndroidWidget( creationParams: creationParams ?? CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: hasNavigationDelegate, hasProgressTracking: hasProgressTracking, )), callbacksHandler: mockCallbacksHandler, javascriptChannelRegistry: mockJavascriptChannelRegistry, webViewProxy: mockWebViewProxy, flutterAssetManager: mockFlutterAssetManager, webStorage: mockWebStorage, onBuildWidget: (WebViewAndroidPlatformController controller) { testController = controller; return Container(); }, )); mockWebViewClient = testController.webViewClient as MockWebViewClient; downloadListener = testController.downloadListener; webChromeClient = testController.webChromeClient; } testWidgets('WebViewAndroidWidget', (WidgetTester tester) async { await buildWidget(tester); verify(mockWebSettings.setDomStorageEnabled(true)); verify(mockWebSettings.setJavaScriptCanOpenWindowsAutomatically(true)); verify(mockWebSettings.setSupportMultipleWindows(true)); verify(mockWebSettings.setLoadWithOverviewMode(true)); verify(mockWebSettings.setUseWideViewPort(true)); verify(mockWebSettings.setDisplayZoomControls(false)); verify(mockWebSettings.setBuiltInZoomControls(true)); verifyInOrder(<Future<void>>[ mockWebView.setDownloadListener(downloadListener), mockWebView.setWebChromeClient(webChromeClient), mockWebView.setWebViewClient(mockWebViewClient), ]); }); testWidgets( 'Create Widget with Hybrid Composition', (WidgetTester tester) async { await buildWidget(tester, useHybridComposition: true); verify(mockWebViewProxy.createWebView()); }, ); group('CreationParams', () { testWidgets('initialUrl', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( initialUrl: 'https://www.google.com', webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mockWebView.loadUrl( 'https://www.google.com', <String, String>{}, )); }); testWidgets('userAgent', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( userAgent: 'MyUserAgent', webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mockWebSettings.setUserAgentString('MyUserAgent')); }); testWidgets('autoMediaPlaybackPolicy true', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mockWebSettings.setMediaPlaybackRequiresUserGesture(any)); }); testWidgets('autoMediaPlaybackPolicy false', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( autoMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow, webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); verify(mockWebSettings.setMediaPlaybackRequiresUserGesture(false)); }); testWidgets('javascriptChannelNames', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( javascriptChannelNames: <String>{'a', 'b'}, webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: false, ), ), ); final List<android_webview.JavaScriptChannel> javaScriptChannels = verify(mockWebView.addJavaScriptChannel(captureAny)) .captured .cast<android_webview.JavaScriptChannel>(); expect(javaScriptChannels[0].channelName, 'a'); expect(javaScriptChannels[1].channelName, 'b'); }); group('WebSettings', () { testWidgets('javascriptMode', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), javascriptMode: JavascriptMode.unrestricted, hasNavigationDelegate: false, ), ), ); verify(mockWebSettings.setJavaScriptEnabled(true)); }); testWidgets('hasNavigationDelegate', (WidgetTester tester) async { final MockWebViewClient mockWebViewClient = MockWebViewClient(); when(mockWebViewProxy.createWebViewClient( onPageStarted: anyNamed('onPageStarted'), onPageFinished: anyNamed('onPageFinished'), onReceivedError: anyNamed('onReceivedError'), onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), )).thenReturn(mockWebViewClient); await buildWidget( tester, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), hasNavigationDelegate: true, ), ), ); verify( mockWebViewClient .setSynchronousReturnValueForShouldOverrideUrlLoading(true), ); }); testWidgets('debuggingEnabled true', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), debuggingEnabled: true, hasNavigationDelegate: false, ), ), ); verify(mockWebViewProxy.setWebContentsDebuggingEnabled(true)); }); testWidgets('debuggingEnabled false', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), debuggingEnabled: false, hasNavigationDelegate: false, ), ), ); verify(mockWebViewProxy.setWebContentsDebuggingEnabled(false)); }); testWidgets('userAgent', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.of('myUserAgent'), hasNavigationDelegate: false, ), ), ); verify(mockWebSettings.setUserAgentString('myUserAgent')); }); testWidgets('zoomEnabled', (WidgetTester tester) async { await buildWidget( tester, creationParams: CreationParams( webSettings: WebSettings( userAgent: const WebSetting<String?>.absent(), zoomEnabled: false, hasNavigationDelegate: false, ), ), ); verify(mockWebSettings.setSupportZoom(false)); }); }); }); group('WebViewPlatformController', () { testWidgets('loadFile without "file://" prefix', (WidgetTester tester) async { await buildWidget(tester); const String filePath = '/path/to/file.html'; await testController.loadFile(filePath); verify(mockWebView.loadUrl( 'file://$filePath', <String, String>{}, )); }); testWidgets('loadFile with "file://" prefix', (WidgetTester tester) async { await buildWidget(tester); await testController.loadFile('file:///path/to/file.html'); verify(mockWebView.loadUrl( 'file:///path/to/file.html', <String, String>{}, )); }); testWidgets('loadFile should setAllowFileAccess to true', (WidgetTester tester) async { await buildWidget(tester); await testController.loadFile('file:///path/to/file.html'); verify(mockWebSettings.setAllowFileAccess(true)); }); testWidgets('loadFlutterAsset', (WidgetTester tester) async { await buildWidget(tester); const String assetKey = 'test_assets/index.html'; when(mockFlutterAssetManager.getAssetFilePathByName(assetKey)) .thenAnswer( (_) => Future<String>.value('flutter_assets/$assetKey')); when(mockFlutterAssetManager.list('flutter_assets/test_assets')) .thenAnswer( (_) => Future<List<String>>.value(<String>['index.html'])); await testController.loadFlutterAsset(assetKey); verify(mockWebView.loadUrl( 'file:///android_asset/flutter_assets/$assetKey', <String, String>{}, )); }); testWidgets('loadFlutterAsset with file in root', (WidgetTester tester) async { await buildWidget(tester); const String assetKey = 'index.html'; when(mockFlutterAssetManager.getAssetFilePathByName(assetKey)) .thenAnswer( (_) => Future<String>.value('flutter_assets/$assetKey')); when(mockFlutterAssetManager.list('flutter_assets')).thenAnswer( (_) => Future<List<String>>.value(<String>['index.html'])); await testController.loadFlutterAsset(assetKey); verify(mockWebView.loadUrl( 'file:///android_asset/flutter_assets/$assetKey', <String, String>{}, )); }); testWidgets( 'loadFlutterAsset throws ArgumentError when asset does not exist', (WidgetTester tester) async { await buildWidget(tester); const String assetKey = 'test_assets/index.html'; when(mockFlutterAssetManager.getAssetFilePathByName(assetKey)) .thenAnswer( (_) => Future<String>.value('flutter_assets/$assetKey')); when(mockFlutterAssetManager.list('flutter_assets/test_assets')) .thenAnswer((_) => Future<List<String>>.value(<String>[''])); expect( () => testController.loadFlutterAsset(assetKey), throwsA( isA<ArgumentError>() .having((ArgumentError error) => error.name, 'name', 'key') .having((ArgumentError error) => error.message, 'message', 'Asset for key "$assetKey" not found.'), ), ); }); testWidgets('loadHtmlString without base URL', (WidgetTester tester) async { await buildWidget(tester); const String htmlString = '<html><body>Test data.</body></html>'; await testController.loadHtmlString(htmlString); verify(mockWebView.loadDataWithBaseUrl( data: htmlString, mimeType: 'text/html', )); }); testWidgets('loadHtmlString with base URL', (WidgetTester tester) async { await buildWidget(tester); const String htmlString = '<html><body>Test data.</body></html>'; await testController.loadHtmlString( htmlString, baseUrl: 'https://flutter.dev', ); verify(mockWebView.loadDataWithBaseUrl( baseUrl: 'https://flutter.dev', data: htmlString, mimeType: 'text/html', )); }); testWidgets('loadUrl', (WidgetTester tester) async { await buildWidget(tester); await testController.loadUrl( 'https://www.google.com', <String, String>{'a': 'header'}, ); verify(mockWebView.loadUrl( 'https://www.google.com', <String, String>{'a': 'header'}, )); }); group('loadRequest', () { testWidgets('Throws ArgumentError for empty scheme', (WidgetTester tester) async { await buildWidget(tester); expect( () async => testController.loadRequest( WebViewRequest( uri: Uri.parse('www.google.com'), method: WebViewRequestMethod.get, ), ), throwsA(const TypeMatcher<ArgumentError>())); }); testWidgets('GET without headers', (WidgetTester tester) async { await buildWidget(tester); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.get, )); verify(mockWebView.loadUrl( 'https://www.google.com', <String, String>{}, )); }); testWidgets('GET with headers', (WidgetTester tester) async { await buildWidget(tester); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.get, headers: <String, String>{'a': 'header'}, )); verify(mockWebView.loadUrl( 'https://www.google.com', <String, String>{'a': 'header'}, )); }); testWidgets('POST without body', (WidgetTester tester) async { await buildWidget(tester); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.post, )); verify(mockWebView.postUrl( 'https://www.google.com', Uint8List(0), )); }); testWidgets('POST with body', (WidgetTester tester) async { await buildWidget(tester); final Uint8List body = Uint8List.fromList('Test Body'.codeUnits); await testController.loadRequest(WebViewRequest( uri: Uri.parse('https://www.google.com'), method: WebViewRequestMethod.post, body: body)); verify(mockWebView.postUrl( 'https://www.google.com', body, )); }); }); testWidgets('no update to userAgentString when there is no change', (WidgetTester tester) async { await buildWidget(tester); reset(mockWebSettings); await testController.updateSettings(WebSettings( userAgent: const WebSetting<String>.absent(), )); verifyNever(mockWebSettings.setUserAgentString(any)); }); testWidgets('update null userAgentString with empty string', (WidgetTester tester) async { await buildWidget(tester); reset(mockWebSettings); await testController.updateSettings(WebSettings( userAgent: const WebSetting<String?>.of(null), )); verify(mockWebSettings.setUserAgentString('')); }); testWidgets('currentUrl', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.getUrl()) .thenAnswer((_) => Future<String>.value('https://www.google.com')); expect( testController.currentUrl(), completion('https://www.google.com')); }); testWidgets('canGoBack', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.canGoBack()).thenAnswer( (_) => Future<bool>.value(false), ); expect(testController.canGoBack(), completion(false)); }); testWidgets('canGoForward', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.canGoForward()).thenAnswer( (_) => Future<bool>.value(true), ); expect(testController.canGoForward(), completion(true)); }); testWidgets('goBack', (WidgetTester tester) async { await buildWidget(tester); await testController.goBack(); verify(mockWebView.goBack()); }); testWidgets('goForward', (WidgetTester tester) async { await buildWidget(tester); await testController.goForward(); verify(mockWebView.goForward()); }); testWidgets('reload', (WidgetTester tester) async { await buildWidget(tester); await testController.reload(); verify(mockWebView.reload()); }); testWidgets('clearCache', (WidgetTester tester) async { await buildWidget(tester); await testController.clearCache(); verify(mockWebView.clearCache(true)); verify(mockWebStorage.deleteAllData()); }); testWidgets('evaluateJavascript', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.evaluateJavascript('runJavaScript')).thenAnswer( (_) => Future<String>.value('returnString'), ); expect( testController.evaluateJavascript('runJavaScript'), completion('returnString'), ); }); testWidgets('runJavascriptReturningResult', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.evaluateJavascript('runJavaScript')).thenAnswer( (_) => Future<String>.value('returnString'), ); expect( testController.runJavascriptReturningResult('runJavaScript'), completion('returnString'), ); }); testWidgets('runJavascript', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.evaluateJavascript('runJavaScript')).thenAnswer( (_) => Future<String>.value('returnString'), ); expect( testController.runJavascript('runJavaScript'), completes, ); }); testWidgets('addJavascriptChannels', (WidgetTester tester) async { await buildWidget(tester); await testController.addJavascriptChannels(<String>{'c', 'd'}); final List<android_webview.JavaScriptChannel> javaScriptChannels = verify(mockWebView.addJavaScriptChannel(captureAny)) .captured .cast<android_webview.JavaScriptChannel>(); expect(javaScriptChannels[0].channelName, 'c'); expect(javaScriptChannels[1].channelName, 'd'); }); testWidgets('removeJavascriptChannels', (WidgetTester tester) async { await buildWidget(tester); await testController.addJavascriptChannels(<String>{'c', 'd'}); await testController.removeJavascriptChannels(<String>{'c', 'd'}); final List<android_webview.JavaScriptChannel> javaScriptChannels = verify(mockWebView.removeJavaScriptChannel(captureAny)) .captured .cast<android_webview.JavaScriptChannel>(); expect(javaScriptChannels[0].channelName, 'c'); expect(javaScriptChannels[1].channelName, 'd'); }); testWidgets('getTitle', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.getTitle()) .thenAnswer((_) => Future<String>.value('Web Title')); expect(testController.getTitle(), completion('Web Title')); }); testWidgets('scrollTo', (WidgetTester tester) async { await buildWidget(tester); await testController.scrollTo(1, 2); verify(mockWebView.scrollTo(1, 2)); }); testWidgets('scrollBy', (WidgetTester tester) async { await buildWidget(tester); await testController.scrollBy(3, 4); verify(mockWebView.scrollBy(3, 4)); }); testWidgets('getScrollX', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.getScrollX()).thenAnswer((_) => Future<int>.value(23)); expect(testController.getScrollX(), completion(23)); }); testWidgets('getScrollY', (WidgetTester tester) async { await buildWidget(tester); when(mockWebView.getScrollY()).thenAnswer((_) => Future<int>.value(25)); expect(testController.getScrollY(), completion(25)); }); }); group('WebViewPlatformCallbacksHandler', () { testWidgets('onPageStarted', (WidgetTester tester) async { await buildWidget(tester); final void Function(android_webview.WebView, String) onPageStarted = verify(mockWebViewProxy.createWebViewClient( onPageStarted: captureAnyNamed('onPageStarted'), onPageFinished: anyNamed('onPageFinished'), onReceivedError: anyNamed('onReceivedError'), onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), )).captured.single as void Function(android_webview.WebView, String); onPageStarted(mockWebView, 'https://google.com'); verify(mockCallbacksHandler.onPageStarted('https://google.com')); }); testWidgets('onPageFinished', (WidgetTester tester) async { await buildWidget(tester); final void Function(android_webview.WebView, String) onPageFinished = verify(mockWebViewProxy.createWebViewClient( onPageStarted: anyNamed('onPageStarted'), onPageFinished: captureAnyNamed('onPageFinished'), onReceivedError: anyNamed('onReceivedError'), onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), )).captured.single as void Function(android_webview.WebView, String); onPageFinished(mockWebView, 'https://google.com'); verify(mockCallbacksHandler.onPageFinished('https://google.com')); }); testWidgets('onWebResourceError from onReceivedError', (WidgetTester tester) async { await buildWidget(tester); final void Function(android_webview.WebView, int, String, String) onReceivedError = verify(mockWebViewProxy.createWebViewClient( onPageStarted: anyNamed('onPageStarted'), onPageFinished: anyNamed('onPageFinished'), onReceivedError: captureAnyNamed('onReceivedError'), onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), )).captured.single as void Function( android_webview.WebView, int, String, String); onReceivedError( mockWebView, android_webview.WebViewClient.errorAuthentication, 'description', 'https://google.com', ); final WebResourceError error = verify(mockCallbacksHandler.onWebResourceError(captureAny)) .captured .single as WebResourceError; expect(error.description, 'description'); expect(error.errorCode, -4); expect(error.failingUrl, 'https://google.com'); expect(error.domain, isNull); expect(error.errorType, WebResourceErrorType.authentication); }); testWidgets('onWebResourceError from onReceivedRequestError', (WidgetTester tester) async { await buildWidget(tester); final void Function( android_webview.WebView, android_webview.WebResourceRequest, android_webview.WebResourceError, ) onReceivedRequestError = verify(mockWebViewProxy.createWebViewClient( onPageStarted: anyNamed('onPageStarted'), onPageFinished: anyNamed('onPageFinished'), onReceivedError: anyNamed('onReceivedError'), onReceivedRequestError: captureAnyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), )).captured.single as void Function( android_webview.WebView, android_webview.WebResourceRequest, android_webview.WebResourceError, ); onReceivedRequestError( mockWebView, android_webview.WebResourceRequest( url: 'https://google.com', isForMainFrame: true, isRedirect: false, hasGesture: false, method: 'POST', requestHeaders: <String, String>{}, ), android_webview.WebResourceError( errorCode: android_webview.WebViewClient.errorUnsafeResource, description: 'description', ), ); final WebResourceError error = verify(mockCallbacksHandler.onWebResourceError(captureAny)) .captured .single as WebResourceError; expect(error.description, 'description'); expect(error.errorCode, -16); expect(error.failingUrl, 'https://google.com'); expect(error.domain, isNull); expect(error.errorType, WebResourceErrorType.unsafeResource); }); testWidgets('onNavigationRequest from urlLoading', (WidgetTester tester) async { await buildWidget(tester, hasNavigationDelegate: true); when(mockCallbacksHandler.onNavigationRequest( isForMainFrame: argThat(isTrue, named: 'isForMainFrame'), url: 'https://google.com', )).thenReturn(true); final void Function(android_webview.WebView, String) urlLoading = verify(mockWebViewProxy.createWebViewClient( onPageStarted: anyNamed('onPageStarted'), onPageFinished: anyNamed('onPageFinished'), onReceivedError: anyNamed('onReceivedError'), onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: anyNamed('requestLoading'), urlLoading: captureAnyNamed('urlLoading'), )).captured.single as void Function(android_webview.WebView, String); urlLoading(mockWebView, 'https://google.com'); verify(mockCallbacksHandler.onNavigationRequest( url: 'https://google.com', isForMainFrame: true, )); verify(mockWebView.loadUrl('https://google.com', <String, String>{})); }); testWidgets('onNavigationRequest from requestLoading', (WidgetTester tester) async { await buildWidget(tester, hasNavigationDelegate: true); when(mockCallbacksHandler.onNavigationRequest( isForMainFrame: argThat(isTrue, named: 'isForMainFrame'), url: 'https://google.com', )).thenReturn(true); final void Function( android_webview.WebView, android_webview.WebResourceRequest, ) requestLoading = verify(mockWebViewProxy.createWebViewClient( onPageStarted: anyNamed('onPageStarted'), onPageFinished: anyNamed('onPageFinished'), onReceivedError: anyNamed('onReceivedError'), onReceivedRequestError: anyNamed('onReceivedRequestError'), requestLoading: captureAnyNamed('requestLoading'), urlLoading: anyNamed('urlLoading'), )).captured.single as void Function( android_webview.WebView, android_webview.WebResourceRequest, ); requestLoading( mockWebView, android_webview.WebResourceRequest( url: 'https://google.com', isForMainFrame: true, isRedirect: false, hasGesture: false, method: 'POST', requestHeaders: <String, String>{}, ), ); verify(mockCallbacksHandler.onNavigationRequest( url: 'https://google.com', isForMainFrame: true, )); verify(mockWebView.loadUrl('https://google.com', <String, String>{})); }); group('JavascriptChannelRegistry', () { testWidgets('onJavascriptChannelMessage', (WidgetTester tester) async { await buildWidget(tester); await testController.addJavascriptChannels(<String>{'hello'}); final WebViewAndroidJavaScriptChannel javaScriptChannel = verify(mockWebView.addJavaScriptChannel(captureAny)) .captured .single as WebViewAndroidJavaScriptChannel; javaScriptChannel.postMessage('goodbye'); verify(mockJavascriptChannelRegistry.onJavascriptChannelMessage( 'hello', 'goodbye', )); }); }); }); }); group('WebViewProxy', () { late MockTestWebViewHostApi mockPlatformHostApi; late InstanceManager instanceManager; setUp(() { // WebViewProxy calls static methods that can't be mocked, so the mocks // have to be set up at the next layer down, by mocking the implementation // of WebView itstelf. mockPlatformHostApi = MockTestWebViewHostApi(); TestWebViewHostApi.setup(mockPlatformHostApi); instanceManager = InstanceManager(onWeakReferenceRemoved: (_) {}); android_webview.WebView.api = WebViewHostApiImpl(instanceManager: instanceManager); }); test('setWebContentsDebuggingEnabled true', () { const WebViewProxy webViewProxy = WebViewProxy(); webViewProxy.setWebContentsDebuggingEnabled(true); verify(mockPlatformHostApi.setWebContentsDebuggingEnabled(true)); }); test('setWebContentsDebuggingEnabled false', () { const WebViewProxy webViewProxy = WebViewProxy(); webViewProxy.setWebContentsDebuggingEnabled(false); verify(mockPlatformHostApi.setWebContentsDebuggingEnabled(false)); }); }); }
packages/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_android/test/legacy/webview_android_widget_test.dart", "repo_id": "packages", "token_count": 14484 }
1,136
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// A message that was sent by JavaScript code running in a [WebView]. class JavascriptMessage { /// Constructs a JavaScript message object. /// /// The `message` parameter must not be null. const JavascriptMessage(this.message); /// The contents of the message that was sent by the JavaScript code. final String message; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_message.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/legacy/types/javascript_message.dart", "repo_id": "packages", "token_count": 124 }
1,137
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Represents the severity of a JavaScript log message. enum JavaScriptLogLevel { /// Indicates an error message was logged via an "error" event of the /// `console.error` method. error, /// Indicates a warning message was logged using the `console.warning` /// method. warning, /// Indicates a debug message was logged using the `console.debug` method. debug, /// Indicates an informational message was logged using the `console.info` /// method. info, /// Indicates a log message was logged using the `console.log` method. log, }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_log_level.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/javascript_log_level.dart", "repo_id": "packages", "token_count": 192 }
1,138
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; /// Contains information about the response for a request. /// /// Platform specific implementations can add additional fields by extending /// this class. /// /// This example demonstrates how to extend the [WebResourceResponse] to /// provide additional platform specific parameters. /// /// When extending [WebResourceResponse] additional parameters should always /// accept `null` or have a default value to prevent breaking changes. /// /// ```dart /// class AndroidWebResourceResponse extends WebResourceResponse { /// WebResourceResponse._({ /// required WebResourceResponse response, /// }) : super( /// uri: response.uri, /// statusCode: response.statusCode, /// headers: response.headers, /// ); /// /// factory AndroidWebResourceResponse.fromWebResourceResponse( /// WebResourceResponse response, { /// Uri? historyUrl, /// }) { /// return AndroidWebResourceResponse._(response, historyUrl: historyUrl); /// } /// /// final Uri? historyUrl; /// } /// ``` @immutable class WebResourceResponse { /// Used by the platform implementation to create a new [WebResourceResponse]. const WebResourceResponse({ required this.uri, required this.statusCode, this.headers = const <String, String>{}, }); /// The URI that this response is associated with. final Uri? uri; /// The HTTP status code. final int statusCode; /// Headers for the request. final Map<String, String> headers; }
packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/web_resource_response.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/lib/src/types/web_resource_response.dart", "repo_id": "packages", "token_count": 454 }
1,139
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_test/flutter_test.dart'; import 'package:webview_flutter_platform_interface/src/types/types.dart'; void main() { group('types', () { test('WebResourceRequest', () { final Uri uri = Uri.parse('https://www.google.com'); final WebResourceRequest request = WebResourceRequest(uri: uri); expect(request.uri, uri); }); test('WebResourceResponse', () { final Uri uri = Uri.parse('https://www.google.com'); const int statusCode = 404; const Map<String, String> headers = <String, String>{'a': 'header'}; final WebResourceResponse response = WebResourceResponse( uri: uri, statusCode: statusCode, headers: headers, ); expect(response.uri, uri); expect(response.statusCode, statusCode); expect(response.headers, headers); }); }); }
packages/packages/webview_flutter/webview_flutter_platform_interface/test/types_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_platform_interface/test/types_test.dart", "repo_id": "packages", "token_count": 368 }
1,140
// Mocks generated by Mockito 5.4.4 from annotations // in webview_flutter_web/test/legacy/webview_flutter_web_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i7; import 'dart:html' as _i2; import 'dart:math' as _i3; import 'package:flutter/foundation.dart' as _i5; import 'package:flutter/src/widgets/notification_listener.dart' as _i8; import 'package:flutter/widgets.dart' as _i4; import 'package:mockito/mockito.dart' as _i1; import 'package:mockito/src/dummies.dart' as _i6; import 'package:webview_flutter_platform_interface/src/legacy/platform_interface/webview_platform_callbacks_handler.dart' as _i10; import 'package:webview_flutter_platform_interface/src/legacy/types/types.dart' as _i9; import 'package:webview_flutter_web/src/http_request_factory.dart' as _i11; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeCssClassSet_0 extends _i1.SmartFake implements _i2.CssClassSet { _FakeCssClassSet_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeRectangle_1<T extends num> extends _i1.SmartFake implements _i3.Rectangle<T> { _FakeRectangle_1( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeCssRect_2 extends _i1.SmartFake implements _i2.CssRect { _FakeCssRect_2( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakePoint_3<T extends num> extends _i1.SmartFake implements _i3.Point<T> { _FakePoint_3( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeElementEvents_4 extends _i1.SmartFake implements _i2.ElementEvents { _FakeElementEvents_4( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeCssStyleDeclaration_5 extends _i1.SmartFake implements _i2.CssStyleDeclaration { _FakeCssStyleDeclaration_5( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeElementStream_6<T extends _i2.Event> extends _i1.SmartFake implements _i2.ElementStream<T> { _FakeElementStream_6( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeElementList_7<T1 extends _i2.Element> extends _i1.SmartFake implements _i2.ElementList<T1> { _FakeElementList_7( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeScrollState_8 extends _i1.SmartFake implements _i2.ScrollState { _FakeScrollState_8( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeAnimation_9 extends _i1.SmartFake implements _i2.Animation { _FakeAnimation_9( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeElement_10 extends _i1.SmartFake implements _i2.Element { _FakeElement_10( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeShadowRoot_11 extends _i1.SmartFake implements _i2.ShadowRoot { _FakeShadowRoot_11( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeDocumentFragment_12 extends _i1.SmartFake implements _i2.DocumentFragment { _FakeDocumentFragment_12( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeNode_13 extends _i1.SmartFake implements _i2.Node { _FakeNode_13( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeWidget_14 extends _i1.SmartFake implements _i4.Widget { _FakeWidget_14( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({_i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) => super.toString(); } class _FakeInheritedWidget_15 extends _i1.SmartFake implements _i4.InheritedWidget { _FakeInheritedWidget_15( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({_i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info}) => super.toString(); } class _FakeDiagnosticsNode_16 extends _i1.SmartFake implements _i5.DiagnosticsNode { _FakeDiagnosticsNode_16( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); @override String toString({ _i5.TextTreeConfiguration? parentConfiguration, _i5.DiagnosticLevel? minLevel = _i5.DiagnosticLevel.info, }) => super.toString(); } class _FakeHttpRequest_17 extends _i1.SmartFake implements _i2.HttpRequest { _FakeHttpRequest_17( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeHttpRequestUpload_18 extends _i1.SmartFake implements _i2.HttpRequestUpload { _FakeHttpRequestUpload_18( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } class _FakeEvents_19 extends _i1.SmartFake implements _i2.Events { _FakeEvents_19( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [IFrameElement]. /// /// See the documentation for Mockito's code generation for more information. class MockIFrameElement extends _i1.Mock implements _i2.IFrameElement { MockIFrameElement() { _i1.throwOnMissingStub(this); } @override set allow(String? value) => super.noSuchMethod( Invocation.setter( #allow, value, ), returnValueForMissingStub: null, ); @override set allowFullscreen(bool? value) => super.noSuchMethod( Invocation.setter( #allowFullscreen, value, ), returnValueForMissingStub: null, ); @override set allowPaymentRequest(bool? value) => super.noSuchMethod( Invocation.setter( #allowPaymentRequest, value, ), returnValueForMissingStub: null, ); @override set csp(String? value) => super.noSuchMethod( Invocation.setter( #csp, value, ), returnValueForMissingStub: null, ); @override set height(String? value) => super.noSuchMethod( Invocation.setter( #height, value, ), returnValueForMissingStub: null, ); @override set name(String? value) => super.noSuchMethod( Invocation.setter( #name, value, ), returnValueForMissingStub: null, ); @override set referrerPolicy(String? value) => super.noSuchMethod( Invocation.setter( #referrerPolicy, value, ), returnValueForMissingStub: null, ); @override set src(String? value) => super.noSuchMethod( Invocation.setter( #src, value, ), returnValueForMissingStub: null, ); @override set srcdoc(String? value) => super.noSuchMethod( Invocation.setter( #srcdoc, value, ), returnValueForMissingStub: null, ); @override set width(String? value) => super.noSuchMethod( Invocation.setter( #width, value, ), returnValueForMissingStub: null, ); @override set nonce(String? value) => super.noSuchMethod( Invocation.setter( #nonce, value, ), returnValueForMissingStub: null, ); @override Map<String, String> get attributes => (super.noSuchMethod( Invocation.getter(#attributes), returnValue: <String, String>{}, ) as Map<String, String>); @override set attributes(Map<String, String>? value) => super.noSuchMethod( Invocation.setter( #attributes, value, ), returnValueForMissingStub: null, ); @override List<_i2.Element> get children => (super.noSuchMethod( Invocation.getter(#children), returnValue: <_i2.Element>[], ) as List<_i2.Element>); @override set children(List<_i2.Element>? value) => super.noSuchMethod( Invocation.setter( #children, value, ), returnValueForMissingStub: null, ); @override _i2.CssClassSet get classes => (super.noSuchMethod( Invocation.getter(#classes), returnValue: _FakeCssClassSet_0( this, Invocation.getter(#classes), ), ) as _i2.CssClassSet); @override set classes(Iterable<String>? value) => super.noSuchMethod( Invocation.setter( #classes, value, ), returnValueForMissingStub: null, ); @override Map<String, String> get dataset => (super.noSuchMethod( Invocation.getter(#dataset), returnValue: <String, String>{}, ) as Map<String, String>); @override set dataset(Map<String, String>? value) => super.noSuchMethod( Invocation.setter( #dataset, value, ), returnValueForMissingStub: null, ); @override _i3.Rectangle<num> get client => (super.noSuchMethod( Invocation.getter(#client), returnValue: _FakeRectangle_1<num>( this, Invocation.getter(#client), ), ) as _i3.Rectangle<num>); @override _i3.Rectangle<num> get offset => (super.noSuchMethod( Invocation.getter(#offset), returnValue: _FakeRectangle_1<num>( this, Invocation.getter(#offset), ), ) as _i3.Rectangle<num>); @override String get localName => (super.noSuchMethod( Invocation.getter(#localName), returnValue: _i6.dummyValue<String>( this, Invocation.getter(#localName), ), ) as String); @override _i2.CssRect get contentEdge => (super.noSuchMethod( Invocation.getter(#contentEdge), returnValue: _FakeCssRect_2( this, Invocation.getter(#contentEdge), ), ) as _i2.CssRect); @override _i2.CssRect get paddingEdge => (super.noSuchMethod( Invocation.getter(#paddingEdge), returnValue: _FakeCssRect_2( this, Invocation.getter(#paddingEdge), ), ) as _i2.CssRect); @override _i2.CssRect get borderEdge => (super.noSuchMethod( Invocation.getter(#borderEdge), returnValue: _FakeCssRect_2( this, Invocation.getter(#borderEdge), ), ) as _i2.CssRect); @override _i2.CssRect get marginEdge => (super.noSuchMethod( Invocation.getter(#marginEdge), returnValue: _FakeCssRect_2( this, Invocation.getter(#marginEdge), ), ) as _i2.CssRect); @override _i3.Point<num> get documentOffset => (super.noSuchMethod( Invocation.getter(#documentOffset), returnValue: _FakePoint_3<num>( this, Invocation.getter(#documentOffset), ), ) as _i3.Point<num>); @override set innerHtml(String? html) => super.noSuchMethod( Invocation.setter( #innerHtml, html, ), returnValueForMissingStub: null, ); @override String get innerText => (super.noSuchMethod( Invocation.getter(#innerText), returnValue: _i6.dummyValue<String>( this, Invocation.getter(#innerText), ), ) as String); @override set innerText(String? value) => super.noSuchMethod( Invocation.setter( #innerText, value, ), returnValueForMissingStub: null, ); @override _i2.ElementEvents get on => (super.noSuchMethod( Invocation.getter(#on), returnValue: _FakeElementEvents_4( this, Invocation.getter(#on), ), ) as _i2.ElementEvents); @override int get offsetHeight => (super.noSuchMethod( Invocation.getter(#offsetHeight), returnValue: 0, ) as int); @override int get offsetLeft => (super.noSuchMethod( Invocation.getter(#offsetLeft), returnValue: 0, ) as int); @override int get offsetTop => (super.noSuchMethod( Invocation.getter(#offsetTop), returnValue: 0, ) as int); @override int get offsetWidth => (super.noSuchMethod( Invocation.getter(#offsetWidth), returnValue: 0, ) as int); @override int get scrollHeight => (super.noSuchMethod( Invocation.getter(#scrollHeight), returnValue: 0, ) as int); @override int get scrollLeft => (super.noSuchMethod( Invocation.getter(#scrollLeft), returnValue: 0, ) as int); @override set scrollLeft(int? value) => super.noSuchMethod( Invocation.setter( #scrollLeft, value, ), returnValueForMissingStub: null, ); @override int get scrollTop => (super.noSuchMethod( Invocation.getter(#scrollTop), returnValue: 0, ) as int); @override set scrollTop(int? value) => super.noSuchMethod( Invocation.setter( #scrollTop, value, ), returnValueForMissingStub: null, ); @override int get scrollWidth => (super.noSuchMethod( Invocation.getter(#scrollWidth), returnValue: 0, ) as int); @override String get contentEditable => (super.noSuchMethod( Invocation.getter(#contentEditable), returnValue: _i6.dummyValue<String>( this, Invocation.getter(#contentEditable), ), ) as String); @override set contentEditable(String? value) => super.noSuchMethod( Invocation.setter( #contentEditable, value, ), returnValueForMissingStub: null, ); @override set dir(String? value) => super.noSuchMethod( Invocation.setter( #dir, value, ), returnValueForMissingStub: null, ); @override bool get draggable => (super.noSuchMethod( Invocation.getter(#draggable), returnValue: false, ) as bool); @override set draggable(bool? value) => super.noSuchMethod( Invocation.setter( #draggable, value, ), returnValueForMissingStub: null, ); @override bool get hidden => (super.noSuchMethod( Invocation.getter(#hidden), returnValue: false, ) as bool); @override set hidden(bool? value) => super.noSuchMethod( Invocation.setter( #hidden, value, ), returnValueForMissingStub: null, ); @override set inert(bool? value) => super.noSuchMethod( Invocation.setter( #inert, value, ), returnValueForMissingStub: null, ); @override set inputMode(String? value) => super.noSuchMethod( Invocation.setter( #inputMode, value, ), returnValueForMissingStub: null, ); @override set lang(String? value) => super.noSuchMethod( Invocation.setter( #lang, value, ), returnValueForMissingStub: null, ); @override set spellcheck(bool? value) => super.noSuchMethod( Invocation.setter( #spellcheck, value, ), returnValueForMissingStub: null, ); @override _i2.CssStyleDeclaration get style => (super.noSuchMethod( Invocation.getter(#style), returnValue: _FakeCssStyleDeclaration_5( this, Invocation.getter(#style), ), ) as _i2.CssStyleDeclaration); @override set tabIndex(int? value) => super.noSuchMethod( Invocation.setter( #tabIndex, value, ), returnValueForMissingStub: null, ); @override set title(String? value) => super.noSuchMethod( Invocation.setter( #title, value, ), returnValueForMissingStub: null, ); @override set translate(bool? value) => super.noSuchMethod( Invocation.setter( #translate, value, ), returnValueForMissingStub: null, ); @override String get className => (super.noSuchMethod( Invocation.getter(#className), returnValue: _i6.dummyValue<String>( this, Invocation.getter(#className), ), ) as String); @override set className(String? value) => super.noSuchMethod( Invocation.setter( #className, value, ), returnValueForMissingStub: null, ); @override int get clientHeight => (super.noSuchMethod( Invocation.getter(#clientHeight), returnValue: 0, ) as int); @override int get clientWidth => (super.noSuchMethod( Invocation.getter(#clientWidth), returnValue: 0, ) as int); @override String get id => (super.noSuchMethod( Invocation.getter(#id), returnValue: _i6.dummyValue<String>( this, Invocation.getter(#id), ), ) as String); @override set id(String? value) => super.noSuchMethod( Invocation.setter( #id, value, ), returnValueForMissingStub: null, ); @override set slot(String? value) => super.noSuchMethod( Invocation.setter( #slot, value, ), returnValueForMissingStub: null, ); @override String get tagName => (super.noSuchMethod( Invocation.getter(#tagName), returnValue: _i6.dummyValue<String>( this, Invocation.getter(#tagName), ), ) as String); @override _i2.ElementStream<_i2.Event> get onAbort => (super.noSuchMethod( Invocation.getter(#onAbort), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onAbort), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBeforeCopy => (super.noSuchMethod( Invocation.getter(#onBeforeCopy), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onBeforeCopy), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBeforeCut => (super.noSuchMethod( Invocation.getter(#onBeforeCut), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onBeforeCut), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBeforePaste => (super.noSuchMethod( Invocation.getter(#onBeforePaste), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onBeforePaste), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onBlur => (super.noSuchMethod( Invocation.getter(#onBlur), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onBlur), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onCanPlay => (super.noSuchMethod( Invocation.getter(#onCanPlay), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onCanPlay), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onCanPlayThrough => (super.noSuchMethod( Invocation.getter(#onCanPlayThrough), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onCanPlayThrough), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onChange => (super.noSuchMethod( Invocation.getter(#onChange), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onChange), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.MouseEvent> get onClick => (super.noSuchMethod( Invocation.getter(#onClick), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onClick), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onContextMenu => (super.noSuchMethod( Invocation.getter(#onContextMenu), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onContextMenu), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.ClipboardEvent> get onCopy => (super.noSuchMethod( Invocation.getter(#onCopy), returnValue: _FakeElementStream_6<_i2.ClipboardEvent>( this, Invocation.getter(#onCopy), ), ) as _i2.ElementStream<_i2.ClipboardEvent>); @override _i2.ElementStream<_i2.ClipboardEvent> get onCut => (super.noSuchMethod( Invocation.getter(#onCut), returnValue: _FakeElementStream_6<_i2.ClipboardEvent>( this, Invocation.getter(#onCut), ), ) as _i2.ElementStream<_i2.ClipboardEvent>); @override _i2.ElementStream<_i2.Event> get onDoubleClick => (super.noSuchMethod( Invocation.getter(#onDoubleClick), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onDoubleClick), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.MouseEvent> get onDrag => (super.noSuchMethod( Invocation.getter(#onDrag), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onDrag), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragEnd => (super.noSuchMethod( Invocation.getter(#onDragEnd), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onDragEnd), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragEnter => (super.noSuchMethod( Invocation.getter(#onDragEnter), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onDragEnter), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragLeave => (super.noSuchMethod( Invocation.getter(#onDragLeave), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onDragLeave), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragOver => (super.noSuchMethod( Invocation.getter(#onDragOver), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onDragOver), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDragStart => (super.noSuchMethod( Invocation.getter(#onDragStart), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onDragStart), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onDrop => (super.noSuchMethod( Invocation.getter(#onDrop), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onDrop), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.Event> get onDurationChange => (super.noSuchMethod( Invocation.getter(#onDurationChange), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onDurationChange), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onEmptied => (super.noSuchMethod( Invocation.getter(#onEmptied), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onEmptied), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onEnded => (super.noSuchMethod( Invocation.getter(#onEnded), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onEnded), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onError => (super.noSuchMethod( Invocation.getter(#onError), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onError), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onFocus => (super.noSuchMethod( Invocation.getter(#onFocus), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onFocus), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onInput => (super.noSuchMethod( Invocation.getter(#onInput), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onInput), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onInvalid => (super.noSuchMethod( Invocation.getter(#onInvalid), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onInvalid), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.KeyboardEvent> get onKeyDown => (super.noSuchMethod( Invocation.getter(#onKeyDown), returnValue: _FakeElementStream_6<_i2.KeyboardEvent>( this, Invocation.getter(#onKeyDown), ), ) as _i2.ElementStream<_i2.KeyboardEvent>); @override _i2.ElementStream<_i2.KeyboardEvent> get onKeyPress => (super.noSuchMethod( Invocation.getter(#onKeyPress), returnValue: _FakeElementStream_6<_i2.KeyboardEvent>( this, Invocation.getter(#onKeyPress), ), ) as _i2.ElementStream<_i2.KeyboardEvent>); @override _i2.ElementStream<_i2.KeyboardEvent> get onKeyUp => (super.noSuchMethod( Invocation.getter(#onKeyUp), returnValue: _FakeElementStream_6<_i2.KeyboardEvent>( this, Invocation.getter(#onKeyUp), ), ) as _i2.ElementStream<_i2.KeyboardEvent>); @override _i2.ElementStream<_i2.Event> get onLoad => (super.noSuchMethod( Invocation.getter(#onLoad), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onLoad), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onLoadedData => (super.noSuchMethod( Invocation.getter(#onLoadedData), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onLoadedData), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onLoadedMetadata => (super.noSuchMethod( Invocation.getter(#onLoadedMetadata), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onLoadedMetadata), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseDown => (super.noSuchMethod( Invocation.getter(#onMouseDown), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onMouseDown), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseEnter => (super.noSuchMethod( Invocation.getter(#onMouseEnter), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onMouseEnter), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseLeave => (super.noSuchMethod( Invocation.getter(#onMouseLeave), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onMouseLeave), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseMove => (super.noSuchMethod( Invocation.getter(#onMouseMove), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onMouseMove), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseOut => (super.noSuchMethod( Invocation.getter(#onMouseOut), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onMouseOut), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseOver => (super.noSuchMethod( Invocation.getter(#onMouseOver), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onMouseOver), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.MouseEvent> get onMouseUp => (super.noSuchMethod( Invocation.getter(#onMouseUp), returnValue: _FakeElementStream_6<_i2.MouseEvent>( this, Invocation.getter(#onMouseUp), ), ) as _i2.ElementStream<_i2.MouseEvent>); @override _i2.ElementStream<_i2.WheelEvent> get onMouseWheel => (super.noSuchMethod( Invocation.getter(#onMouseWheel), returnValue: _FakeElementStream_6<_i2.WheelEvent>( this, Invocation.getter(#onMouseWheel), ), ) as _i2.ElementStream<_i2.WheelEvent>); @override _i2.ElementStream<_i2.ClipboardEvent> get onPaste => (super.noSuchMethod( Invocation.getter(#onPaste), returnValue: _FakeElementStream_6<_i2.ClipboardEvent>( this, Invocation.getter(#onPaste), ), ) as _i2.ElementStream<_i2.ClipboardEvent>); @override _i2.ElementStream<_i2.Event> get onPause => (super.noSuchMethod( Invocation.getter(#onPause), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onPause), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onPlay => (super.noSuchMethod( Invocation.getter(#onPlay), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onPlay), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onPlaying => (super.noSuchMethod( Invocation.getter(#onPlaying), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onPlaying), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onRateChange => (super.noSuchMethod( Invocation.getter(#onRateChange), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onRateChange), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onReset => (super.noSuchMethod( Invocation.getter(#onReset), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onReset), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onResize => (super.noSuchMethod( Invocation.getter(#onResize), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onResize), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onScroll => (super.noSuchMethod( Invocation.getter(#onScroll), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onScroll), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSearch => (super.noSuchMethod( Invocation.getter(#onSearch), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onSearch), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSeeked => (super.noSuchMethod( Invocation.getter(#onSeeked), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onSeeked), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSeeking => (super.noSuchMethod( Invocation.getter(#onSeeking), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onSeeking), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSelect => (super.noSuchMethod( Invocation.getter(#onSelect), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onSelect), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSelectStart => (super.noSuchMethod( Invocation.getter(#onSelectStart), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onSelectStart), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onStalled => (super.noSuchMethod( Invocation.getter(#onStalled), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onStalled), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSubmit => (super.noSuchMethod( Invocation.getter(#onSubmit), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onSubmit), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onSuspend => (super.noSuchMethod( Invocation.getter(#onSuspend), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onSuspend), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onTimeUpdate => (super.noSuchMethod( Invocation.getter(#onTimeUpdate), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onTimeUpdate), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchCancel => (super.noSuchMethod( Invocation.getter(#onTouchCancel), returnValue: _FakeElementStream_6<_i2.TouchEvent>( this, Invocation.getter(#onTouchCancel), ), ) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchEnd => (super.noSuchMethod( Invocation.getter(#onTouchEnd), returnValue: _FakeElementStream_6<_i2.TouchEvent>( this, Invocation.getter(#onTouchEnd), ), ) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchEnter => (super.noSuchMethod( Invocation.getter(#onTouchEnter), returnValue: _FakeElementStream_6<_i2.TouchEvent>( this, Invocation.getter(#onTouchEnter), ), ) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchLeave => (super.noSuchMethod( Invocation.getter(#onTouchLeave), returnValue: _FakeElementStream_6<_i2.TouchEvent>( this, Invocation.getter(#onTouchLeave), ), ) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchMove => (super.noSuchMethod( Invocation.getter(#onTouchMove), returnValue: _FakeElementStream_6<_i2.TouchEvent>( this, Invocation.getter(#onTouchMove), ), ) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TouchEvent> get onTouchStart => (super.noSuchMethod( Invocation.getter(#onTouchStart), returnValue: _FakeElementStream_6<_i2.TouchEvent>( this, Invocation.getter(#onTouchStart), ), ) as _i2.ElementStream<_i2.TouchEvent>); @override _i2.ElementStream<_i2.TransitionEvent> get onTransitionEnd => (super.noSuchMethod( Invocation.getter(#onTransitionEnd), returnValue: _FakeElementStream_6<_i2.TransitionEvent>( this, Invocation.getter(#onTransitionEnd), ), ) as _i2.ElementStream<_i2.TransitionEvent>); @override _i2.ElementStream<_i2.Event> get onVolumeChange => (super.noSuchMethod( Invocation.getter(#onVolumeChange), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onVolumeChange), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onWaiting => (super.noSuchMethod( Invocation.getter(#onWaiting), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onWaiting), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onFullscreenChange => (super.noSuchMethod( Invocation.getter(#onFullscreenChange), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onFullscreenChange), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.Event> get onFullscreenError => (super.noSuchMethod( Invocation.getter(#onFullscreenError), returnValue: _FakeElementStream_6<_i2.Event>( this, Invocation.getter(#onFullscreenError), ), ) as _i2.ElementStream<_i2.Event>); @override _i2.ElementStream<_i2.WheelEvent> get onWheel => (super.noSuchMethod( Invocation.getter(#onWheel), returnValue: _FakeElementStream_6<_i2.WheelEvent>( this, Invocation.getter(#onWheel), ), ) as _i2.ElementStream<_i2.WheelEvent>); @override List<_i2.Node> get nodes => (super.noSuchMethod( Invocation.getter(#nodes), returnValue: <_i2.Node>[], ) as List<_i2.Node>); @override set nodes(Iterable<_i2.Node>? value) => super.noSuchMethod( Invocation.setter( #nodes, value, ), returnValueForMissingStub: null, ); @override List<_i2.Node> get childNodes => (super.noSuchMethod( Invocation.getter(#childNodes), returnValue: <_i2.Node>[], ) as List<_i2.Node>); @override int get nodeType => (super.noSuchMethod( Invocation.getter(#nodeType), returnValue: 0, ) as int); @override set text(String? value) => super.noSuchMethod( Invocation.setter( #text, value, ), returnValueForMissingStub: null, ); @override String? getAttribute(String? name) => (super.noSuchMethod(Invocation.method( #getAttribute, [name], )) as String?); @override String? getAttributeNS( String? namespaceURI, String? name, ) => (super.noSuchMethod(Invocation.method( #getAttributeNS, [ namespaceURI, name, ], )) as String?); @override bool hasAttribute(String? name) => (super.noSuchMethod( Invocation.method( #hasAttribute, [name], ), returnValue: false, ) as bool); @override bool hasAttributeNS( String? namespaceURI, String? name, ) => (super.noSuchMethod( Invocation.method( #hasAttributeNS, [ namespaceURI, name, ], ), returnValue: false, ) as bool); @override void removeAttribute(String? name) => super.noSuchMethod( Invocation.method( #removeAttribute, [name], ), returnValueForMissingStub: null, ); @override void removeAttributeNS( String? namespaceURI, String? name, ) => super.noSuchMethod( Invocation.method( #removeAttributeNS, [ namespaceURI, name, ], ), returnValueForMissingStub: null, ); @override void setAttribute( String? name, Object? value, ) => super.noSuchMethod( Invocation.method( #setAttribute, [ name, value, ], ), returnValueForMissingStub: null, ); @override void setAttributeNS( String? namespaceURI, String? name, Object? value, ) => super.noSuchMethod( Invocation.method( #setAttributeNS, [ namespaceURI, name, value, ], ), returnValueForMissingStub: null, ); @override _i2.ElementList<T> querySelectorAll<T extends _i2.Element>( String? selectors) => (super.noSuchMethod( Invocation.method( #querySelectorAll, [selectors], ), returnValue: _FakeElementList_7<T>( this, Invocation.method( #querySelectorAll, [selectors], ), ), ) as _i2.ElementList<T>); @override _i7.Future<_i2.ScrollState> setApplyScroll(String? nativeScrollBehavior) => (super.noSuchMethod( Invocation.method( #setApplyScroll, [nativeScrollBehavior], ), returnValue: _i7.Future<_i2.ScrollState>.value(_FakeScrollState_8( this, Invocation.method( #setApplyScroll, [nativeScrollBehavior], ), )), ) as _i7.Future<_i2.ScrollState>); @override _i7.Future<_i2.ScrollState> setDistributeScroll( String? nativeScrollBehavior) => (super.noSuchMethod( Invocation.method( #setDistributeScroll, [nativeScrollBehavior], ), returnValue: _i7.Future<_i2.ScrollState>.value(_FakeScrollState_8( this, Invocation.method( #setDistributeScroll, [nativeScrollBehavior], ), )), ) as _i7.Future<_i2.ScrollState>); @override Map<String, String> getNamespacedAttributes(String? namespace) => (super.noSuchMethod( Invocation.method( #getNamespacedAttributes, [namespace], ), returnValue: <String, String>{}, ) as Map<String, String>); @override _i2.CssStyleDeclaration getComputedStyle([String? pseudoElement]) => (super.noSuchMethod( Invocation.method( #getComputedStyle, [pseudoElement], ), returnValue: _FakeCssStyleDeclaration_5( this, Invocation.method( #getComputedStyle, [pseudoElement], ), ), ) as _i2.CssStyleDeclaration); @override void appendText(String? text) => super.noSuchMethod( Invocation.method( #appendText, [text], ), returnValueForMissingStub: null, ); @override void appendHtml( String? text, { _i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer, }) => super.noSuchMethod( Invocation.method( #appendHtml, [text], { #validator: validator, #treeSanitizer: treeSanitizer, }, ), returnValueForMissingStub: null, ); @override void attached() => super.noSuchMethod( Invocation.method( #attached, [], ), returnValueForMissingStub: null, ); @override void detached() => super.noSuchMethod( Invocation.method( #detached, [], ), returnValueForMissingStub: null, ); @override void enteredView() => super.noSuchMethod( Invocation.method( #enteredView, [], ), returnValueForMissingStub: null, ); @override List<_i3.Rectangle<num>> getClientRects() => (super.noSuchMethod( Invocation.method( #getClientRects, [], ), returnValue: <_i3.Rectangle<num>>[], ) as List<_i3.Rectangle<num>>); @override void leftView() => super.noSuchMethod( Invocation.method( #leftView, [], ), returnValueForMissingStub: null, ); @override _i2.Animation animate( Iterable<Map<String, dynamic>>? frames, [ dynamic timing, ]) => (super.noSuchMethod( Invocation.method( #animate, [ frames, timing, ], ), returnValue: _FakeAnimation_9( this, Invocation.method( #animate, [ frames, timing, ], ), ), ) as _i2.Animation); @override void attributeChanged( String? name, String? oldValue, String? newValue, ) => super.noSuchMethod( Invocation.method( #attributeChanged, [ name, oldValue, newValue, ], ), returnValueForMissingStub: null, ); @override void scrollIntoView([_i2.ScrollAlignment? alignment]) => super.noSuchMethod( Invocation.method( #scrollIntoView, [alignment], ), returnValueForMissingStub: null, ); @override void insertAdjacentText( String? where, String? text, ) => super.noSuchMethod( Invocation.method( #insertAdjacentText, [ where, text, ], ), returnValueForMissingStub: null, ); @override void insertAdjacentHtml( String? where, String? html, { _i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer, }) => super.noSuchMethod( Invocation.method( #insertAdjacentHtml, [ where, html, ], { #validator: validator, #treeSanitizer: treeSanitizer, }, ), returnValueForMissingStub: null, ); @override _i2.Element insertAdjacentElement( String? where, _i2.Element? element, ) => (super.noSuchMethod( Invocation.method( #insertAdjacentElement, [ where, element, ], ), returnValue: _FakeElement_10( this, Invocation.method( #insertAdjacentElement, [ where, element, ], ), ), ) as _i2.Element); @override bool matches(String? selectors) => (super.noSuchMethod( Invocation.method( #matches, [selectors], ), returnValue: false, ) as bool); @override bool matchesWithAncestors(String? selectors) => (super.noSuchMethod( Invocation.method( #matchesWithAncestors, [selectors], ), returnValue: false, ) as bool); @override _i2.ShadowRoot createShadowRoot() => (super.noSuchMethod( Invocation.method( #createShadowRoot, [], ), returnValue: _FakeShadowRoot_11( this, Invocation.method( #createShadowRoot, [], ), ), ) as _i2.ShadowRoot); @override _i3.Point<num> offsetTo(_i2.Element? parent) => (super.noSuchMethod( Invocation.method( #offsetTo, [parent], ), returnValue: _FakePoint_3<num>( this, Invocation.method( #offsetTo, [parent], ), ), ) as _i3.Point<num>); @override _i2.DocumentFragment createFragment( String? html, { _i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer, }) => (super.noSuchMethod( Invocation.method( #createFragment, [html], { #validator: validator, #treeSanitizer: treeSanitizer, }, ), returnValue: _FakeDocumentFragment_12( this, Invocation.method( #createFragment, [html], { #validator: validator, #treeSanitizer: treeSanitizer, }, ), ), ) as _i2.DocumentFragment); @override void setInnerHtml( String? html, { _i2.NodeValidator? validator, _i2.NodeTreeSanitizer? treeSanitizer, }) => super.noSuchMethod( Invocation.method( #setInnerHtml, [html], { #validator: validator, #treeSanitizer: treeSanitizer, }, ), returnValueForMissingStub: null, ); @override _i7.Future<void> requestFullscreen([Map<dynamic, dynamic>? options]) => (super.noSuchMethod( Invocation.method( #requestFullscreen, [options], ), returnValue: _i7.Future<void>.value(), returnValueForMissingStub: _i7.Future<void>.value(), ) as _i7.Future<void>); @override void blur() => super.noSuchMethod( Invocation.method( #blur, [], ), returnValueForMissingStub: null, ); @override void click() => super.noSuchMethod( Invocation.method( #click, [], ), returnValueForMissingStub: null, ); @override void focus() => super.noSuchMethod( Invocation.method( #focus, [], ), returnValueForMissingStub: null, ); @override _i2.ShadowRoot attachShadow(Map<dynamic, dynamic>? shadowRootInitDict) => (super.noSuchMethod( Invocation.method( #attachShadow, [shadowRootInitDict], ), returnValue: _FakeShadowRoot_11( this, Invocation.method( #attachShadow, [shadowRootInitDict], ), ), ) as _i2.ShadowRoot); @override _i2.Element? closest(String? selectors) => (super.noSuchMethod(Invocation.method( #closest, [selectors], )) as _i2.Element?); @override List<_i2.Animation> getAnimations() => (super.noSuchMethod( Invocation.method( #getAnimations, [], ), returnValue: <_i2.Animation>[], ) as List<_i2.Animation>); @override List<String> getAttributeNames() => (super.noSuchMethod( Invocation.method( #getAttributeNames, [], ), returnValue: <String>[], ) as List<String>); @override _i3.Rectangle<num> getBoundingClientRect() => (super.noSuchMethod( Invocation.method( #getBoundingClientRect, [], ), returnValue: _FakeRectangle_1<num>( this, Invocation.method( #getBoundingClientRect, [], ), ), ) as _i3.Rectangle<num>); @override List<_i2.Node> getDestinationInsertionPoints() => (super.noSuchMethod( Invocation.method( #getDestinationInsertionPoints, [], ), returnValue: <_i2.Node>[], ) as List<_i2.Node>); @override List<_i2.Node> getElementsByClassName(String? classNames) => (super.noSuchMethod( Invocation.method( #getElementsByClassName, [classNames], ), returnValue: <_i2.Node>[], ) as List<_i2.Node>); @override bool hasPointerCapture(int? pointerId) => (super.noSuchMethod( Invocation.method( #hasPointerCapture, [pointerId], ), returnValue: false, ) as bool); @override void releasePointerCapture(int? pointerId) => super.noSuchMethod( Invocation.method( #releasePointerCapture, [pointerId], ), returnValueForMissingStub: null, ); @override void requestPointerLock() => super.noSuchMethod( Invocation.method( #requestPointerLock, [], ), returnValueForMissingStub: null, ); @override void scroll([ dynamic options_OR_x, num? y, ]) => super.noSuchMethod( Invocation.method( #scroll, [ options_OR_x, y, ], ), returnValueForMissingStub: null, ); @override void scrollBy([ dynamic options_OR_x, num? y, ]) => super.noSuchMethod( Invocation.method( #scrollBy, [ options_OR_x, y, ], ), returnValueForMissingStub: null, ); @override void scrollIntoViewIfNeeded([bool? centerIfNeeded]) => super.noSuchMethod( Invocation.method( #scrollIntoViewIfNeeded, [centerIfNeeded], ), returnValueForMissingStub: null, ); @override void scrollTo([ dynamic options_OR_x, num? y, ]) => super.noSuchMethod( Invocation.method( #scrollTo, [ options_OR_x, y, ], ), returnValueForMissingStub: null, ); @override void setPointerCapture(int? pointerId) => super.noSuchMethod( Invocation.method( #setPointerCapture, [pointerId], ), returnValueForMissingStub: null, ); @override void after(Object? nodes) => super.noSuchMethod( Invocation.method( #after, [nodes], ), returnValueForMissingStub: null, ); @override void before(Object? nodes) => super.noSuchMethod( Invocation.method( #before, [nodes], ), returnValueForMissingStub: null, ); @override _i2.Element? querySelector(String? selectors) => (super.noSuchMethod(Invocation.method( #querySelector, [selectors], )) as _i2.Element?); @override void remove() => super.noSuchMethod( Invocation.method( #remove, [], ), returnValueForMissingStub: null, ); @override _i2.Node replaceWith(_i2.Node? otherNode) => (super.noSuchMethod( Invocation.method( #replaceWith, [otherNode], ), returnValue: _FakeNode_13( this, Invocation.method( #replaceWith, [otherNode], ), ), ) as _i2.Node); @override void insertAllBefore( Iterable<_i2.Node>? newNodes, _i2.Node? child, ) => super.noSuchMethod( Invocation.method( #insertAllBefore, [ newNodes, child, ], ), returnValueForMissingStub: null, ); @override _i2.Node append(_i2.Node? node) => (super.noSuchMethod( Invocation.method( #append, [node], ), returnValue: _FakeNode_13( this, Invocation.method( #append, [node], ), ), ) as _i2.Node); @override _i2.Node clone(bool? deep) => (super.noSuchMethod( Invocation.method( #clone, [deep], ), returnValue: _FakeNode_13( this, Invocation.method( #clone, [deep], ), ), ) as _i2.Node); @override bool contains(_i2.Node? other) => (super.noSuchMethod( Invocation.method( #contains, [other], ), returnValue: false, ) as bool); @override _i2.Node getRootNode([Map<dynamic, dynamic>? options]) => (super.noSuchMethod( Invocation.method( #getRootNode, [options], ), returnValue: _FakeNode_13( this, Invocation.method( #getRootNode, [options], ), ), ) as _i2.Node); @override bool hasChildNodes() => (super.noSuchMethod( Invocation.method( #hasChildNodes, [], ), returnValue: false, ) as bool); @override _i2.Node insertBefore( _i2.Node? node, _i2.Node? child, ) => (super.noSuchMethod( Invocation.method( #insertBefore, [ node, child, ], ), returnValue: _FakeNode_13( this, Invocation.method( #insertBefore, [ node, child, ], ), ), ) as _i2.Node); @override void addEventListener( String? type, _i2.EventListener? listener, [ bool? useCapture, ]) => super.noSuchMethod( Invocation.method( #addEventListener, [ type, listener, useCapture, ], ), returnValueForMissingStub: null, ); @override void removeEventListener( String? type, _i2.EventListener? listener, [ bool? useCapture, ]) => super.noSuchMethod( Invocation.method( #removeEventListener, [ type, listener, useCapture, ], ), returnValueForMissingStub: null, ); @override bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod( Invocation.method( #dispatchEvent, [event], ), returnValue: false, ) as bool); } /// A class which mocks [BuildContext]. /// /// See the documentation for Mockito's code generation for more information. class MockBuildContext extends _i1.Mock implements _i4.BuildContext { MockBuildContext() { _i1.throwOnMissingStub(this); } @override _i4.Widget get widget => (super.noSuchMethod( Invocation.getter(#widget), returnValue: _FakeWidget_14( this, Invocation.getter(#widget), ), ) as _i4.Widget); @override bool get mounted => (super.noSuchMethod( Invocation.getter(#mounted), returnValue: false, ) as bool); @override bool get debugDoingBuild => (super.noSuchMethod( Invocation.getter(#debugDoingBuild), returnValue: false, ) as bool); @override _i4.InheritedWidget dependOnInheritedElement( _i4.InheritedElement? ancestor, { Object? aspect, }) => (super.noSuchMethod( Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}, ), returnValue: _FakeInheritedWidget_15( this, Invocation.method( #dependOnInheritedElement, [ancestor], {#aspect: aspect}, ), ), ) as _i4.InheritedWidget); @override void visitAncestorElements(_i4.ConditionalElementVisitor? visitor) => super.noSuchMethod( Invocation.method( #visitAncestorElements, [visitor], ), returnValueForMissingStub: null, ); @override void visitChildElements(_i4.ElementVisitor? visitor) => super.noSuchMethod( Invocation.method( #visitChildElements, [visitor], ), returnValueForMissingStub: null, ); @override void dispatchNotification(_i8.Notification? notification) => super.noSuchMethod( Invocation.method( #dispatchNotification, [notification], ), returnValueForMissingStub: null, ); @override _i5.DiagnosticsNode describeElement( String? name, { _i5.DiagnosticsTreeStyle? style = _i5.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( Invocation.method( #describeElement, [name], {#style: style}, ), returnValue: _FakeDiagnosticsNode_16( this, Invocation.method( #describeElement, [name], {#style: style}, ), ), ) as _i5.DiagnosticsNode); @override _i5.DiagnosticsNode describeWidget( String? name, { _i5.DiagnosticsTreeStyle? style = _i5.DiagnosticsTreeStyle.errorProperty, }) => (super.noSuchMethod( Invocation.method( #describeWidget, [name], {#style: style}, ), returnValue: _FakeDiagnosticsNode_16( this, Invocation.method( #describeWidget, [name], {#style: style}, ), ), ) as _i5.DiagnosticsNode); @override List<_i5.DiagnosticsNode> describeMissingAncestor( {required Type? expectedAncestorType}) => (super.noSuchMethod( Invocation.method( #describeMissingAncestor, [], {#expectedAncestorType: expectedAncestorType}, ), returnValue: <_i5.DiagnosticsNode>[], ) as List<_i5.DiagnosticsNode>); @override _i5.DiagnosticsNode describeOwnershipChain(String? name) => (super.noSuchMethod( Invocation.method( #describeOwnershipChain, [name], ), returnValue: _FakeDiagnosticsNode_16( this, Invocation.method( #describeOwnershipChain, [name], ), ), ) as _i5.DiagnosticsNode); } /// A class which mocks [CreationParams]. /// /// See the documentation for Mockito's code generation for more information. class MockCreationParams extends _i1.Mock implements _i9.CreationParams { MockCreationParams() { _i1.throwOnMissingStub(this); } @override Set<String> get javascriptChannelNames => (super.noSuchMethod( Invocation.getter(#javascriptChannelNames), returnValue: <String>{}, ) as Set<String>); @override _i9.AutoMediaPlaybackPolicy get autoMediaPlaybackPolicy => (super.noSuchMethod( Invocation.getter(#autoMediaPlaybackPolicy), returnValue: _i9.AutoMediaPlaybackPolicy.require_user_action_for_all_media_types, ) as _i9.AutoMediaPlaybackPolicy); @override List<_i9.WebViewCookie> get cookies => (super.noSuchMethod( Invocation.getter(#cookies), returnValue: <_i9.WebViewCookie>[], ) as List<_i9.WebViewCookie>); } /// A class which mocks [WebViewPlatformCallbacksHandler]. /// /// See the documentation for Mockito's code generation for more information. class MockWebViewPlatformCallbacksHandler extends _i1.Mock implements _i10.WebViewPlatformCallbacksHandler { MockWebViewPlatformCallbacksHandler() { _i1.throwOnMissingStub(this); } @override _i7.FutureOr<bool> onNavigationRequest({ required String? url, required bool? isForMainFrame, }) => (super.noSuchMethod( Invocation.method( #onNavigationRequest, [], { #url: url, #isForMainFrame: isForMainFrame, }, ), returnValue: _i7.Future<bool>.value(false), ) as _i7.FutureOr<bool>); @override void onPageStarted(String? url) => super.noSuchMethod( Invocation.method( #onPageStarted, [url], ), returnValueForMissingStub: null, ); @override void onPageFinished(String? url) => super.noSuchMethod( Invocation.method( #onPageFinished, [url], ), returnValueForMissingStub: null, ); @override void onProgress(int? progress) => super.noSuchMethod( Invocation.method( #onProgress, [progress], ), returnValueForMissingStub: null, ); @override void onWebResourceError(_i9.WebResourceError? error) => super.noSuchMethod( Invocation.method( #onWebResourceError, [error], ), returnValueForMissingStub: null, ); } /// A class which mocks [HttpRequestFactory]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpRequestFactory extends _i1.Mock implements _i11.HttpRequestFactory { MockHttpRequestFactory() { _i1.throwOnMissingStub(this); } @override _i7.Future<_i2.HttpRequest> request( String? url, { String? method, bool? withCredentials, String? responseType, String? mimeType, Map<String, String>? requestHeaders, dynamic sendData, void Function(_i2.ProgressEvent)? onProgress, }) => (super.noSuchMethod( Invocation.method( #request, [url], { #method: method, #withCredentials: withCredentials, #responseType: responseType, #mimeType: mimeType, #requestHeaders: requestHeaders, #sendData: sendData, #onProgress: onProgress, }, ), returnValue: _i7.Future<_i2.HttpRequest>.value(_FakeHttpRequest_17( this, Invocation.method( #request, [url], { #method: method, #withCredentials: withCredentials, #responseType: responseType, #mimeType: mimeType, #requestHeaders: requestHeaders, #sendData: sendData, #onProgress: onProgress, }, ), )), ) as _i7.Future<_i2.HttpRequest>); } /// A class which mocks [HttpRequest]. /// /// See the documentation for Mockito's code generation for more information. class MockHttpRequest extends _i1.Mock implements _i2.HttpRequest { MockHttpRequest() { _i1.throwOnMissingStub(this); } @override Map<String, String> get responseHeaders => (super.noSuchMethod( Invocation.getter(#responseHeaders), returnValue: <String, String>{}, ) as Map<String, String>); @override int get readyState => (super.noSuchMethod( Invocation.getter(#readyState), returnValue: 0, ) as int); @override String get responseType => (super.noSuchMethod( Invocation.getter(#responseType), returnValue: _i6.dummyValue<String>( this, Invocation.getter(#responseType), ), ) as String); @override set responseType(String? value) => super.noSuchMethod( Invocation.setter( #responseType, value, ), returnValueForMissingStub: null, ); @override set timeout(int? value) => super.noSuchMethod( Invocation.setter( #timeout, value, ), returnValueForMissingStub: null, ); @override _i2.HttpRequestUpload get upload => (super.noSuchMethod( Invocation.getter(#upload), returnValue: _FakeHttpRequestUpload_18( this, Invocation.getter(#upload), ), ) as _i2.HttpRequestUpload); @override set withCredentials(bool? value) => super.noSuchMethod( Invocation.setter( #withCredentials, value, ), returnValueForMissingStub: null, ); @override _i7.Stream<_i2.Event> get onReadyStateChange => (super.noSuchMethod( Invocation.getter(#onReadyStateChange), returnValue: _i7.Stream<_i2.Event>.empty(), ) as _i7.Stream<_i2.Event>); @override _i7.Stream<_i2.ProgressEvent> get onAbort => (super.noSuchMethod( Invocation.getter(#onAbort), returnValue: _i7.Stream<_i2.ProgressEvent>.empty(), ) as _i7.Stream<_i2.ProgressEvent>); @override _i7.Stream<_i2.ProgressEvent> get onError => (super.noSuchMethod( Invocation.getter(#onError), returnValue: _i7.Stream<_i2.ProgressEvent>.empty(), ) as _i7.Stream<_i2.ProgressEvent>); @override _i7.Stream<_i2.ProgressEvent> get onLoad => (super.noSuchMethod( Invocation.getter(#onLoad), returnValue: _i7.Stream<_i2.ProgressEvent>.empty(), ) as _i7.Stream<_i2.ProgressEvent>); @override _i7.Stream<_i2.ProgressEvent> get onLoadEnd => (super.noSuchMethod( Invocation.getter(#onLoadEnd), returnValue: _i7.Stream<_i2.ProgressEvent>.empty(), ) as _i7.Stream<_i2.ProgressEvent>); @override _i7.Stream<_i2.ProgressEvent> get onLoadStart => (super.noSuchMethod( Invocation.getter(#onLoadStart), returnValue: _i7.Stream<_i2.ProgressEvent>.empty(), ) as _i7.Stream<_i2.ProgressEvent>); @override _i7.Stream<_i2.ProgressEvent> get onProgress => (super.noSuchMethod( Invocation.getter(#onProgress), returnValue: _i7.Stream<_i2.ProgressEvent>.empty(), ) as _i7.Stream<_i2.ProgressEvent>); @override _i7.Stream<_i2.ProgressEvent> get onTimeout => (super.noSuchMethod( Invocation.getter(#onTimeout), returnValue: _i7.Stream<_i2.ProgressEvent>.empty(), ) as _i7.Stream<_i2.ProgressEvent>); @override _i2.Events get on => (super.noSuchMethod( Invocation.getter(#on), returnValue: _FakeEvents_19( this, Invocation.getter(#on), ), ) as _i2.Events); @override void open( String? method, String? url, { bool? async, String? user, String? password, }) => super.noSuchMethod( Invocation.method( #open, [ method, url, ], { #async: async, #user: user, #password: password, }, ), returnValueForMissingStub: null, ); @override void abort() => super.noSuchMethod( Invocation.method( #abort, [], ), returnValueForMissingStub: null, ); @override String getAllResponseHeaders() => (super.noSuchMethod( Invocation.method( #getAllResponseHeaders, [], ), returnValue: _i6.dummyValue<String>( this, Invocation.method( #getAllResponseHeaders, [], ), ), ) as String); @override String? getResponseHeader(String? name) => (super.noSuchMethod(Invocation.method( #getResponseHeader, [name], )) as String?); @override void overrideMimeType(String? mime) => super.noSuchMethod( Invocation.method( #overrideMimeType, [mime], ), returnValueForMissingStub: null, ); @override void send([dynamic body_OR_data]) => super.noSuchMethod( Invocation.method( #send, [body_OR_data], ), returnValueForMissingStub: null, ); @override void setRequestHeader( String? name, String? value, ) => super.noSuchMethod( Invocation.method( #setRequestHeader, [ name, value, ], ), returnValueForMissingStub: null, ); @override void addEventListener( String? type, _i2.EventListener? listener, [ bool? useCapture, ]) => super.noSuchMethod( Invocation.method( #addEventListener, [ type, listener, useCapture, ], ), returnValueForMissingStub: null, ); @override void removeEventListener( String? type, _i2.EventListener? listener, [ bool? useCapture, ]) => super.noSuchMethod( Invocation.method( #removeEventListener, [ type, listener, useCapture, ], ), returnValueForMissingStub: null, ); @override bool dispatchEvent(_i2.Event? event) => (super.noSuchMethod( Invocation.method( #dispatchEvent, [event], ), returnValue: false, ) as bool); }
packages/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.mocks.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_web/test/legacy/webview_flutter_web_test.mocks.dart", "repo_id": "packages", "token_count": 35502 }
1,141
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This test is run using `flutter drive` by the CI (see /script/tool/README.md // in this repository for details on driving that tooling manually), but can // also be run using `flutter test` directly during development. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; import 'package:webview_flutter_wkwebview/src/common/instance_manager.dart'; import 'package:webview_flutter_wkwebview/src/common/weak_reference_utils.dart'; import 'package:webview_flutter_wkwebview/src/web_kit/web_kit.dart'; import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'; Future<void> main() async { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); final HttpServer server = await HttpServer.bind(InternetAddress.anyIPv4, 0); unawaited(server.forEach((HttpRequest request) { if (request.uri.path == '/hello.txt') { request.response.writeln('Hello, world.'); } else if (request.uri.path == '/secondary.txt') { request.response.writeln('How are you today?'); } else if (request.uri.path == '/headers') { request.response.writeln('${request.headers}'); } else if (request.uri.path == '/favicon.ico') { request.response.statusCode = HttpStatus.notFound; } else if (request.uri.path == '/http-basic-authentication') { final bool isAuthenticating = request.headers['Authorization'] != null; if (isAuthenticating) { request.response.writeln('Authorized'); } else { request.response.headers .add('WWW-Authenticate', 'Basic realm="Test realm"'); request.response.statusCode = HttpStatus.unauthorized; } } else { fail('unexpected request: ${request.method} ${request.uri}'); } request.response.close(); })); final String prefixUrl = 'http://${server.address.address}:${server.port}'; final String primaryUrl = '$prefixUrl/hello.txt'; final String secondaryUrl = '$prefixUrl/secondary.txt'; final String headersUrl = '$prefixUrl/headers'; final String basicAuthUrl = '$prefixUrl/http-basic-authentication'; testWidgets( 'withWeakReferenceTo allows encapsulating class to be garbage collected', (WidgetTester tester) async { final Completer<int> gcCompleter = Completer<int>(); final InstanceManager instanceManager = InstanceManager( onWeakReferenceRemoved: gcCompleter.complete, ); ClassWithCallbackClass? instance = ClassWithCallbackClass(); instanceManager.addHostCreatedInstance(instance.callbackClass, 0); instance = null; // Force garbage collection. await IntegrationTestWidgetsFlutterBinding.instance .watchPerformance(() async { await tester.pumpAndSettle(); }); final int gcIdentifier = await gcCompleter.future; expect(gcIdentifier, 0); }, timeout: const Timeout(Duration(seconds: 10))); testWidgets( 'WKWebView is released by garbage collection', (WidgetTester tester) async { bool aWebViewHasBeenGarbageCollected = false; late final InstanceManager instanceManager; instanceManager = InstanceManager(onWeakReferenceRemoved: (int identifier) { if (!aWebViewHasBeenGarbageCollected) { final Copyable instance = instanceManager.getInstanceWithWeakReference(identifier)!; if (instance is WKWebView) { aWebViewHasBeenGarbageCollected = true; } } }); // Wait for any WebView to be garbage collected. while (!aWebViewHasBeenGarbageCollected) { await tester.pumpWidget( Builder( builder: (BuildContext context) { return PlatformWebViewWidget( WebKitWebViewWidgetCreationParams( instanceManager: instanceManager, controller: PlatformWebViewController( WebKitWebViewControllerCreationParams( instanceManager: instanceManager, ), ), ), ).build(context); }, ), ); await tester.pumpAndSettle(); await tester.pumpWidget(Container()); // Force garbage collection. await IntegrationTestWidgetsFlutterBinding.instance .watchPerformance(() async { await tester.pumpAndSettle(); }); } }, timeout: const Timeout(Duration(seconds: 30)), ); testWidgets('loadRequest', (WidgetTester tester) async { final Completer<void> pageFinished = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageFinished.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams(uri: Uri.parse(primaryUrl)), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageFinished.future; final String? currentUrl = await controller.currentUrl(); expect(currentUrl, primaryUrl); }); testWidgets('runJavaScriptReturningResult', (WidgetTester tester) async { final Completer<void> pageFinished = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageFinished.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageFinished.future; await expectLater( controller.runJavaScriptReturningResult('1 + 1'), completion(2), ); }); testWidgets('loadRequest with headers', (WidgetTester tester) async { final Map<String, String> headers = <String, String>{ 'test_header': 'flutter_test_header' }; final StreamController<String> pageLoads = StreamController<String>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((String url) => pageLoads.add(url))); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse(headersUrl), headers: headers, ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoads.stream.firstWhere((String url) => url == headersUrl); final String content = await controller.runJavaScriptReturningResult( 'document.documentElement.innerText', ) as String; expect(content.contains('flutter_test_header'), isTrue); }); testWidgets('JavascriptChannel', (WidgetTester tester) async { final Completer<void> pageFinished = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageFinished.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); final Completer<String> channelCompleter = Completer<String>(); await controller.addJavaScriptChannel( JavaScriptChannelParams( name: 'Echo', onMessageReceived: (JavaScriptMessage message) { channelCompleter.complete(message.message); }, ), ); await controller.loadHtmlString( 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageFinished.future; await controller.runJavaScript('Echo.postMessage("hello");'); await expectLater(channelCompleter.future, completion('hello')); }); testWidgets('resize webview', (WidgetTester tester) async { final Completer<void> buttonTapResizeCompleter = Completer<void>(); final Completer<void> onPageFinished = Completer<void>(); bool resizeButtonTapped = false; await tester.pumpWidget(ResizableWebView( onResize: () { if (resizeButtonTapped) { buttonTapResizeCompleter.complete(); } }, onPageFinished: () => onPageFinished.complete(), )); await onPageFinished.future; resizeButtonTapped = true; await tester.tap(find.byKey(const ValueKey<String>('resizeButton'))); await tester.pumpAndSettle(); await expectLater(buttonTapResizeCompleter.future, completes); }); testWidgets('set custom userAgent', (WidgetTester tester) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited(controller.setUserAgent('Custom_User_Agent1')); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); final String? customUserAgent = await controller.getUserAgent(); expect(customUserAgent, 'Custom_User_Agent1'); }); testWidgets( 'getUserAgent returns a default value when custom value is not set', (WidgetTester tester) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); final String? userAgent = await controller.getUserAgent(); expect(userAgent, isNotNull); expect(userAgent, isNotEmpty); }); group('Video playback policy', () { late String videoTestBase64; setUpAll(() async { final ByteData videoData = await rootBundle.load('assets/sample_video.mp4'); final String base64VideoData = base64Encode(Uint8List.view(videoData.buffer)); final String videoTest = ''' <!DOCTYPE html><html> <head><title>Video auto play</title> <script type="text/javascript"> function play() { var video = document.getElementById("video"); video.play(); video.addEventListener('timeupdate', videoTimeUpdateHandler, false); } function videoTimeUpdateHandler(e) { var video = document.getElementById("video"); VideoTestTime.postMessage(video.currentTime); } function isPaused() { var video = document.getElementById("video"); return video.paused; } function isFullScreen() { var video = document.getElementById("video"); return video.webkitDisplayingFullscreen; } </script> </head> <body onload="play();"> <video controls playsinline autoplay id="video"> <source src="data:video/mp4;charset=utf-8;base64,$base64VideoData"> </video> </body> </html> '''; videoTestBase64 = base64Encode(const Utf8Encoder().convert(videoTest)); }); testWidgets('Auto media playback', (WidgetTester tester) async { Completer<void> pageLoaded = Completer<void>(); WebKitWebViewController controller = WebKitWebViewController( WebKitWebViewControllerCreationParams( mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{}, ), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); WebKitNavigationDelegate delegate = WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$videoTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; bool isPaused = await controller.runJavaScriptReturningResult('isPaused();') as bool; expect(isPaused, false); pageLoaded = Completer<void>(); controller = WebKitWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); delegate = WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$videoTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; isPaused = await controller.runJavaScriptReturningResult('isPaused();') as bool; expect(isPaused, true); }); testWidgets('Video plays inline when allowsInlineMediaPlayback is true', (WidgetTester tester) async { final Completer<void> pageLoaded = Completer<void>(); final Completer<void> videoPlaying = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( WebKitWebViewControllerCreationParams( mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{}, allowsInlineMediaPlayback: true, ), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final WebKitNavigationDelegate delegate = WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); unawaited(controller.addJavaScriptChannel( JavaScriptChannelParams( name: 'VideoTestTime', onMessageReceived: (JavaScriptMessage message) { final double currentTime = double.parse(message.message); // Let it play for at least 1 second to make sure the related video's properties are set. if (currentTime > 1 && !videoPlaying.isCompleted) { videoPlaying.complete(null); } }, ), )); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$videoTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await tester.pumpAndSettle(); await pageLoaded.future; // Makes sure we get the correct event that indicates the video is actually playing. await videoPlaying.future; final bool fullScreen = await controller .runJavaScriptReturningResult('isFullScreen();') as bool; expect(fullScreen, false); }); testWidgets( 'Video plays full screen when allowsInlineMediaPlayback is false', (WidgetTester tester) async { final Completer<void> pageLoaded = Completer<void>(); final Completer<void> videoPlaying = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( WebKitWebViewControllerCreationParams( mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{}, ), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final WebKitNavigationDelegate delegate = WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); unawaited(controller.addJavaScriptChannel( JavaScriptChannelParams( name: 'VideoTestTime', onMessageReceived: (JavaScriptMessage message) { final double currentTime = double.parse(message.message); // Let it play for at least 1 second to make sure the related video's properties are set. if (currentTime > 1 && !videoPlaying.isCompleted) { videoPlaying.complete(null); } }, ), )); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$videoTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await tester.pumpAndSettle(); await pageLoaded.future; // Makes sure we get the correct event that indicates the video is actually playing. await videoPlaying.future; final bool fullScreen = await controller .runJavaScriptReturningResult('isFullScreen();') as bool; expect(fullScreen, true); }); }); group('Audio playback policy', () { late String audioTestBase64; setUpAll(() async { final ByteData audioData = await rootBundle.load('assets/sample_audio.ogg'); final String base64AudioData = base64Encode(Uint8List.view(audioData.buffer)); final String audioTest = ''' <!DOCTYPE html><html> <head><title>Audio auto play</title> <script type="text/javascript"> function play() { var audio = document.getElementById("audio"); audio.play(); } function isPaused() { var audio = document.getElementById("audio"); return audio.paused; } </script> </head> <body onload="play();"> <audio controls id="audio"> <source src="data:audio/ogg;charset=utf-8;base64,$base64AudioData"> </audio> </body> </html> '''; audioTestBase64 = base64Encode(const Utf8Encoder().convert(audioTest)); }); testWidgets('Auto media playback', (WidgetTester tester) async { Completer<void> pageLoaded = Completer<void>(); PlatformWebViewController controller = PlatformWebViewController( WebKitWebViewControllerCreationParams( mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{}, ), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); WebKitNavigationDelegate delegate = WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$audioTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; bool isPaused = await controller.runJavaScriptReturningResult('isPaused();') as bool; expect(isPaused, false); pageLoaded = Completer<void>(); controller = PlatformWebViewController( WebKitWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); delegate = WebKitNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$audioTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; isPaused = await controller.runJavaScriptReturningResult('isPaused();') as bool; expect(isPaused, true); }); }); testWidgets('getTitle', (WidgetTester tester) async { const String getTitleTest = ''' <!DOCTYPE html><html> <head><title>Some title</title> </head> <body> </body> </html> '''; final String getTitleTestBase64 = base64Encode(const Utf8Encoder().convert(getTitleTest)); final Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$getTitleTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; // On at least iOS, it does not appear to be guaranteed that the native // code has the title when the page load completes. Execute some JavaScript // before checking the title to ensure that the page has been fully parsed // and processed. await controller.runJavaScript('1;'); final String? title = await controller.getTitle(); expect(title, 'Some title'); }); group('Programmatic Scroll', () { testWidgets('setAndGetAndListenScrollPosition', (WidgetTester tester) async { const String scrollTestPage = ''' <!DOCTYPE html> <html> <head> <style> body { height: 100%; width: 100%; } #container{ width:5000px; height:5000px; } </style> </head> <body> <div id="container"/> </body> </html> '''; final String scrollTestPageBase64 = base64Encode(const Utf8Encoder().convert(scrollTestPage)); final Completer<void> pageLoaded = Completer<void>(); ScrollPositionChange? recordedPosition; final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); unawaited(controller.setOnScrollPositionChange( (ScrollPositionChange scrollPositionChange) { recordedPosition = scrollPositionChange; })); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$scrollTestPageBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; await tester.pumpAndSettle(const Duration(seconds: 3)); Offset scrollPos = await controller.getScrollPosition(); // Check scrollTo() const int X_SCROLL = 123; const int Y_SCROLL = 321; // Get the initial position; this ensures that scrollTo is actually // changing something, but also gives the native view's scroll position // time to settle. expect(scrollPos.dx, isNot(X_SCROLL)); expect(scrollPos.dy, isNot(Y_SCROLL)); expect(recordedPosition?.x, isNot(X_SCROLL)); expect(recordedPosition?.y, isNot(Y_SCROLL)); await controller.scrollTo(X_SCROLL, Y_SCROLL); scrollPos = await controller.getScrollPosition(); expect(scrollPos.dx, X_SCROLL); expect(scrollPos.dy, Y_SCROLL); expect(recordedPosition?.x, X_SCROLL); expect(recordedPosition?.y, Y_SCROLL); // Check scrollBy() (on top of scrollTo()) await controller.scrollBy(X_SCROLL, Y_SCROLL); scrollPos = await controller.getScrollPosition(); expect(scrollPos.dx, X_SCROLL * 2); expect(scrollPos.dy, Y_SCROLL * 2); expect(recordedPosition?.x, X_SCROLL * 2); expect(recordedPosition?.y, Y_SCROLL * 2); }); }); group('NavigationDelegate', () { const String blankPage = '<!DOCTYPE html><head></head><body></body></html>'; final String blankPageEncoded = 'data:text/html;charset=utf-8;base64,' '${base64Encode(const Utf8Encoder().convert(blankPage))}'; testWidgets('can allow requests', (WidgetTester tester) async { Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited( delegate.setOnNavigationRequest((NavigationRequest navigationRequest) { return (navigationRequest.url.contains('youtube.com')) ? NavigationDecision.prevent : NavigationDecision.navigate; }), ); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams(uri: Uri.parse(blankPageEncoded)), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; // Wait for initial page load. pageLoaded = Completer<void>(); await controller.runJavaScript('location.href = "$secondaryUrl"'); await pageLoaded.future; final String? currentUrl = await controller.currentUrl(); expect(currentUrl, secondaryUrl); }); testWidgets('onWebResourceError', (WidgetTester tester) async { final Completer<WebResourceError> errorCompleter = Completer<WebResourceError>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited( delegate.setOnWebResourceError((WebResourceError error) { errorCompleter.complete(error); }), ); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams(uri: Uri.parse('https://www.notawebsite..com')), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); final WebResourceError error = await errorCompleter.future; expect(error, isNotNull); expect( error.url?.startsWith('https://www.notawebsite..com'), isTrue, ); expect((error as WebKitWebResourceError).domain, isNotNull); }); testWidgets('onWebResourceError is not called with valid url', (WidgetTester tester) async { final Completer<WebResourceError> errorCompleter = Completer<WebResourceError>(); final Completer<void> pageFinishCompleter = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited( delegate.setOnPageFinished((_) => pageFinishCompleter.complete()), ); unawaited( delegate.setOnWebResourceError((WebResourceError error) { errorCompleter.complete(error); }), ); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,PCFET0NUWVBFIGh0bWw+', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); expect(errorCompleter.future, doesNotComplete); await pageFinishCompleter.future; }); testWidgets( 'onWebResourceError only called for main frame', (WidgetTester tester) async { const String iframeTest = ''' <!DOCTYPE html> <html> <head> <title>WebResourceError test</title> </head> <body> <iframe src="https://notawebsite..com"></iframe> </body> </html> '''; final String iframeTestBase64 = base64Encode(const Utf8Encoder().convert(iframeTest)); final Completer<WebResourceError> errorCompleter = Completer<WebResourceError>(); final Completer<void> pageFinishCompleter = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited( delegate.setOnPageFinished((_) => pageFinishCompleter.complete()), ); unawaited( delegate.setOnWebResourceError((WebResourceError error) { errorCompleter.complete(error); }), ); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,$iframeTestBase64', ), ), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); expect(errorCompleter.future, doesNotComplete); await pageFinishCompleter.future; }, ); testWidgets('onHttpError', (WidgetTester tester) async { final Completer<HttpResponseError> errorCompleter = Completer<HttpResponseError>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnHttpError((HttpResponseError error) { errorCompleter.complete(error); })); unawaited(controller.setPlatformNavigationDelegate(delegate)); unawaited(controller.loadRequest( LoadRequestParams(uri: Uri.parse('$prefixUrl/favicon.ico')), )); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); final HttpResponseError error = await errorCompleter.future; expect(error, isNotNull); expect(error.response?.statusCode, 404); }); testWidgets('onHttpError is not called when no HTTP error is received', (WidgetTester tester) async { const String testPage = ''' <!DOCTYPE html><html> </head> <body> </body> </html> '''; final Completer<HttpResponseError> errorCompleter = Completer<HttpResponseError>(); final Completer<void> pageFinishCompleter = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnHttpError((HttpResponseError error) { errorCompleter.complete(error); })); unawaited(delegate.setOnPageFinished( (_) => pageFinishCompleter.complete(), )); unawaited(controller.setPlatformNavigationDelegate(delegate)); unawaited(controller.loadHtmlString(testPage)); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); expect(errorCompleter.future, doesNotComplete); await pageFinishCompleter.future; }); testWidgets('can block requests', (WidgetTester tester) async { Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(delegate .setOnNavigationRequest((NavigationRequest navigationRequest) { return (navigationRequest.url.contains('youtube.com')) ? NavigationDecision.prevent : NavigationDecision.navigate; })); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller .loadRequest(LoadRequestParams(uri: Uri.parse(blankPageEncoded))); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; // Wait for initial page load. pageLoaded = Completer<void>(); await controller .runJavaScript('location.href = "https://www.youtube.com/"'); // There should never be any second page load, since our new URL is // blocked. Still wait for a potential page change for some time in order // to give the test a chance to fail. await pageLoaded.future .timeout(const Duration(milliseconds: 500), onTimeout: () => ''); final String? currentUrl = await controller.currentUrl(); expect(currentUrl, isNot(contains('youtube.com'))); }); testWidgets('supports asynchronous decisions', (WidgetTester tester) async { Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(delegate .setOnNavigationRequest((NavigationRequest navigationRequest) async { NavigationDecision decision = NavigationDecision.prevent; decision = await Future<NavigationDecision>.delayed( const Duration(milliseconds: 10), () => NavigationDecision.navigate); return decision; })); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller .loadRequest(LoadRequestParams(uri: Uri.parse(blankPageEncoded))); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; // Wait for initial page load. pageLoaded = Completer<void>(); await controller.runJavaScript('location.href = "$secondaryUrl"'); await pageLoaded.future; // Wait for second page to load. final String? currentUrl = await controller.currentUrl(); expect(currentUrl, secondaryUrl); }); testWidgets('can receive url changes', (WidgetTester tester) async { final Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller .loadRequest(LoadRequestParams(uri: Uri.parse(blankPageEncoded))); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; await delegate.setOnPageFinished((_) {}); final Completer<String> urlChangeCompleter = Completer<String>(); await delegate.setOnUrlChange((UrlChange change) { urlChangeCompleter.complete(change.url); }); await controller.runJavaScript('location.href = "$primaryUrl"'); await expectLater(urlChangeCompleter.future, completion(primaryUrl)); }); testWidgets('can receive updates to history state', (WidgetTester tester) async { final Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller .loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; await delegate.setOnPageFinished((_) {}); final Completer<String> urlChangeCompleter = Completer<String>(); await delegate.setOnUrlChange((UrlChange change) { urlChangeCompleter.complete(change.url); }); await controller.runJavaScript( 'window.history.pushState({}, "", "secondary.txt");', ); await expectLater(urlChangeCompleter.future, completion(secondaryUrl)); }); }); testWidgets('can receive HTTP basic auth requests', (WidgetTester tester) async { final Completer<void> authRequested = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); final PlatformNavigationDelegate navigationDelegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); await navigationDelegate.setOnHttpAuthRequest( (HttpAuthRequest request) => authRequested.complete()); await controller.setPlatformNavigationDelegate(navigationDelegate); // Clear cache so that the auth request is always received and we don't get // a cached response. await controller.clearCache(); await tester.pumpWidget( Builder( builder: (BuildContext context) { return PlatformWebViewWidget( WebKitWebViewWidgetCreationParams(controller: controller), ).build(context); }, ), ); await controller.loadRequest( LoadRequestParams(uri: Uri.parse(basicAuthUrl)), ); await expectLater(authRequested.future, completes); }); testWidgets('can reply to HTTP basic auth requests', (WidgetTester tester) async { final Completer<void> pageFinished = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); final PlatformNavigationDelegate navigationDelegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); await navigationDelegate.setOnPageFinished((_) => pageFinished.complete()); await navigationDelegate.setOnHttpAuthRequest( (HttpAuthRequest request) => request.onProceed( const WebViewCredential(user: 'user', password: 'password'), ), ); await controller.setPlatformNavigationDelegate(navigationDelegate); // Clear cache so that the auth request is always received and we don't get // a cached response. await controller.clearCache(); await tester.pumpWidget( Builder( builder: (BuildContext context) { return PlatformWebViewWidget( WebKitWebViewWidgetCreationParams(controller: controller), ).build(context); }, ), ); await controller.loadRequest( LoadRequestParams(uri: Uri.parse(basicAuthUrl)), ); await expectLater(pageFinished.future, completes); }); testWidgets('launches with gestureNavigationEnabled on iOS', (WidgetTester tester) async { final WebKitWebViewController controller = WebKitWebViewController( WebKitWebViewControllerCreationParams(), ); unawaited(controller.setAllowsBackForwardNavigationGestures(true)); await controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); final String? currentUrl = await controller.currentUrl(); expect(currentUrl, primaryUrl); }); testWidgets('target _blank opens in same window', (WidgetTester tester) async { final Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( WebKitWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller.runJavaScript('window.open("$primaryUrl", "_blank")'); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await pageLoaded.future; final String? currentUrl = await controller.currentUrl(); expect(currentUrl, primaryUrl); }); testWidgets( 'can open new window and go back', (WidgetTester tester) async { Completer<void> pageLoaded = Completer<void>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); final PlatformNavigationDelegate delegate = PlatformNavigationDelegate( const PlatformNavigationDelegateCreationParams(), ); unawaited(delegate.setOnPageFinished((_) => pageLoaded.complete())); unawaited(controller.setPlatformNavigationDelegate(delegate)); await controller .loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); expect(controller.currentUrl(), completion(primaryUrl)); await pageLoaded.future; pageLoaded = Completer<void>(); await controller.runJavaScript('window.open("$secondaryUrl")'); await pageLoaded.future; pageLoaded = Completer<void>(); expect(controller.currentUrl(), completion(secondaryUrl)); expect(controller.canGoBack(), completion(true)); await controller.goBack(); await pageLoaded.future; await expectLater(controller.currentUrl(), completion(primaryUrl)); }, ); testWidgets('can receive JavaScript alert dialogs', (WidgetTester tester) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); final Completer<String> alertMessage = Completer<String>(); unawaited(controller.setOnJavaScriptAlertDialog( (JavaScriptAlertDialogRequest request) async { alertMessage.complete(request.message); }, )); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await controller.runJavaScript('alert("alert message")'); await expectLater(alertMessage.future, completion('alert message')); }); testWidgets('can receive JavaScript confirm dialogs', (WidgetTester tester) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); final Completer<String> confirmMessage = Completer<String>(); unawaited(controller.setOnJavaScriptConfirmDialog( (JavaScriptConfirmDialogRequest request) async { confirmMessage.complete(request.message); return true; }, )); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await controller.runJavaScript('confirm("confirm message")'); await expectLater(confirmMessage.future, completion('confirm message')); }); testWidgets('can receive JavaScript prompt dialogs', (WidgetTester tester) async { final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setOnJavaScriptTextInputDialog( (JavaScriptTextInputDialogRequest request) async { return 'return message'; }, )); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); unawaited( controller.loadRequest(LoadRequestParams(uri: Uri.parse(primaryUrl))), ); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); final Object promptResponse = await controller.runJavaScriptReturningResult( 'prompt("input message", "default text")', ); expect(promptResponse, 'return message'); }); group('Logging', () { testWidgets('can receive console log messages', (WidgetTester tester) async { const String testPage = ''' <!DOCTYPE html> <html> <head> <title>WebResourceError test</title> </head> <body onload="console.debug('Debug message')"> <p>Test page</p> </body> </html> '''; final Completer<String> debugMessageReceived = Completer<String>(); final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ); unawaited(controller.setJavaScriptMode(JavaScriptMode.unrestricted)); await controller .setOnConsoleMessage((JavaScriptConsoleMessage consoleMessage) { debugMessageReceived .complete('${consoleMessage.level.name}:${consoleMessage.message}'); }); await controller.loadHtmlString(testPage); await tester.pumpWidget(Builder( builder: (BuildContext context) { return PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context); }, )); await expectLater( debugMessageReceived.future, completion('debug:Debug message')); }); }); } class ResizableWebView extends StatefulWidget { const ResizableWebView({ super.key, required this.onResize, required this.onPageFinished, }); final VoidCallback onResize; final VoidCallback onPageFinished; @override State<StatefulWidget> createState() => ResizableWebViewState(); } class ResizableWebViewState extends State<ResizableWebView> { late final PlatformWebViewController controller = PlatformWebViewController( const PlatformWebViewControllerCreationParams(), ) ..setJavaScriptMode(JavaScriptMode.unrestricted) ..setPlatformNavigationDelegate( WebKitNavigationDelegate( const WebKitNavigationDelegateCreationParams(), )..setOnPageFinished((_) => widget.onPageFinished()), ) ..addJavaScriptChannel( JavaScriptChannelParams( name: 'Resize', onMessageReceived: (_) { widget.onResize(); }, ), ) ..loadRequest( LoadRequestParams( uri: Uri.parse( 'data:text/html;charset=utf-8;base64,${base64Encode(const Utf8Encoder().convert(resizePage))}', ), ), ); double webViewWidth = 200; double webViewHeight = 200; static const String resizePage = ''' <!DOCTYPE html><html> <head><title>Resize test</title> <script type="text/javascript"> function onResize() { Resize.postMessage("resize"); } function onLoad() { window.onresize = onResize; } </script> </head> <body onload="onLoad();" bgColor="blue"> </body> </html> '''; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Column( children: <Widget>[ SizedBox( width: webViewWidth, height: webViewHeight, child: PlatformWebViewWidget( PlatformWebViewWidgetCreationParams(controller: controller), ).build(context), ), TextButton( key: const Key('resizeButton'), onPressed: () { setState(() { webViewWidth += 100.0; webViewHeight += 100.0; }); }, child: const Text('ResizeButton'), ), ], ), ); } } class CopyableObjectWithCallback with Copyable { CopyableObjectWithCallback(this.callback); final VoidCallback callback; @override CopyableObjectWithCallback copy() { return CopyableObjectWithCallback(callback); } } class ClassWithCallbackClass { ClassWithCallbackClass() { callbackClass = CopyableObjectWithCallback( withWeakReferenceTo( this, (WeakReference<ClassWithCallbackClass> weakReference) { return () { // Weak reference to `this` in callback. // ignore: unnecessary_statements weakReference; }; }, ), ); } late final CopyableObjectWithCallback callbackClass; }
packages/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/example/integration_test/webview_flutter_test.dart", "repo_id": "packages", "token_count": 21998 }
1,142
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFNavigationDelegateHostApi.h" #import "FWFDataConverters.h" #import "FWFURLAuthenticationChallengeHostApi.h" #import "FWFWebViewConfigurationHostApi.h" @interface FWFNavigationDelegateFlutterApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFNavigationDelegateFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self initWithBinaryMessenger:binaryMessenger]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (long)identifierForDelegate:(FWFNavigationDelegate *)instance { return [self.instanceManager identifierWithStrongReferenceForInstance:instance]; } - (void)didFinishNavigationForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView URL:(NSString *)URL completion:(void (^)(FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; [self didFinishNavigationForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier URL:URL completion:completion]; } - (void)didStartProvisionalNavigationForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView URL:(NSString *)URL completion:(void (^)(FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; [self didStartProvisionalNavigationForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier URL:URL completion:completion]; } - (void) decidePolicyForNavigationActionForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView navigationAction:(WKNavigationAction *)navigationAction completion: (void (^)(FWFWKNavigationActionPolicyEnumData *_Nullable, FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; FWFWKNavigationActionData *navigationActionData = FWFWKNavigationActionDataFromNativeWKNavigationAction(navigationAction); [self decidePolicyForNavigationActionForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier navigationAction:navigationActionData completion:completion]; } - (void)decidePolicyForNavigationResponseForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView navigationResponse:(WKNavigationResponse *)navigationResponse completion: (void (^)(FWFWKNavigationResponsePolicyEnumBox *, FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; FWFWKNavigationResponseData *navigationResponseData = FWFWKNavigationResponseDataFromNativeNavigationResponse(navigationResponse); [self decidePolicyForNavigationResponseForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier navigationResponse:navigationResponseData completion:completion]; } - (void)didFailNavigationForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView error:(NSError *)error completion:(void (^)(FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; [self didFailNavigationForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier error:FWFNSErrorDataFromNativeNSError(error) completion:completion]; } - (void)didFailProvisionalNavigationForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView error:(NSError *)error completion:(void (^)(FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; [self didFailProvisionalNavigationForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier error:FWFNSErrorDataFromNativeNSError(error) completion:completion]; } - (void)webViewWebContentProcessDidTerminateForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView completion: (void (^)(FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; [self webViewWebContentProcessDidTerminateForDelegateWithIdentifier: [self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier completion:completion]; } - (void) didReceiveAuthenticationChallengeForDelegate:(FWFNavigationDelegate *)instance webView:(WKWebView *)webView challenge:(NSURLAuthenticationChallenge *)challenge completion: (void (^)(FWFAuthenticationChallengeResponse *_Nullable, FlutterError *_Nullable))completion { NSInteger webViewIdentifier = [self.instanceManager identifierWithStrongReferenceForInstance:webView]; FWFURLAuthenticationChallengeFlutterApiImpl *challengeApi = [[FWFURLAuthenticationChallengeFlutterApiImpl alloc] initWithBinaryMessenger:self.binaryMessenger instanceManager:self.instanceManager]; [challengeApi createWithInstance:challenge protectionSpace:challenge.protectionSpace completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; [self didReceiveAuthenticationChallengeForDelegateWithIdentifier:[self identifierForDelegate:instance] webViewIdentifier:webViewIdentifier challengeIdentifier: [self.instanceManager identifierWithStrongReferenceForInstance: challenge] completion:completion]; } @end @implementation FWFNavigationDelegate - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [super initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; if (self) { _navigationDelegateAPI = [[FWFNavigationDelegateFlutterApiImpl alloc] initWithBinaryMessenger:binaryMessenger instanceManager:instanceManager]; } return self; } - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { [self.navigationDelegateAPI didFinishNavigationForDelegate:self webView:webView URL:webView.URL.absoluteString completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { [self.navigationDelegateAPI didStartProvisionalNavigationForDelegate:self webView:webView URL:webView.URL.absoluteString completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { [self.navigationDelegateAPI decidePolicyForNavigationActionForDelegate:self webView:webView navigationAction:navigationAction completion:^(FWFWKNavigationActionPolicyEnumData *policy, FlutterError *error) { NSAssert(!error, @"%@", error); if (!error) { decisionHandler( FWFNativeWKNavigationActionPolicyFromEnumData( policy)); } else { decisionHandler(WKNavigationActionPolicyCancel); } }]; } - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { [self.navigationDelegateAPI decidePolicyForNavigationResponseForDelegate:self webView:webView navigationResponse:navigationResponse completion:^(FWFWKNavigationResponsePolicyEnumBox *policy, FlutterError *error) { NSAssert(!error, @"%@", error); if (!error) { decisionHandler( FWFNativeWKNavigationResponsePolicyFromEnum( policy.value)); } else { decisionHandler(WKNavigationResponsePolicyCancel); } }]; } - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error { [self.navigationDelegateAPI didFailNavigationForDelegate:self webView:webView error:error completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { [self.navigationDelegateAPI didFailProvisionalNavigationForDelegate:self webView:webView error:error completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView { [self.navigationDelegateAPI webViewWebContentProcessDidTerminateForDelegate:self webView:webView completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; } - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler { [self.navigationDelegateAPI didReceiveAuthenticationChallengeForDelegate:self webView:webView challenge:challenge completion:^(FWFAuthenticationChallengeResponse *response, FlutterError *error) { NSAssert(!error, @"%@", error); if (!error) { NSURLSessionAuthChallengeDisposition disposition = FWFNativeNSURLSessionAuthChallengeDispositionFromFWFNSUrlSessionAuthChallengeDisposition( response.disposition); NSURLCredential *credential = response.credentialIdentifier ? (NSURLCredential *)[self.navigationDelegateAPI .instanceManager instanceForIdentifier: response.credentialIdentifier .longValue] : nil; completionHandler(disposition, credential); } else { completionHandler( NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); } }]; } @end @interface FWFNavigationDelegateHostApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFNavigationDelegateHostApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; } return self; } - (FWFNavigationDelegate *)navigationDelegateForIdentifier:(NSInteger)identifier { return (FWFNavigationDelegate *)[self.instanceManager instanceForIdentifier:identifier]; } - (void)createWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { FWFNavigationDelegate *navigationDelegate = [[FWFNavigationDelegate alloc] initWithBinaryMessenger:self.binaryMessenger instanceManager:self.instanceManager]; [self.instanceManager addDartCreatedInstance:navigationDelegate withIdentifier:identifier]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFNavigationDelegateHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFNavigationDelegateHostApi.m", "repo_id": "packages", "token_count": 9997 }
1,143
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFURLAuthenticationChallengeHostApi.h" #import "FWFURLProtectionSpaceHostApi.h" @interface FWFURLAuthenticationChallengeFlutterApiImpl () // BinaryMessenger must be weak to prevent a circular reference with the host API it // references. @property(nonatomic, weak) id<FlutterBinaryMessenger> binaryMessenger; // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFURLAuthenticationChallengeFlutterApiImpl - (instancetype)initWithBinaryMessenger:(id<FlutterBinaryMessenger>)binaryMessenger instanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _binaryMessenger = binaryMessenger; _instanceManager = instanceManager; _api = [[FWFNSUrlAuthenticationChallengeFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; } return self; } - (void)createWithInstance:(NSURLAuthenticationChallenge *)instance protectionSpace:(NSURLProtectionSpace *)protectionSpace completion:(void (^)(FlutterError *_Nullable))completion { if ([self.instanceManager containsInstance:instance]) { return; } FWFURLProtectionSpaceFlutterApiImpl *protectionSpaceApi = [[FWFURLProtectionSpaceFlutterApiImpl alloc] initWithBinaryMessenger:self.binaryMessenger instanceManager:self.instanceManager]; [protectionSpaceApi createWithInstance:protectionSpace host:protectionSpace.host realm:protectionSpace.realm authenticationMethod:protectionSpace.authenticationMethod completion:^(FlutterError *error) { NSAssert(!error, @"%@", error); }]; [self.api createWithIdentifier:[self.instanceManager addHostCreatedInstance:instance] protectionSpaceIdentifier:[self.instanceManager identifierWithStrongReferenceForInstance:protectionSpace] completion:completion]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLAuthenticationChallengeHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFURLAuthenticationChallengeHostApi.m", "repo_id": "packages", "token_count": 928 }
1,144
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "FWFWebsiteDataStoreHostApi.h" #import "FWFDataConverters.h" #import "FWFWebViewConfigurationHostApi.h" @interface FWFWebsiteDataStoreHostApiImpl () // InstanceManager must be weak to prevent a circular reference with the object it stores. @property(nonatomic, weak) FWFInstanceManager *instanceManager; @end @implementation FWFWebsiteDataStoreHostApiImpl - (instancetype)initWithInstanceManager:(FWFInstanceManager *)instanceManager { self = [self init]; if (self) { _instanceManager = instanceManager; } return self; } - (WKWebsiteDataStore *)websiteDataStoreForIdentifier:(NSInteger)identifier { return (WKWebsiteDataStore *)[self.instanceManager instanceForIdentifier:identifier]; } - (void)createFromWebViewConfigurationWithIdentifier:(NSInteger)identifier configurationIdentifier:(NSInteger)configurationIdentifier error:(FlutterError *_Nullable *_Nonnull)error { WKWebViewConfiguration *configuration = (WKWebViewConfiguration *)[self.instanceManager instanceForIdentifier:configurationIdentifier]; [self.instanceManager addDartCreatedInstance:configuration.websiteDataStore withIdentifier:identifier]; } - (void)createDefaultDataStoreWithIdentifier:(NSInteger)identifier error:(FlutterError *_Nullable __autoreleasing *_Nonnull) error { [self.instanceManager addDartCreatedInstance:[WKWebsiteDataStore defaultDataStore] withIdentifier:identifier]; } - (void)removeDataFromDataStoreWithIdentifier:(NSInteger)identifier ofTypes:(nonnull NSArray<FWFWKWebsiteDataTypeEnumData *> *) dataTypes modifiedSince:(double)modificationTimeInSecondsSinceEpoch completion: (nonnull void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { NSMutableSet<NSString *> *stringDataTypes = [NSMutableSet set]; for (FWFWKWebsiteDataTypeEnumData *type in dataTypes) { [stringDataTypes addObject:FWFNativeWKWebsiteDataTypeFromEnumData(type)]; } WKWebsiteDataStore *dataStore = [self websiteDataStoreForIdentifier:identifier]; [dataStore fetchDataRecordsOfTypes:stringDataTypes completionHandler:^(NSArray<WKWebsiteDataRecord *> *records) { [dataStore removeDataOfTypes:stringDataTypes modifiedSince:[NSDate dateWithTimeIntervalSince1970: modificationTimeInSecondsSinceEpoch] completionHandler:^{ completion([NSNumber numberWithBool:(records.count > 0)], nil); }]; }]; } @end
packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebsiteDataStoreHostApi.m/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/ios/Classes/FWFWebsiteDataStoreHostApi.m", "repo_id": "packages", "token_count": 1456 }
1,145
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import '../common/instance_manager.dart'; import '../common/web_kit.g.dart'; import '../foundation/foundation.dart'; import '../ui_kit/ui_kit.dart'; import '../ui_kit/ui_kit_api_impls.dart'; import 'web_kit.dart'; export '../common/web_kit.g.dart' show WKMediaCaptureType, WKNavigationType, WKPermissionDecision; Iterable<WKWebsiteDataTypeEnumData> _toWKWebsiteDataTypeEnumData( Iterable<WKWebsiteDataType> types) { return types.map<WKWebsiteDataTypeEnumData>((WKWebsiteDataType type) { late final WKWebsiteDataTypeEnum value; switch (type) { case WKWebsiteDataType.cookies: value = WKWebsiteDataTypeEnum.cookies; case WKWebsiteDataType.memoryCache: value = WKWebsiteDataTypeEnum.memoryCache; case WKWebsiteDataType.diskCache: value = WKWebsiteDataTypeEnum.diskCache; case WKWebsiteDataType.offlineWebApplicationCache: value = WKWebsiteDataTypeEnum.offlineWebApplicationCache; case WKWebsiteDataType.localStorage: value = WKWebsiteDataTypeEnum.localStorage; case WKWebsiteDataType.sessionStorage: value = WKWebsiteDataTypeEnum.sessionStorage; case WKWebsiteDataType.webSQLDatabases: value = WKWebsiteDataTypeEnum.webSQLDatabases; case WKWebsiteDataType.indexedDBDatabases: value = WKWebsiteDataTypeEnum.indexedDBDatabases; } return WKWebsiteDataTypeEnumData(value: value); }); } extension _NSHttpCookieConverter on NSHttpCookie { NSHttpCookieData toNSHttpCookieData() { final Iterable<NSHttpCookiePropertyKey> keys = properties.keys; return NSHttpCookieData( propertyKeys: keys.map<NSHttpCookiePropertyKeyEnumData>( (NSHttpCookiePropertyKey key) { return key.toNSHttpCookiePropertyKeyEnumData(); }, ).toList(), propertyValues: keys .map<Object>((NSHttpCookiePropertyKey key) => properties[key]!) .toList(), ); } } extension _WKNavigationActionPolicyConverter on WKNavigationActionPolicy { WKNavigationActionPolicyEnumData toWKNavigationActionPolicyEnumData() { return WKNavigationActionPolicyEnumData( value: WKNavigationActionPolicyEnum.values.firstWhere( (WKNavigationActionPolicyEnum element) => element.name == name, ), ); } } extension _WKNavigationResponsePolicyConverter on WKNavigationResponsePolicy { WKNavigationResponsePolicyEnum toWKNavigationResponsePolicyEnumData() { return WKNavigationResponsePolicyEnum.values.firstWhere( (WKNavigationResponsePolicyEnum element) => element.name == name, ); } } extension _NSHttpCookiePropertyKeyConverter on NSHttpCookiePropertyKey { NSHttpCookiePropertyKeyEnumData toNSHttpCookiePropertyKeyEnumData() { late final NSHttpCookiePropertyKeyEnum value; switch (this) { case NSHttpCookiePropertyKey.comment: value = NSHttpCookiePropertyKeyEnum.comment; case NSHttpCookiePropertyKey.commentUrl: value = NSHttpCookiePropertyKeyEnum.commentUrl; case NSHttpCookiePropertyKey.discard: value = NSHttpCookiePropertyKeyEnum.discard; case NSHttpCookiePropertyKey.domain: value = NSHttpCookiePropertyKeyEnum.domain; case NSHttpCookiePropertyKey.expires: value = NSHttpCookiePropertyKeyEnum.expires; case NSHttpCookiePropertyKey.maximumAge: value = NSHttpCookiePropertyKeyEnum.maximumAge; case NSHttpCookiePropertyKey.name: value = NSHttpCookiePropertyKeyEnum.name; case NSHttpCookiePropertyKey.originUrl: value = NSHttpCookiePropertyKeyEnum.originUrl; case NSHttpCookiePropertyKey.path: value = NSHttpCookiePropertyKeyEnum.path; case NSHttpCookiePropertyKey.port: value = NSHttpCookiePropertyKeyEnum.port; case NSHttpCookiePropertyKey.sameSitePolicy: value = NSHttpCookiePropertyKeyEnum.sameSitePolicy; case NSHttpCookiePropertyKey.secure: value = NSHttpCookiePropertyKeyEnum.secure; case NSHttpCookiePropertyKey.value: value = NSHttpCookiePropertyKeyEnum.value; case NSHttpCookiePropertyKey.version: value = NSHttpCookiePropertyKeyEnum.version; } return NSHttpCookiePropertyKeyEnumData(value: value); } } extension _WKUserScriptInjectionTimeConverter on WKUserScriptInjectionTime { WKUserScriptInjectionTimeEnumData toWKUserScriptInjectionTimeEnumData() { late final WKUserScriptInjectionTimeEnum value; switch (this) { case WKUserScriptInjectionTime.atDocumentStart: value = WKUserScriptInjectionTimeEnum.atDocumentStart; case WKUserScriptInjectionTime.atDocumentEnd: value = WKUserScriptInjectionTimeEnum.atDocumentEnd; } return WKUserScriptInjectionTimeEnumData(value: value); } } Iterable<WKAudiovisualMediaTypeEnumData> _toWKAudiovisualMediaTypeEnumData( Iterable<WKAudiovisualMediaType> types, ) { return types .map<WKAudiovisualMediaTypeEnumData>((WKAudiovisualMediaType type) { late final WKAudiovisualMediaTypeEnum value; switch (type) { case WKAudiovisualMediaType.none: value = WKAudiovisualMediaTypeEnum.none; case WKAudiovisualMediaType.audio: value = WKAudiovisualMediaTypeEnum.audio; case WKAudiovisualMediaType.video: value = WKAudiovisualMediaTypeEnum.video; case WKAudiovisualMediaType.all: value = WKAudiovisualMediaTypeEnum.all; } return WKAudiovisualMediaTypeEnumData(value: value); }); } extension _NavigationActionDataConverter on WKNavigationActionData { WKNavigationAction toNavigationAction() { return WKNavigationAction( request: request.toNSUrlRequest(), targetFrame: targetFrame.toWKFrameInfo(), navigationType: navigationType, ); } } extension _NavigationResponseDataConverter on WKNavigationResponseData { WKNavigationResponse toNavigationResponse() { return WKNavigationResponse( response: response.toNSUrlResponse(), forMainFrame: forMainFrame); } } extension _WKFrameInfoDataConverter on WKFrameInfoData { WKFrameInfo toWKFrameInfo() { return WKFrameInfo( isMainFrame: isMainFrame, request: request.toNSUrlRequest(), ); } } extension _NSUrlRequestDataConverter on NSUrlRequestData { NSUrlRequest toNSUrlRequest() { return NSUrlRequest( url: url, httpBody: httpBody, httpMethod: httpMethod, allHttpHeaderFields: allHttpHeaderFields.cast(), ); } } extension _NSUrlResponseDataConverter on NSHttpUrlResponseData { NSHttpUrlResponse toNSUrlResponse() { return NSHttpUrlResponse(statusCode: statusCode); } } extension _WKNSErrorDataConverter on NSErrorData { NSError toNSError() { return NSError( domain: domain, code: code, userInfo: userInfo?.cast<String, Object?>() ?? <String, Object?>{}, ); } } extension _WKScriptMessageDataConverter on WKScriptMessageData { WKScriptMessage toWKScriptMessage() { return WKScriptMessage(name: name, body: body); } } extension _WKUserScriptConverter on WKUserScript { WKUserScriptData toWKUserScriptData() { return WKUserScriptData( source: source, injectionTime: injectionTime.toWKUserScriptInjectionTimeEnumData(), isMainFrameOnly: isMainFrameOnly, ); } } extension _NSUrlRequestConverter on NSUrlRequest { NSUrlRequestData toNSUrlRequestData() { return NSUrlRequestData( url: url, httpMethod: httpMethod, httpBody: httpBody, allHttpHeaderFields: allHttpHeaderFields, ); } } extension _WKSecurityOriginConverter on WKSecurityOriginData { WKSecurityOrigin toWKSecurityOrigin() { return WKSecurityOrigin(host: host, port: port, protocol: protocol); } } /// Handles initialization of Flutter APIs for WebKit. class WebKitFlutterApis { /// Constructs a [WebKitFlutterApis]. @visibleForTesting WebKitFlutterApis({ BinaryMessenger? binaryMessenger, InstanceManager? instanceManager, }) : _binaryMessenger = binaryMessenger, navigationDelegate = WKNavigationDelegateFlutterApiImpl( instanceManager: instanceManager, ), scriptMessageHandler = WKScriptMessageHandlerFlutterApiImpl( instanceManager: instanceManager, ), uiDelegate = WKUIDelegateFlutterApiImpl( instanceManager: instanceManager, ), webViewConfiguration = WKWebViewConfigurationFlutterApiImpl( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), uiScrollViewDelegate = UIScrollViewDelegateFlutterApiImpl( instanceManager: instanceManager, ); static WebKitFlutterApis _instance = WebKitFlutterApis(); /// Sets the global instance containing the Flutter Apis for the WebKit library. @visibleForTesting static set instance(WebKitFlutterApis instance) { _instance = instance; } /// Global instance containing the Flutter Apis for the WebKit library. static WebKitFlutterApis get instance { return _instance; } final BinaryMessenger? _binaryMessenger; bool _hasBeenSetUp = false; /// Flutter Api for [WKNavigationDelegate]. @visibleForTesting final WKNavigationDelegateFlutterApiImpl navigationDelegate; /// Flutter Api for [WKScriptMessageHandler]. @visibleForTesting final WKScriptMessageHandlerFlutterApiImpl scriptMessageHandler; /// Flutter Api for [WKUIDelegate]. @visibleForTesting final WKUIDelegateFlutterApiImpl uiDelegate; /// Flutter Api for [WKWebViewConfiguration]. @visibleForTesting final WKWebViewConfigurationFlutterApiImpl webViewConfiguration; /// Flutter Api for [UIScrollViewDelegate]. @visibleForTesting final UIScrollViewDelegateFlutterApiImpl uiScrollViewDelegate; /// Ensures all the Flutter APIs have been set up to receive calls from native code. void ensureSetUp() { if (!_hasBeenSetUp) { WKNavigationDelegateFlutterApi.setup( navigationDelegate, binaryMessenger: _binaryMessenger, ); WKScriptMessageHandlerFlutterApi.setup( scriptMessageHandler, binaryMessenger: _binaryMessenger, ); WKUIDelegateFlutterApi.setup( uiDelegate, binaryMessenger: _binaryMessenger, ); WKWebViewConfigurationFlutterApi.setup( webViewConfiguration, binaryMessenger: _binaryMessenger, ); UIScrollViewDelegateFlutterApi.setup(uiScrollViewDelegate, binaryMessenger: _binaryMessenger); _hasBeenSetUp = true; } } } /// Host api implementation for [WKWebSiteDataStore]. class WKWebsiteDataStoreHostApiImpl extends WKWebsiteDataStoreHostApi { /// Constructs a [WebsiteDataStoreHostApiImpl]. WKWebsiteDataStoreHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebViewConfiguration] with the ids of the provided object instances. Future<void> createFromWebViewConfigurationForInstances( WKWebsiteDataStore instance, WKWebViewConfiguration configuration, ) { return createFromWebViewConfiguration( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [createDefaultDataStore] with the ids of the provided object instances. Future<void> createDefaultDataStoreForInstances( WKWebsiteDataStore instance, ) { return createDefaultDataStore( instanceManager.addDartCreatedInstance(instance), ); } /// Calls [removeDataOfTypes] with the ids of the provided object instances. Future<bool> removeDataOfTypesForInstances( WKWebsiteDataStore instance, Set<WKWebsiteDataType> dataTypes, { required double secondsModifiedSinceEpoch, }) { return removeDataOfTypes( instanceManager.getIdentifier(instance)!, _toWKWebsiteDataTypeEnumData(dataTypes).toList(), secondsModifiedSinceEpoch, ); } } /// Host api implementation for [WKScriptMessageHandler]. class WKScriptMessageHandlerHostApiImpl extends WKScriptMessageHandlerHostApi { /// Constructs a [WKScriptMessageHandlerHostApiImpl]. WKScriptMessageHandlerHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKScriptMessageHandler instance) { return create(instanceManager.addDartCreatedInstance(instance)); } } /// Flutter api implementation for [WKScriptMessageHandler]. class WKScriptMessageHandlerFlutterApiImpl extends WKScriptMessageHandlerFlutterApi { /// Constructs a [WKScriptMessageHandlerFlutterApiImpl]. WKScriptMessageHandlerFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; WKScriptMessageHandler _getHandler(int identifier) { return instanceManager.getInstanceWithWeakReference(identifier)!; } @override void didReceiveScriptMessage( int identifier, int userContentControllerIdentifier, WKScriptMessageData message, ) { _getHandler(identifier).didReceiveScriptMessage( instanceManager.getInstanceWithWeakReference( userContentControllerIdentifier, )! as WKUserContentController, message.toWKScriptMessage(), ); } } /// Host api implementation for [WKPreferences]. class WKPreferencesHostApiImpl extends WKPreferencesHostApi { /// Constructs a [WKPreferencesHostApiImpl]. WKPreferencesHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebViewConfiguration] with the ids of the provided object instances. Future<void> createFromWebViewConfigurationForInstances( WKPreferences instance, WKWebViewConfiguration configuration, ) { return createFromWebViewConfiguration( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [setJavaScriptEnabled] with the ids of the provided object instances. Future<void> setJavaScriptEnabledForInstances( WKPreferences instance, bool enabled, ) { return setJavaScriptEnabled( instanceManager.getIdentifier(instance)!, enabled, ); } } /// Host api implementation for [WKHttpCookieStore]. class WKHttpCookieStoreHostApiImpl extends WKHttpCookieStoreHostApi { /// Constructs a [WKHttpCookieStoreHostApiImpl]. WKHttpCookieStoreHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebsiteDataStore] with the ids of the provided object instances. Future<void> createFromWebsiteDataStoreForInstances( WKHttpCookieStore instance, WKWebsiteDataStore dataStore, ) { return createFromWebsiteDataStore( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(dataStore)!, ); } /// Calls [setCookie] with the ids of the provided object instances. Future<void> setCookieForInstances( WKHttpCookieStore instance, NSHttpCookie cookie, ) { return setCookie( instanceManager.getIdentifier(instance)!, cookie.toNSHttpCookieData(), ); } } /// Host api implementation for [WKUserContentController]. class WKUserContentControllerHostApiImpl extends WKUserContentControllerHostApi { /// Constructs a [WKUserContentControllerHostApiImpl]. WKUserContentControllerHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [createFromWebViewConfiguration] with the ids of the provided object instances. Future<void> createFromWebViewConfigurationForInstances( WKUserContentController instance, WKWebViewConfiguration configuration, ) { return createFromWebViewConfiguration( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [addScriptMessageHandler] with the ids of the provided object instances. Future<void> addScriptMessageHandlerForInstances( WKUserContentController instance, WKScriptMessageHandler handler, String name, ) { return addScriptMessageHandler( instanceManager.getIdentifier(instance)!, instanceManager.getIdentifier(handler)!, name, ); } /// Calls [removeScriptMessageHandler] with the ids of the provided object instances. Future<void> removeScriptMessageHandlerForInstances( WKUserContentController instance, String name, ) { return removeScriptMessageHandler( instanceManager.getIdentifier(instance)!, name, ); } /// Calls [removeAllScriptMessageHandlers] with the ids of the provided object instances. Future<void> removeAllScriptMessageHandlersForInstances( WKUserContentController instance, ) { return removeAllScriptMessageHandlers( instanceManager.getIdentifier(instance)!, ); } /// Calls [addUserScript] with the ids of the provided object instances. Future<void> addUserScriptForInstances( WKUserContentController instance, WKUserScript userScript, ) { return addUserScript( instanceManager.getIdentifier(instance)!, userScript.toWKUserScriptData(), ); } /// Calls [removeAllUserScripts] with the ids of the provided object instances. Future<void> removeAllUserScriptsForInstances( WKUserContentController instance, ) { return removeAllUserScripts(instanceManager.getIdentifier(instance)!); } } /// Host api implementation for [WKWebViewConfiguration]. class WKWebViewConfigurationHostApiImpl extends WKWebViewConfigurationHostApi { /// Constructs a [WKWebViewConfigurationHostApiImpl]. WKWebViewConfigurationHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKWebViewConfiguration instance) { return create(instanceManager.addDartCreatedInstance(instance)); } /// Calls [createFromWebView] with the ids of the provided object instances. Future<void> createFromWebViewForInstances( WKWebViewConfiguration instance, WKWebView webView, ) { return createFromWebView( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(webView)!, ); } /// Calls [setAllowsInlineMediaPlayback] with the ids of the provided object instances. Future<void> setAllowsInlineMediaPlaybackForInstances( WKWebViewConfiguration instance, bool allow, ) { return setAllowsInlineMediaPlayback( instanceManager.getIdentifier(instance)!, allow, ); } /// Calls [setLimitsNavigationsToAppBoundDomains] with the ids of the provided object instances. Future<void> setLimitsNavigationsToAppBoundDomainsForInstances( WKWebViewConfiguration instance, bool limit, ) { return setLimitsNavigationsToAppBoundDomains( instanceManager.getIdentifier(instance)!, limit, ); } /// Calls [setMediaTypesRequiringUserActionForPlayback] with the ids of the provided object instances. Future<void> setMediaTypesRequiringUserActionForPlaybackForInstances( WKWebViewConfiguration instance, Set<WKAudiovisualMediaType> types, ) { return setMediaTypesRequiringUserActionForPlayback( instanceManager.getIdentifier(instance)!, _toWKAudiovisualMediaTypeEnumData(types).toList(), ); } } /// Flutter api implementation for [WKWebViewConfiguration]. @immutable class WKWebViewConfigurationFlutterApiImpl extends WKWebViewConfigurationFlutterApi { /// Constructs a [WKWebViewConfigurationFlutterApiImpl]. WKWebViewConfigurationFlutterApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Receives binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; @override void create(int identifier) { instanceManager.addHostCreatedInstance( WKWebViewConfiguration.detached( binaryMessenger: binaryMessenger, instanceManager: instanceManager, ), identifier, ); } } /// Host api implementation for [WKUIDelegate]. class WKUIDelegateHostApiImpl extends WKUIDelegateHostApi { /// Constructs a [WKUIDelegateHostApiImpl]. WKUIDelegateHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKUIDelegate instance) async { return create(instanceManager.addDartCreatedInstance(instance)); } } /// Flutter api implementation for [WKUIDelegate]. class WKUIDelegateFlutterApiImpl extends WKUIDelegateFlutterApi { /// Constructs a [WKUIDelegateFlutterApiImpl]. WKUIDelegateFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; WKUIDelegate _getDelegate(int identifier) { return instanceManager.getInstanceWithWeakReference(identifier)!; } @override void onCreateWebView( int identifier, int webViewIdentifier, int configurationIdentifier, WKNavigationActionData navigationAction, ) { final void Function(WKWebView, WKWebViewConfiguration, WKNavigationAction)? function = _getDelegate(identifier).onCreateWebView; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, instanceManager.getInstanceWithWeakReference(configurationIdentifier)! as WKWebViewConfiguration, navigationAction.toNavigationAction(), ); } @override Future<WKPermissionDecisionData> requestMediaCapturePermission( int identifier, int webViewIdentifier, WKSecurityOriginData origin, WKFrameInfoData frame, WKMediaCaptureTypeData type, ) async { final WKUIDelegate instance = instanceManager.getInstanceWithWeakReference(identifier)!; late final WKPermissionDecision decision; if (instance.requestMediaCapturePermission != null) { decision = await instance.requestMediaCapturePermission!( instance, instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, origin.toWKSecurityOrigin(), frame.toWKFrameInfo(), type.value, ); } else { // The default response for iOS is to prompt. See // https://developer.apple.com/documentation/webkit/wkuidelegate/3763087-webview?language=objc decision = WKPermissionDecision.prompt; } return WKPermissionDecisionData(value: decision); } @override Future<void> runJavaScriptAlertPanel( int identifier, String message, WKFrameInfoData frame) { final WKUIDelegate instance = instanceManager.getInstanceWithWeakReference(identifier)!; return instance.runJavaScriptAlertDialog! .call(message, frame.toWKFrameInfo()); } @override Future<bool> runJavaScriptConfirmPanel( int identifier, String message, WKFrameInfoData frame) { final WKUIDelegate instance = instanceManager.getInstanceWithWeakReference(identifier)!; return instance.runJavaScriptConfirmDialog! .call(message, frame.toWKFrameInfo()); } @override Future<String> runJavaScriptTextInputPanel(int identifier, String prompt, String defaultText, WKFrameInfoData frame) { final WKUIDelegate instance = instanceManager.getInstanceWithWeakReference(identifier)!; return instance.runJavaScriptTextInputDialog! .call(prompt, defaultText, frame.toWKFrameInfo()); } } /// Host api implementation for [WKNavigationDelegate]. class WKNavigationDelegateHostApiImpl extends WKNavigationDelegateHostApi { /// Constructs a [WKNavigationDelegateHostApiImpl]. WKNavigationDelegateHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances(WKNavigationDelegate instance) async { return create(instanceManager.addDartCreatedInstance(instance)); } } /// Flutter api implementation for [WKNavigationDelegate]. class WKNavigationDelegateFlutterApiImpl extends WKNavigationDelegateFlutterApi { /// Constructs a [WKNavigationDelegateFlutterApiImpl]. WKNavigationDelegateFlutterApiImpl({InstanceManager? instanceManager}) : instanceManager = instanceManager ?? NSObject.globalInstanceManager; /// Maintains instances stored to communicate with native language objects. final InstanceManager instanceManager; WKNavigationDelegate _getDelegate(int identifier) { return instanceManager.getInstanceWithWeakReference(identifier)!; } @override void didFinishNavigation( int identifier, int webViewIdentifier, String? url, ) { final void Function(WKWebView, String?)? function = _getDelegate(identifier).didFinishNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, url, ); } @override Future<WKNavigationActionPolicyEnumData> decidePolicyForNavigationAction( int identifier, int webViewIdentifier, WKNavigationActionData navigationAction, ) async { final Future<WKNavigationActionPolicy> Function( WKWebView, WKNavigationAction navigationAction, )? function = _getDelegate(identifier).decidePolicyForNavigationAction; if (function == null) { return WKNavigationActionPolicyEnumData( value: WKNavigationActionPolicyEnum.allow, ); } final WKNavigationActionPolicy policy = await function( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, navigationAction.toNavigationAction(), ); return policy.toWKNavigationActionPolicyEnumData(); } @override void didFailNavigation( int identifier, int webViewIdentifier, NSErrorData error, ) { final void Function(WKWebView, NSError)? function = _getDelegate(identifier).didFailNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, error.toNSError(), ); } @override void didFailProvisionalNavigation( int identifier, int webViewIdentifier, NSErrorData error, ) { final void Function(WKWebView, NSError)? function = _getDelegate(identifier).didFailProvisionalNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, error.toNSError(), ); } @override void didStartProvisionalNavigation( int identifier, int webViewIdentifier, String? url, ) { final void Function(WKWebView, String?)? function = _getDelegate(identifier).didStartProvisionalNavigation; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, url, ); } @override Future<WKNavigationResponsePolicyEnum> decidePolicyForNavigationResponse( int identifier, int webViewIdentifier, WKNavigationResponseData navigationResponse, ) async { final Future<WKNavigationResponsePolicy> Function( WKWebView, WKNavigationResponse navigationResponse, )? function = _getDelegate(identifier).decidePolicyForNavigationResponse; if (function == null) { return WKNavigationResponsePolicyEnum.allow; } final WKNavigationResponsePolicy policy = await function( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, navigationResponse.toNavigationResponse(), ); return policy.toWKNavigationResponsePolicyEnumData(); } @override void webViewWebContentProcessDidTerminate( int identifier, int webViewIdentifier, ) { final void Function(WKWebView)? function = _getDelegate(identifier).webViewWebContentProcessDidTerminate; function?.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, ); } @override Future<AuthenticationChallengeResponse> didReceiveAuthenticationChallenge( int identifier, int webViewIdentifier, int challengeIdentifier, ) async { final void Function( WKWebView webView, NSUrlAuthenticationChallenge challenge, void Function( NSUrlSessionAuthChallengeDisposition disposition, NSUrlCredential? credential, ), )? function = _getDelegate(identifier).didReceiveAuthenticationChallenge; if (function == null) { return AuthenticationChallengeResponse( disposition: NSUrlSessionAuthChallengeDisposition.rejectProtectionSpace, ); } final Completer<AuthenticationChallengeResponse> responseCompleter = Completer<AuthenticationChallengeResponse>(); function.call( instanceManager.getInstanceWithWeakReference(webViewIdentifier)! as WKWebView, instanceManager.getInstanceWithWeakReference(challengeIdentifier)! as NSUrlAuthenticationChallenge, ( NSUrlSessionAuthChallengeDisposition disposition, NSUrlCredential? credential, ) { responseCompleter.complete( AuthenticationChallengeResponse( disposition: disposition, credentialIdentifier: credential != null ? instanceManager.getIdentifier(credential) : null, ), ); }, ); return responseCompleter.future; } } /// Host api implementation for [WKWebView]. class WKWebViewHostApiImpl extends WKWebViewHostApi { /// Constructs a [WKWebViewHostApiImpl]. WKWebViewHostApiImpl({ this.binaryMessenger, InstanceManager? instanceManager, }) : instanceManager = instanceManager ?? NSObject.globalInstanceManager, super(binaryMessenger: binaryMessenger); /// Sends binary data across the Flutter platform barrier. /// /// If it is null, the default BinaryMessenger will be used which routes to /// the host platform. final BinaryMessenger? binaryMessenger; /// Maintains instances stored to communicate with Objective-C objects. final InstanceManager instanceManager; /// Calls [create] with the ids of the provided object instances. Future<void> createForInstances( WKWebView instance, WKWebViewConfiguration configuration, ) { return create( instanceManager.addDartCreatedInstance(instance), instanceManager.getIdentifier(configuration)!, ); } /// Calls [loadRequest] with the ids of the provided object instances. Future<void> loadRequestForInstances( WKWebView webView, NSUrlRequest request, ) { return loadRequest( instanceManager.getIdentifier(webView)!, request.toNSUrlRequestData(), ); } /// Calls [loadHtmlString] with the ids of the provided object instances. Future<void> loadHtmlStringForInstances( WKWebView instance, String string, String? baseUrl, ) { return loadHtmlString( instanceManager.getIdentifier(instance)!, string, baseUrl, ); } /// Calls [loadFileUrl] with the ids of the provided object instances. Future<void> loadFileUrlForInstances( WKWebView instance, String url, String readAccessUrl, ) { return loadFileUrl( instanceManager.getIdentifier(instance)!, url, readAccessUrl, ); } /// Calls [loadFlutterAsset] with the ids of the provided object instances. Future<void> loadFlutterAssetForInstances(WKWebView instance, String key) { return loadFlutterAsset( instanceManager.getIdentifier(instance)!, key, ); } /// Calls [canGoBack] with the ids of the provided object instances. Future<bool> canGoBackForInstances(WKWebView instance) { return canGoBack(instanceManager.getIdentifier(instance)!); } /// Calls [canGoForward] with the ids of the provided object instances. Future<bool> canGoForwardForInstances(WKWebView instance) { return canGoForward(instanceManager.getIdentifier(instance)!); } /// Calls [goBack] with the ids of the provided object instances. Future<void> goBackForInstances(WKWebView instance) { return goBack(instanceManager.getIdentifier(instance)!); } /// Calls [goForward] with the ids of the provided object instances. Future<void> goForwardForInstances(WKWebView instance) { return goForward(instanceManager.getIdentifier(instance)!); } /// Calls [reload] with the ids of the provided object instances. Future<void> reloadForInstances(WKWebView instance) { return reload(instanceManager.getIdentifier(instance)!); } /// Calls [getUrl] with the ids of the provided object instances. Future<String?> getUrlForInstances(WKWebView instance) { return getUrl(instanceManager.getIdentifier(instance)!); } /// Calls [getTitle] with the ids of the provided object instances. Future<String?> getTitleForInstances(WKWebView instance) { return getTitle(instanceManager.getIdentifier(instance)!); } /// Calls [getEstimatedProgress] with the ids of the provided object instances. Future<double> getEstimatedProgressForInstances(WKWebView instance) { return getEstimatedProgress(instanceManager.getIdentifier(instance)!); } /// Calls [setAllowsBackForwardNavigationGestures] with the ids of the provided object instances. Future<void> setAllowsBackForwardNavigationGesturesForInstances( WKWebView instance, bool allow, ) { return setAllowsBackForwardNavigationGestures( instanceManager.getIdentifier(instance)!, allow, ); } /// Calls [setCustomUserAgent] with the ids of the provided object instances. Future<void> setCustomUserAgentForInstances( WKWebView instance, String? userAgent, ) { return setCustomUserAgent( instanceManager.getIdentifier(instance)!, userAgent, ); } /// Calls [evaluateJavaScript] with the ids of the provided object instances. Future<Object?> evaluateJavaScriptForInstances( WKWebView instance, String javaScriptString, ) async { try { final Object? result = await evaluateJavaScript( instanceManager.getIdentifier(instance)!, javaScriptString, ); return result; } on PlatformException catch (exception) { if (exception.details is! NSErrorData) { rethrow; } throw PlatformException( code: exception.code, message: exception.message, stacktrace: exception.stacktrace, details: (exception.details as NSErrorData).toNSError(), ); } } /// Calls [setInspectable] with the ids of the provided object instances. Future<void> setInspectableForInstances( WKWebView instance, bool inspectable, ) async { return setInspectable( instanceManager.getIdentifier(instance)!, inspectable, ); } /// Calls [getCustomUserAgent] with the ids of the provided object instances. Future<String?> getCustomUserAgentForInstances(WKWebView instance) { return getCustomUserAgent(instanceManager.getIdentifier(instance)!); } /// Calls [setNavigationDelegate] with the ids of the provided object instances. Future<void> setNavigationDelegateForInstances( WKWebView instance, WKNavigationDelegate? delegate, ) { return setNavigationDelegate( instanceManager.getIdentifier(instance)!, delegate != null ? instanceManager.getIdentifier(delegate)! : null, ); } /// Calls [setUIDelegate] with the ids of the provided object instances. Future<void> setUIDelegateForInstances( WKWebView instance, WKUIDelegate? delegate, ) { return setUIDelegate( instanceManager.getIdentifier(instance)!, delegate != null ? instanceManager.getIdentifier(delegate)! : null, ); } }
packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/web_kit/web_kit_api_impls.dart/0
{ "file_path": "packages/packages/webview_flutter/webview_flutter_wkwebview/lib/src/web_kit/web_kit_api_impls.dart", "repo_id": "packages", "token_count": 13525 }
1,146
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 1.0.4 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 1.0.3 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 1.0.2 * Adds example app to demonstrate how to use the package. ## 1.0.1 * Removes `process` dependency. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. ## 1.0.0 * Updates version to 1.0 to reflect the level of API stability. * Updates minimum SDK version to Flutter 3.0. ## 0.2.0+3 * Returns null instead of throwing exception from getUserDirectory when xdg-user-dir executable is missing. ## 0.2.0+2 * Fixes unit tests on Windows. * Fixes lint warnings. ## 0.2.0+1 * Marks the package as Linux-only using the new Dart `platforms` key. ## 0.2.0 * Migrated to null safety. ## 0.1.2 * Broaden dependencies to allow nullsafety version of process, meta, and path to be OK. ## 0.1.1 * Remove flutter, flutter_test from pubspec dependencies. ## 0.1.0 * Initial release includes all the features described in the README.md
packages/packages/xdg_directories/CHANGELOG.md/0
{ "file_path": "packages/packages/xdg_directories/CHANGELOG.md", "repo_id": "packages", "token_count": 383 }
1,147
name: xdg_directories_example description: Demonstrates how to use the xdg_directories package. publish_to: 'none' environment: sdk: ^3.1.0 flutter: ">=3.13.0" dependencies: flutter: sdk: flutter xdg_directories: # When depending on this package from a real application you should use: # xdg_directories: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ dev_dependencies: flutter_test: sdk: flutter integration_test: sdk: flutter test: any flutter: uses-material-design: true
packages/packages/xdg_directories/example/pubspec.yaml/0
{ "file_path": "packages/packages/xdg_directories/example/pubspec.yaml", "repo_id": "packages", "token_count": 259 }
1,148
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:file/file.dart'; import 'common/core.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/plugin_utils.dart'; import 'common/repository_package.dart'; const int _exitNoPlatformFlags = 2; const int _exitNoAvailableDevice = 3; // From https://docs.flutter.dev/testing/integration-tests#running-in-a-browser const int _chromeDriverPort = 4444; /// A command to run the integration tests for a package's example applications. class DriveExamplesCommand extends PackageLoopingCommand { /// Creates an instance of the drive command. DriveExamplesCommand( super.packagesDir, { super.processRunner, super.platform, }) { argParser.addFlag(platformAndroid, help: 'Runs the Android implementation of the examples', aliases: const <String>[platformAndroidAlias]); argParser.addFlag(platformIOS, help: 'Runs the iOS implementation of the examples'); argParser.addFlag(platformLinux, help: 'Runs the Linux implementation of the examples'); argParser.addFlag(platformMacOS, help: 'Runs the macOS implementation of the examples'); argParser.addFlag(platformWeb, help: 'Runs the web implementation of the examples'); argParser.addFlag(platformWindows, help: 'Runs the Windows implementation of the examples'); argParser.addOption( kEnableExperiment, defaultsTo: '', help: 'Runs the driver tests in Dart VM with the given experiments enabled.', ); argParser.addFlag(_chromeDriverFlag, help: 'Runs chromedriver for the duration of the test.\n\n' 'Requires the correct version of chromedriver to be in your path.'); } static const String _chromeDriverFlag = 'run-chromedriver'; @override final String name = 'drive-examples'; @override final String description = 'Runs Dart integration tests for example apps.\n\n' "This runs all tests in each example's integration_test directory, " 'via "flutter test" on most platforms, and "flutter drive" on web.\n\n' 'This command requires "flutter" to be in your path.'; Map<String, List<String>> _targetDeviceFlags = const <String, List<String>>{}; @override Future<void> initializeRun() async { final List<String> platformSwitches = <String>[ platformAndroid, platformIOS, platformLinux, platformMacOS, platformWeb, platformWindows, ]; final int platformCount = platformSwitches .where((String platform) => getBoolArg(platform)) .length; // The flutter tool currently doesn't accept multiple device arguments: // https://github.com/flutter/flutter/issues/35733 // If that is implemented, this check can be relaxed. if (platformCount != 1) { printError( 'Exactly one of ${platformSwitches.map((String platform) => '--$platform').join(', ')} ' 'must be specified.'); throw ToolExit(_exitNoPlatformFlags); } String? androidDevice; if (getBoolArg(platformAndroid)) { final List<String> devices = await _getDevicesForPlatform('android'); if (devices.isEmpty) { printError('No Android devices available'); throw ToolExit(_exitNoAvailableDevice); } androidDevice = devices.first; } String? iOSDevice; if (getBoolArg(platformIOS)) { final List<String> devices = await _getDevicesForPlatform('ios'); if (devices.isEmpty) { printError('No iOS devices available'); throw ToolExit(_exitNoAvailableDevice); } iOSDevice = devices.first; } _targetDeviceFlags = <String, List<String>>{ if (getBoolArg(platformAndroid)) platformAndroid: <String>['-d', androidDevice!], if (getBoolArg(platformIOS)) platformIOS: <String>['-d', iOSDevice!], if (getBoolArg(platformLinux)) platformLinux: <String>['-d', 'linux'], if (getBoolArg(platformMacOS)) platformMacOS: <String>['-d', 'macos'], if (getBoolArg(platformWeb)) platformWeb: <String>[ '-d', 'web-server', '--web-port=7357', '--browser-name=chrome', '--web-renderer=html', if (platform.environment.containsKey('CHROME_EXECUTABLE')) '--chrome-binary=${platform.environment['CHROME_EXECUTABLE']}', ], if (getBoolArg(platformWindows)) platformWindows: <String>['-d', 'windows'], }; } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final bool isPlugin = isFlutterPlugin(package); if (package.isPlatformInterface && package.getExamples().isEmpty) { // Platform interface packages generally aren't intended to have // examples, and don't need integration tests, so skip rather than fail. return PackageResult.skip( 'Platform interfaces are not expected to have integration tests.'); } // For plugin packages, skip if the plugin itself doesn't support any // requested platform(s). if (isPlugin) { final Iterable<String> requestedPlatforms = _targetDeviceFlags.keys; final Iterable<String> unsupportedPlatforms = requestedPlatforms.where( (String platform) => !pluginSupportsPlatform(platform, package)); for (final String platform in unsupportedPlatforms) { print('Skipping unsupported platform $platform...'); } if (unsupportedPlatforms.length == requestedPlatforms.length) { return PackageResult.skip( '${package.displayName} does not support any requested platform.'); } } int examplesFound = 0; int supportedExamplesFound = 0; bool testsRan = false; final List<String> errors = <String>[]; for (final RepositoryPackage example in package.getExamples()) { ++examplesFound; final String exampleName = getRelativePosixPath(example.directory, from: packagesDir); // Skip examples that don't support any requested platform(s). final List<String> deviceFlags = _deviceFlagsForExample(example); if (deviceFlags.isEmpty) { print( 'Skipping $exampleName; does not support any requested platforms.'); continue; } ++supportedExamplesFound; final List<File> testTargets = await _getIntegrationTests(example); if (testTargets.isEmpty) { print('No integration_test/*.dart files found for $exampleName.'); continue; } // Check files for known problematic patterns. testTargets .where((File file) => !_validateIntegrationTest(file)) .forEach((File file) { // Report the issue, but continue with the test as the validation // errors don't prevent running. errors.add('${file.basename} failed validation'); }); // `flutter test` doesn't yet support web integration tests, so fall back // to `flutter drive`. final bool useFlutterDrive = getBoolArg(platformWeb); final List<File> drivers; if (useFlutterDrive) { drivers = await _getDrivers(example); if (drivers.isEmpty) { print('No driver found for $exampleName'); continue; } } else { drivers = <File>[]; } testsRan = true; if (useFlutterDrive) { Process? chromedriver; if (getBoolArg(_chromeDriverFlag)) { print('Starting chromedriver on port $_chromeDriverPort'); chromedriver = await processRunner .start('chromedriver', <String>['--port=$_chromeDriverPort']); } for (final File driver in drivers) { final List<File> failingTargets = await _driveTests( example, driver, testTargets, deviceFlags: deviceFlags); for (final File failingTarget in failingTargets) { errors.add( getRelativePosixPath(failingTarget, from: package.directory)); } } if (chromedriver != null) { print('Stopping chromedriver'); chromedriver.kill(); } } else { if (!await _runTests(example, deviceFlags: deviceFlags, testFiles: testTargets)) { errors.add('Integration tests failed.'); } } } if (!testsRan) { // It is an error for a plugin not to have integration tests, because that // is the only way to test the method channel communication. if (isPlugin) { printError( 'No driver tests were run ($examplesFound example(s) found).'); errors.add('No tests ran (use --exclude if this is intentional).'); } else { return PackageResult.skip(supportedExamplesFound == 0 ? 'No example supports requested platform(s).' : 'No example is configured for integration tests.'); } } return errors.isEmpty ? PackageResult.success() : PackageResult.fail(errors); } /// Returns the device flags for the intersection of the requested platforms /// and the platforms supported by [example]. List<String> _deviceFlagsForExample(RepositoryPackage example) { final List<String> deviceFlags = <String>[]; for (final MapEntry<String, List<String>> entry in _targetDeviceFlags.entries) { final String platform = entry.key; if (example.appSupportsPlatform(getPlatformByName(platform))) { deviceFlags.addAll(entry.value); } else { final String exampleName = getRelativePosixPath(example.directory, from: packagesDir); print('Skipping unsupported platform $platform for $exampleName'); } } return deviceFlags; } Future<List<String>> _getDevicesForPlatform(String platform) async { final List<String> deviceIds = <String>[]; final ProcessResult result = await processRunner.run( flutterCommand, <String>['devices', '--machine'], stdoutEncoding: utf8); if (result.exitCode != 0) { return deviceIds; } String output = result.stdout as String; // --machine doesn't currently prevent the tool from printing banners; // see https://github.com/flutter/flutter/issues/86055. This workaround // can be removed once that is fixed. output = output.substring(output.indexOf('[')); final List<Map<String, dynamic>> devices = (jsonDecode(output) as List<dynamic>).cast<Map<String, dynamic>>(); for (final Map<String, dynamic> deviceInfo in devices) { final String targetPlatform = (deviceInfo['targetPlatform'] as String?) ?? ''; if (targetPlatform.startsWith(platform)) { final String? deviceId = deviceInfo['id'] as String?; if (deviceId != null) { deviceIds.add(deviceId); } } } return deviceIds; } Future<List<File>> _getDrivers(RepositoryPackage example) async { final List<File> drivers = <File>[]; final Directory driverDir = example.directory.childDirectory('test_driver'); if (driverDir.existsSync()) { await for (final FileSystemEntity driver in driverDir.list()) { if (driver is File && driver.basename.endsWith('_test.dart')) { drivers.add(driver); } } } return drivers; } Future<List<File>> _getIntegrationTests(RepositoryPackage example) async { final List<File> tests = <File>[]; final Directory integrationTestDir = example.directory.childDirectory('integration_test'); if (integrationTestDir.existsSync()) { await for (final FileSystemEntity file in integrationTestDir.list(recursive: true)) { if (file is File && file.basename.endsWith('_test.dart')) { tests.add(file); } } } return tests; } /// Checks [testFile] for known bad patterns in integration tests, logging /// any issues. /// /// Returns true if the file passes validation without issues. bool _validateIntegrationTest(File testFile) { final List<String> lines = testFile.readAsLinesSync(); final RegExp badTestPattern = RegExp(r'\s*test\('); if (lines.any((String line) => line.startsWith(badTestPattern))) { final String filename = testFile.basename; printError( '$filename uses "test", which will not report failures correctly. ' 'Use testWidgets instead.'); return false; } return true; } /// For each file in [targets], uses /// `flutter drive --driver [driver] --target <target>` /// to drive [example], returning a list of any failing test targets. /// /// [deviceFlags] should contain the flags to run the test on a specific /// target device (plus any supporting device-specific flags). E.g.: /// - `['-d', 'macos']` for driving for macOS. /// - `['-d', 'web-server', '--web-port=<port>', '--browser-name=<browser>]` /// for web Future<List<File>> _driveTests( RepositoryPackage example, File driver, List<File> targets, { required List<String> deviceFlags, }) async { final List<File> failures = <File>[]; final String enableExperiment = getStringArg(kEnableExperiment); for (final File target in targets) { final int exitCode = await processRunner.runAndStream( flutterCommand, <String>[ 'drive', ...deviceFlags, if (enableExperiment.isNotEmpty) '--enable-experiment=$enableExperiment', '--driver', getRelativePosixPath(driver, from: example.directory), '--target', getRelativePosixPath(target, from: example.directory), ], workingDir: example.directory); if (exitCode != 0) { failures.add(target); } } return failures; } /// Uses `flutter test integration_test` to run [example], returning the /// success of the test run. /// /// [deviceFlags] should contain the flags to run the test on a specific /// target device (plus any supporting device-specific flags). E.g.: /// - `['-d', 'macos']` for driving for macOS. /// - `['-d', 'web-server', '--web-port=<port>', '--browser-name=<browser>]` /// for web Future<bool> _runTests( RepositoryPackage example, { required List<String> deviceFlags, required List<File> testFiles, }) async { final String enableExperiment = getStringArg(kEnableExperiment); // Workaround for https://github.com/flutter/flutter/issues/135673 // Once that is fixed on stable, this logic can be removed and the command // can always just be run with "integration_test". final bool needsMultipleInvocations = testFiles.length > 1 && (getBoolArg(platformLinux) || getBoolArg(platformMacOS) || getBoolArg(platformWindows)); final Iterable<String> individualRunTargets = needsMultipleInvocations ? testFiles .map((File f) => getRelativePosixPath(f, from: example.directory)) : <String>['integration_test']; bool passed = true; for (final String target in individualRunTargets) { final int exitCode = await processRunner.runAndStream( flutterCommand, <String>[ 'test', ...deviceFlags, if (enableExperiment.isNotEmpty) '--enable-experiment=$enableExperiment', target, ], workingDir: example.directory); passed = passed && (exitCode == 0); } return passed; } }
packages/script/tool/lib/src/drive_examples_command.dart/0
{ "file_path": "packages/script/tool/lib/src/drive_examples_command.dart", "repo_id": "packages", "token_count": 5878 }
1,149
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/file.dart'; import 'package:path/path.dart' as p; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:yaml/yaml.dart'; import 'common/core.dart'; import 'common/output_utils.dart'; import 'common/package_looping_command.dart'; import 'common/plugin_utils.dart'; import 'common/repository_package.dart'; /// A command to enforce pubspec conventions across the repository. /// /// This both ensures that repo best practices for which optional fields are /// used are followed, and that the structure is consistent to make edits /// across multiple pubspec files easier. class PubspecCheckCommand extends PackageLoopingCommand { /// Creates an instance of the version check command. PubspecCheckCommand( super.packagesDir, { super.processRunner, super.platform, super.gitDir, }) { argParser.addOption( _minMinFlutterVersionFlag, help: 'The minimum Flutter version to allow as the minimum SDK constraint.', ); argParser.addMultiOption(_allowDependenciesFlag, help: 'Packages (comma separated) that are allowed as dependencies or ' 'dev_dependencies.\n\n' 'Alternately, a list of one or more YAML files that contain a list ' 'of allowed dependencies.', defaultsTo: <String>[]); argParser.addMultiOption(_allowPinnedDependenciesFlag, help: 'Packages (comma separated) that are allowed as dependencies or ' 'dev_dependencies only if pinned to an exact version.\n\n' 'Alternately, a list of one or more YAML files that contain a list ' 'of allowed pinned dependencies.', defaultsTo: <String>[]); } static const String _minMinFlutterVersionFlag = 'min-min-flutter-version'; static const String _allowDependenciesFlag = 'allow-dependencies'; static const String _allowPinnedDependenciesFlag = 'allow-pinned-dependencies'; // Section order for plugins. Because the 'flutter' section is critical // information for plugins, and usually small, it goes near the top unlike in // a normal app or package. static const List<String> _majorPluginSections = <String>[ 'environment:', 'flutter:', 'dependencies:', 'dev_dependencies:', 'topics:', 'screenshots:', 'false_secrets:', ]; static const List<String> _majorPackageSections = <String>[ 'environment:', 'dependencies:', 'dev_dependencies:', 'flutter:', 'topics:', 'screenshots:', 'false_secrets:', ]; static const String _expectedIssueLinkFormat = 'https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A'; // The names of all published packages in the repository. late final Set<String> _localPackages = <String>{}; // Packages on the explicit allow list. late final Set<String> _allowedUnpinnedPackages = <String>{}; late final Set<String> _allowedPinnedPackages = <String>{}; @override final String name = 'pubspec-check'; @override List<String> get aliases => <String>['check-pubspec']; @override final String description = 'Checks that pubspecs follow repository conventions.'; @override bool get hasLongOutput => false; @override PackageLoopingType get packageLoopingType => PackageLoopingType.includeAllSubpackages; @override Future<void> initializeRun() async { // Find all local, published packages. for (final File pubspecFile in (await packagesDir.parent .list(recursive: true, followLinks: false) .toList()) .whereType<File>() .where((File entity) => p.basename(entity.path) == 'pubspec.yaml')) { final Pubspec? pubspec = _tryParsePubspec(pubspecFile.readAsStringSync()); if (pubspec != null && pubspec.publishTo != 'none') { _localPackages.add(pubspec.name); } } // Load explicitly allowed packages. _allowedUnpinnedPackages .addAll(_getAllowedPackages(_allowDependenciesFlag)); _allowedPinnedPackages .addAll(_getAllowedPackages(_allowPinnedDependenciesFlag)); } Iterable<String> _getAllowedPackages(String flag) { return getStringListArg(flag).expand<String>((String item) { if (item.endsWith('.yaml')) { final File file = packagesDir.fileSystem.file(item); final Object? yaml = loadYaml(file.readAsStringSync()); if (yaml == null) { return <String>[]; } return (yaml as YamlList).toList().cast<String>(); } return <String>[item]; }); } @override Future<PackageResult> runForPackage(RepositoryPackage package) async { final File pubspec = package.pubspecFile; final bool passesCheck = !pubspec.existsSync() || await _checkPubspec(pubspec, package: package); if (!passesCheck) { return PackageResult.fail(); } return PackageResult.success(); } Future<bool> _checkPubspec( File pubspecFile, { required RepositoryPackage package, }) async { final String contents = pubspecFile.readAsStringSync(); final Pubspec? pubspec = _tryParsePubspec(contents); if (pubspec == null) { return false; } final List<String> pubspecLines = contents.split('\n'); final bool isPlugin = pubspec.flutter?.containsKey('plugin') ?? false; final List<String> sectionOrder = isPlugin ? _majorPluginSections : _majorPackageSections; bool passing = _checkSectionOrder(pubspecLines, sectionOrder); if (!passing) { printError('${indentation}Major sections should follow standard ' 'repository ordering:'); final String listIndentation = indentation * 2; printError('$listIndentation${sectionOrder.join('\n$listIndentation')}'); } final String minMinFlutterVersionString = getStringArg(_minMinFlutterVersionFlag); final String? minVersionError = _checkForMinimumVersionError( pubspec, package, minMinFlutterVersion: minMinFlutterVersionString.isEmpty ? null : Version.parse(minMinFlutterVersionString), ); if (minVersionError != null) { printError('$indentation$minVersionError'); passing = false; } if (isPlugin) { final String? implementsError = _checkForImplementsError(pubspec, package: package); if (implementsError != null) { printError('$indentation$implementsError'); passing = false; } final String? defaultPackageError = _checkForDefaultPackageError(pubspec, package: package); if (defaultPackageError != null) { printError('$indentation$defaultPackageError'); passing = false; } } final String? dependenciesError = _checkDependencies(pubspec); if (dependenciesError != null) { printError('$indentation$dependenciesError'); passing = false; } // Ignore metadata that's only relevant for published packages if the // packages is not intended for publishing. if (pubspec.publishTo != 'none') { final List<String> repositoryErrors = _checkForRepositoryLinkErrors(pubspec, package: package); if (repositoryErrors.isNotEmpty) { for (final String error in repositoryErrors) { printError('$indentation$error'); } passing = false; } if (!_checkIssueLink(pubspec)) { printError( '${indentation}A package should have an "issue_tracker" link to a ' 'search for open flutter/flutter bugs with the relevant label:\n' '${indentation * 2}$_expectedIssueLinkFormat<package label>'); passing = false; } final String? topicsError = _checkTopics(pubspec, package: package); if (topicsError != null) { printError('$indentation$topicsError'); passing = false; } // Don't check descriptions for federated package components other than // the app-facing package, since they are unlisted, and are expected to // have short descriptions. if (!package.isPlatformInterface && !package.isPlatformImplementation) { final String? descriptionError = _checkDescription(pubspec, package: package); if (descriptionError != null) { printError('$indentation$descriptionError'); passing = false; } } } return passing; } Pubspec? _tryParsePubspec(String pubspecContents) { try { return Pubspec.parse(pubspecContents); } on Exception catch (exception) { print(' Cannot parse pubspec.yaml: $exception'); } return null; } bool _checkSectionOrder( List<String> pubspecLines, List<String> sectionOrder) { int previousSectionIndex = 0; for (final String line in pubspecLines) { final int index = sectionOrder.indexOf(line); if (index == -1) { continue; } if (index < previousSectionIndex) { return false; } previousSectionIndex = index; } return true; } List<String> _checkForRepositoryLinkErrors( Pubspec pubspec, { required RepositoryPackage package, }) { final List<String> errorMessages = <String>[]; if (pubspec.repository == null) { errorMessages.add('Missing "repository"'); } else { final String relativePackagePath = getRelativePosixPath(package.directory, from: packagesDir.parent); if (!pubspec.repository!.path.endsWith(relativePackagePath)) { errorMessages .add('The "repository" link should end with the package path.'); } if (!pubspec.repository! .toString() .startsWith('https://github.com/flutter/packages/tree/main')) { errorMessages .add('The "repository" link should start with the repository\'s ' 'main tree: "https://github.com/flutter/packages/tree/main".'); } } if (pubspec.homepage != null) { errorMessages .add('Found a "homepage" entry; only "repository" should be used.'); } return errorMessages; } // Validates the "description" field for a package, returning an error // string if there are any issues. String? _checkDescription( Pubspec pubspec, { required RepositoryPackage package, }) { final String? description = pubspec.description; if (description == null) { return 'Missing "description"'; } if (description.length < 60) { return '"description" is too short. pub.dev recommends package ' 'descriptions of 60-180 characters.'; } if (description.length > 180) { return '"description" is too long. pub.dev recommends package ' 'descriptions of 60-180 characters.'; } return null; } bool _checkIssueLink(Pubspec pubspec) { return pubspec.issueTracker ?.toString() .startsWith(_expectedIssueLinkFormat) ?? false; } // Validates the "topics" keyword for a plugin, returning an error // string if there are any issues. String? _checkTopics( Pubspec pubspec, { required RepositoryPackage package, }) { final List<String> topics = pubspec.topics ?? <String>[]; if (topics.isEmpty) { return 'A published package should include "topics". ' 'See https://dart.dev/tools/pub/pubspec#topics.'; } if (topics.length > 5) { return 'A published package should have maximum 5 topics. ' 'See https://dart.dev/tools/pub/pubspec#topics.'; } if (isFlutterPlugin(package) && package.isFederated) { final String pluginName = package.directory.parent.basename; // '_' isn't allowed in topics, so convert to '-'. final String topicName = pluginName.replaceAll('_', '-'); if (!topics.contains(topicName)) { return 'A federated plugin package should include its plugin name as ' 'a topic. Add "$topicName" to the "topics" section.'; } } // Validates topic names according to https://dart.dev/tools/pub/pubspec#topics final RegExp expectedTopicFormat = RegExp(r'^[a-z](?:-?[a-z0-9]+)*$'); final Iterable<String> invalidTopics = topics.where((String topic) => !expectedTopicFormat.hasMatch(topic) || topic.length < 2 || topic.length > 32); if (invalidTopics.isNotEmpty) { return 'Invalid topic(s): ${invalidTopics.join(', ')} in "topics" section. ' 'Topics must consist of lowercase alphanumerical characters or dash (but no double dash), ' 'start with a-z and ending with a-z or 0-9, have a minimum of 2 characters ' 'and have a maximum of 32 characters.'; } return null; } // Validates the "implements" keyword for a plugin, returning an error // string if there are any issues. // // Should only be called on plugin packages. String? _checkForImplementsError( Pubspec pubspec, { required RepositoryPackage package, }) { if (_isImplementationPackage(package)) { final YamlMap pluginSection = pubspec.flutter!['plugin'] as YamlMap; final String? implements = pluginSection['implements'] as String?; final String expectedImplements = package.directory.parent.basename; if (implements == null) { return 'Missing "implements: $expectedImplements" in "plugin" section.'; } else if (implements != expectedImplements) { return 'Expecetd "implements: $expectedImplements"; ' 'found "implements: $implements".'; } } return null; } // Validates any "default_package" entries a plugin, returning an error // string if there are any issues. // // Should only be called on plugin packages. String? _checkForDefaultPackageError( Pubspec pubspec, { required RepositoryPackage package, }) { final YamlMap pluginSection = pubspec.flutter!['plugin'] as YamlMap; final YamlMap? platforms = pluginSection['platforms'] as YamlMap?; if (platforms == null) { logWarning('Does not implement any platforms'); return null; } final String packageName = package.directory.basename; // Validate that the default_package entries look correct (e.g., no typos). final Set<String> defaultPackages = <String>{}; for (final MapEntry<Object?, Object?> platformEntry in platforms.entries) { final YamlMap platformDetails = platformEntry.value! as YamlMap; final String? defaultPackage = platformDetails['default_package'] as String?; if (defaultPackage != null) { defaultPackages.add(defaultPackage); if (!defaultPackage.startsWith('${packageName}_')) { return '"$defaultPackage" is not an expected implementation name ' 'for "$packageName"'; } } } // Validate that all default_packages are also dependencies. final Iterable<String> dependencies = pubspec.dependencies.keys; final Iterable<String> missingPackages = defaultPackages .where((String package) => !dependencies.contains(package)); if (missingPackages.isNotEmpty) { return 'The following default_packages are missing ' 'corresponding dependencies:\n' ' ${missingPackages.join('\n ')}'; } return null; } // Returns true if [packageName] appears to be an implementation package // according to repository conventions. bool _isImplementationPackage(RepositoryPackage package) { if (!package.isFederated) { return false; } final String packageName = package.directory.basename; final String parentName = package.directory.parent.basename; // A few known package names are not implementation packages; assume // anything else is. (This is done instead of listing known implementation // suffixes to allow for non-standard suffixes; e.g., to put several // platforms in one package for code-sharing purposes.) const Set<String> nonImplementationSuffixes = <String>{ '', // App-facing package. '_platform_interface', // Platform interface package. }; final String suffix = packageName.substring(parentName.length); return !nonImplementationSuffixes.contains(suffix); } /// Validates that a Flutter package has a minimum SDK version constraint of /// at least [minMinFlutterVersion] (if provided), or that a non-Flutter /// package has a minimum SDK version constraint of [minMinDartVersion] /// (if provided). /// /// Returns an error string if validation fails. String? _checkForMinimumVersionError( Pubspec pubspec, RepositoryPackage package, { Version? minMinFlutterVersion, }) { String unknownDartVersionError(Version flutterVersion) { return 'Dart SDK version for Fluter SDK version ' '$flutterVersion is unknown. ' 'Please update the map for getDartSdkForFlutterSdk with the ' 'corresponding Dart version.'; } Version? minMinDartVersion; if (minMinFlutterVersion != null) { minMinDartVersion = getDartSdkForFlutterSdk(minMinFlutterVersion); if (minMinDartVersion == null) { return unknownDartVersionError(minMinFlutterVersion); } } final Version? dartConstraintMin = _minimumForConstraint(pubspec.environment?['sdk']); final Version? flutterConstraintMin = _minimumForConstraint(pubspec.environment?['flutter']); // Validate the Flutter constraint, if any. if (flutterConstraintMin != null && minMinFlutterVersion != null) { if (flutterConstraintMin < minMinFlutterVersion) { return 'Minimum allowed Flutter version $flutterConstraintMin is less ' 'than $minMinFlutterVersion'; } } // Validate the Dart constraint, if any. if (dartConstraintMin != null) { // Ensure that it satisfies the minimum. if (minMinDartVersion != null) { if (dartConstraintMin < minMinDartVersion) { return 'Minimum allowed Dart version $dartConstraintMin is less than $minMinDartVersion'; } } // Ensure that if there is also a Flutter constraint, they are consistent. if (flutterConstraintMin != null) { final Version? dartVersionForFlutterMinimum = getDartSdkForFlutterSdk(flutterConstraintMin); if (dartVersionForFlutterMinimum == null) { return unknownDartVersionError(flutterConstraintMin); } if (dartVersionForFlutterMinimum != dartConstraintMin) { return 'The minimum Dart version is $dartConstraintMin, but the ' 'minimum Flutter version of $flutterConstraintMin shipped with ' 'Dart $dartVersionForFlutterMinimum. Please use consistent lower ' 'SDK bounds'; } } } return null; } /// Returns the minumum version allowed by [constraint], or null if the /// constraint is null. Version? _minimumForConstraint(VersionConstraint? constraint) { if (constraint == null) { return null; } Version? result; if (constraint is VersionRange) { result = constraint.min; } return result ?? Version.none; } // Validates the dependencies for a package, returning an error string if // there are any that aren't allowed. String? _checkDependencies(Pubspec pubspec) { final Set<String> badDependencies = <String>{}; for (final Map<String, Dependency> dependencies in <Map<String, Dependency>>[ pubspec.dependencies, pubspec.devDependencies ]) { dependencies.forEach((String name, Dependency dependency) { if (!_shouldAllowDependency(name, dependency)) { badDependencies.add(name); } }); } if (badDependencies.isEmpty) { return null; } return 'The following unexpected non-local dependencies were found:\n' '${badDependencies.map((String name) => ' $name').join('\n')}\n' 'Please see https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#Dependencies ' 'for more information and next steps.'; } // Checks whether a given dependency is allowed. bool _shouldAllowDependency(String name, Dependency dependency) { if (dependency is PathDependency || dependency is SdkDependency) { return true; } if (_localPackages.contains(name) || _allowedUnpinnedPackages.contains(name)) { return true; } if (dependency is HostedDependency && _allowedPinnedPackages.contains(name)) { final VersionConstraint constraint = dependency.version; if (constraint is VersionRange && constraint.min != null && constraint.max != null && constraint.min == constraint.max) { return true; } } return false; } }
packages/script/tool/lib/src/pubspec_check_command.dart/0
{ "file_path": "packages/script/tool/lib/src/pubspec_check_command.dart", "repo_id": "packages", "token_count": 7679 }
1,150
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:flutter_plugin_tools/src/common/output_utils.dart'; import 'package:test/test.dart'; void main() { group('with color support', () { setUp(() { useColorForOutput = true; }); tearDown(() { useColorForOutput = stdout.supportsAnsiEscapes; }); test('colorize works', () async { const String message = 'a message'; expect( colorizeString(message, Styles.MAGENTA), '\x1B[35m$message\x1B[0m'); }); test('printSuccess is green', () async { const String message = 'a message'; expect(await _capturePrint(() => printSuccess(message)), '\x1B[32m$message\x1B[0m'); }); test('printWarning is yellow', () async { const String message = 'a message'; expect(await _capturePrint(() => printWarning(message)), '\x1B[33m$message\x1B[0m'); }); test('printError is red', () async { const String message = 'a message'; expect(await _capturePrint(() => printError(message)), '\x1B[31m$message\x1B[0m'); }); }); group('without color support', () { setUp(() { useColorForOutput = false; }); tearDown(() { useColorForOutput = stdout.supportsAnsiEscapes; }); test('colorize no-ops', () async { const String message = 'a message'; expect(colorizeString(message, Styles.MAGENTA), message); }); test('printSuccess just prints', () async { const String message = 'a message'; expect(await _capturePrint(() => printSuccess(message)), message); }); test('printWarning just prints', () async { const String message = 'a message'; expect(await _capturePrint(() => printWarning(message)), message); }); test('printError just prints', () async { const String message = 'a message'; expect(await _capturePrint(() => printError(message)), message); }); }); } /// Run the command [runner] with the given [args] and return /// what was printed. /// A custom [errorHandler] can be used to handle the runner error as desired without throwing. Future<String> _capturePrint(void Function() printFunction) async { final StringBuffer output = StringBuffer(); final ZoneSpecification spec = ZoneSpecification( print: (_, __, ___, String message) { output.write(message); }, ); await Zone.current .fork(specification: spec) .run<Future<void>>(() async => printFunction()); return output.toString(); }
packages/script/tool/test/common/output_utils_test.dart/0
{ "file_path": "packages/script/tool/test/common/output_utils_test.dart", "repo_id": "packages", "token_count": 979 }
1,151
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/common/core.dart'; import 'package:flutter_plugin_tools/src/common/plugin_utils.dart'; import 'package:flutter_plugin_tools/src/fetch_deps_command.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'util.dart'; void main() { group('FetchDepsCommand', () { FileSystem fileSystem; late Directory packagesDir; late CommandRunner<void> runner; late MockPlatform mockPlatform; late RecordingProcessRunner processRunner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); mockPlatform = MockPlatform(); processRunner = RecordingProcessRunner(); final FetchDepsCommand command = FetchDepsCommand( packagesDir, processRunner: processRunner, platform: mockPlatform, ); runner = CommandRunner<void>('fetch_deps_test', 'Test for $FetchDepsCommand'); runner.addCommand(command); }); group('dart', () { test('runs pub get', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final List<String> output = await runCapturingPrint(runner, <String>['fetch-deps']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'flutter', const <String>['pub', 'get'], plugin.directory.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('fails if pub get fails', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('Failed to "pub get"'), ], )); }); test('skips unsupported packages when any platforms are passed', () async { final RepositoryPackage packageWithBoth = createFakePackage( 'supports_both', packagesDir, extraFiles: <String>[ 'example/linux/placeholder', 'example/windows/placeholder' ]); final RepositoryPackage packageWithOne = createFakePackage( 'supports_one', packagesDir, extraFiles: <String>['example/linux/placeholder']); createFakePackage('supports_neither', packagesDir); await runCapturingPrint(runner, <String>[ 'fetch-deps', '--linux', '--windows', '--supporting-target-platforms-only' ]); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'dart', const <String>['pub', 'get'], packageWithBoth.path, ), ProcessCall( 'dart', const <String>['pub', 'get'], packageWithOne.path, ), ]), ); }); }); group('android', () { test('runs pub get before gradlew dependencies', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, extraFiles: <String>[ 'example/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Directory androidDir = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( 'flutter', const <String>['pub', 'get'], plugin.directory.path, ), ProcessCall( androidDir.childFile('gradlew').path, const <String>['plugin1:dependencies'], androidDir.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('runs gradlew dependencies', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, extraFiles: <String>[ 'example/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Directory androidDir = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( androidDir.childFile('gradlew').path, const <String>['plugin1:dependencies'], androidDir.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('runs on all examples', () async { final List<String> examples = <String>['example1', 'example2']; final RepositoryPackage plugin = createFakePlugin( 'plugin1', packagesDir, examples: examples, extraFiles: <String>[ 'example/example1/android/gradlew', 'example/example2/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Iterable<Directory> exampleAndroidDirs = plugin.getExamples().map( (RepositoryPackage example) => example.platformDirectory(FlutterPlatform.android)); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ for (final Directory directory in exampleAndroidDirs) ProcessCall( directory.childFile('gradlew').path, const <String>['plugin1:dependencies'], directory.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('runs --config-only build if gradlew is missing', () async { final RepositoryPackage plugin = createFakePlugin( 'plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final Directory androidDir = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--android']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ ProcessCall( getFlutterCommand(mockPlatform), const <String>['build', 'apk', '--config-only'], plugin.getExamples().first.directory.path, ), ProcessCall( androidDir.childFile('gradlew').path, const <String>['plugin1:dependencies'], androidDir.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('fails if gradlew generation fails', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('Unable to configure Gradle project'), ], )); }); test('fails if dependency download finds issues', () async { final RepositoryPackage plugin = createFakePlugin('plugin1', packagesDir, extraFiles: <String>[ 'example/android/gradlew', ], platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.inline) }); final String gradlewPath = plugin .getExamples() .first .platformDirectory(FlutterPlatform.android) .childFile('gradlew') .path; processRunner.mockProcessesForExecutable[gradlewPath] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(exitCode: 1)), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--android'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('The following packages had errors:'), ], )); }); test('skips non-Android plugins', () async { createFakePlugin('plugin1', packagesDir); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--android']); expect( output, containsAllInOrder( <Matcher>[ contains('Package does not have native Android dependencies.') ], )); }); test('skips non-inline plugins', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformAndroid: const PlatformDetails(PlatformSupport.federated) }); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--android']); expect( output, containsAllInOrder( <Matcher>[ contains('Package does not have native Android dependencies.') ], )); }); }); group('ios', () { test('runs on all examples', () async { final List<String> examples = <String>['example1', 'example2']; final RepositoryPackage plugin = createFakePlugin( 'plugin1', packagesDir, examples: examples, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); final Iterable<Directory> exampleDirs = plugin .getExamples() .map((RepositoryPackage example) => example.directory); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--ios']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ const ProcessCall( 'flutter', <String>['precache', '--ios'], null, ), for (final Directory directory in exampleDirs) ProcessCall( 'flutter', const <String>['build', 'ios', '--config-only'], directory.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('fails if flutter build --config-only fails', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.inline) }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['precache']), FakeProcessInfo(MockProcess(exitCode: 1), <String>['build', 'ios', '--config-only']), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--ios'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('The following packages had errors:'), ], )); }); test('skips non-iOS plugins', () async { createFakePlugin('plugin1', packagesDir); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--ios']); expect( output, containsAllInOrder( <Matcher>[ contains('Package does not have native iOS dependencies.') ], )); }); test('skips non-inline plugins', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformIOS: const PlatformDetails(PlatformSupport.federated) }); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--ios']); expect( output, containsAllInOrder( <Matcher>[ contains('Package does not have native iOS dependencies.') ], )); }); }); group('macos', () { test('runs on all examples', () async { final List<String> examples = <String>['example1', 'example2']; final RepositoryPackage plugin = createFakePlugin( 'plugin1', packagesDir, examples: examples, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline) }); final Iterable<Directory> exampleDirs = plugin .getExamples() .map((RepositoryPackage example) => example.directory); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--macos']); expect( processRunner.recordedCalls, orderedEquals(<ProcessCall>[ const ProcessCall( 'flutter', <String>['precache', '--macos'], null, ), for (final Directory directory in exampleDirs) ProcessCall( 'flutter', const <String>['build', 'macos', '--config-only'], directory.path, ), ]), ); expect( output, containsAllInOrder(<Matcher>[ contains('Running for plugin1'), contains('No issues found!'), ])); }); test('fails if flutter build --config-only fails', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.inline) }); processRunner .mockProcessesForExecutable[getFlutterCommand(mockPlatform)] = <FakeProcessInfo>[ FakeProcessInfo(MockProcess(), <String>['precache']), FakeProcessInfo(MockProcess(exitCode: 1), <String>['build', 'macos', '--config-only']), ]; Error? commandError; final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--macos'], errorHandler: (Error e) { commandError = e; }); expect(commandError, isA<ToolExit>()); expect( output, containsAllInOrder( <Matcher>[ contains('The following packages had errors:'), ], )); }); test('skips non-macOS plugins', () async { createFakePlugin('plugin1', packagesDir); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--macos']); expect( output, containsAllInOrder( <Matcher>[ contains('Package does not have native macOS dependencies.') ], )); }); test('skips non-inline plugins', () async { createFakePlugin('plugin1', packagesDir, platformSupport: <String, PlatformDetails>{ platformMacOS: const PlatformDetails(PlatformSupport.federated) }); final List<String> output = await runCapturingPrint( runner, <String>['fetch-deps', '--no-dart', '--macos']); expect( output, containsAllInOrder( <Matcher>[ contains('Package does not have native macOS dependencies.') ], )); }); }); }); }
packages/script/tool/test/fetch_deps_command_test.dart/0
{ "file_path": "packages/script/tool/test/fetch_deps_command_test.dart", "repo_id": "packages", "token_count": 9145 }
1,152
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/command_runner.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_plugin_tools/src/remove_dev_dependencies_command.dart'; import 'package:test/test.dart'; import 'util.dart'; void main() { late FileSystem fileSystem; late Directory packagesDir; late CommandRunner<void> runner; setUp(() { fileSystem = MemoryFileSystem(); packagesDir = createPackagesDirectory(fileSystem: fileSystem); final RemoveDevDependenciesCommand command = RemoveDevDependenciesCommand( packagesDir, ); runner = CommandRunner<void>('trim_dev_dependencies_command', 'Test for trim_dev_dependencies_command'); runner.addCommand(command); }); void addToPubspec(RepositoryPackage package, String addition) { final String originalContent = package.pubspecFile.readAsStringSync(); package.pubspecFile.writeAsStringSync(''' $originalContent $addition '''); } test('skips if nothing is removed', () async { createFakePackage('a_package', packagesDir, version: '1.0.0'); final List<String> output = await runCapturingPrint(runner, <String>['remove-dev-dependencies']); expect( output, containsAllInOrder(<Matcher>[ contains('SKIPPING: Nothing to remove.'), ]), ); }); test('removes dev_dependencies', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, version: '1.0.0'); addToPubspec(package, ''' dev_dependencies: some_dependency: ^2.1.8 another_dependency: ^1.0.0 '''); final List<String> output = await runCapturingPrint(runner, <String>['remove-dev-dependencies']); expect( output, containsAllInOrder(<Matcher>[ contains('Removed dev_dependencies'), ]), ); expect(package.pubspecFile.readAsStringSync(), isNot(contains('some_dependency:'))); expect(package.pubspecFile.readAsStringSync(), isNot(contains('another_dependency:'))); }); test('removes from examples', () async { final RepositoryPackage package = createFakePackage('a_package', packagesDir, version: '1.0.0'); final RepositoryPackage example = package.getExamples().first; addToPubspec(example, ''' dev_dependencies: some_dependency: ^2.1.8 another_dependency: ^1.0.0 '''); final List<String> output = await runCapturingPrint(runner, <String>['remove-dev-dependencies']); expect( output, containsAllInOrder(<Matcher>[ contains('Removed dev_dependencies'), ]), ); expect(package.pubspecFile.readAsStringSync(), isNot(contains('some_dependency:'))); expect(package.pubspecFile.readAsStringSync(), isNot(contains('another_dependency:'))); }); }
packages/script/tool/test/remove_dev_dependencies_command_test.dart/0
{ "file_path": "packages/script/tool/test/remove_dev_dependencies_command_test.dart", "repo_id": "packages", "token_count": 1062 }
1,153
{ "hosting": { "public": "build/web", "site": "io-photobooth-dev", "cleanUrls": true, "trailingSlash": false, "ignore": [ ".firebase", "firebase.json", "functions/node_modules", "functions/src", "__/**" ], "rewrites": [ { "source": "/share/**", "function": "shareImage" }, { "source": "**", "destination": "/index.html" } ], "headers": [ { "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)", "headers": [{ "key": "Access-Control-Allow-Origin", "value": "*" }] }, { "source": "**/*.@(jpg|jpeg|gif|png)", "headers": [{ "key": "Cache-Control", "value": "max-age=3600" }] }, { "source": "**", "headers": [{ "key": "Cache-Control", "value": "no-cache, no-store, must-revalidate" }] } ], "predeploy": [] }, "functions": { "source": "functions", "runtime": "nodejs14", "predeploy": [ "npm --prefix ./functions run test", "npm --prefix ./functions run build" ] }, "storage": { "rules": "storage.rules" }, "emulators": { "hosting": { "name": "app", "port": 5000, "host": "0.0.0.0" }, "functions": { "name": "api", "port": 5001, "host": "0.0.0.0" }, "ui": { "enabled": true, "port": 5002, "host": "0.0.0.0" } } }
photobooth/firebase.json/0
{ "file_path": "photobooth/firebase.json", "repo_id": "photobooth", "token_count": 828 }
1,154
{ "compilerOptions": { "noUnusedLocals": false }, "include": [ ".eslintrc.js" ] }
photobooth/functions/tsconfig.dev.json/0
{ "file_path": "photobooth/functions/tsconfig.dev.json", "repo_id": "photobooth", "token_count": 48 }
1,155
{ "@@locale": "hu", "landingPageHeading": "Üdvözlünk az I∕O Photo Booth-ban", "landingPageSubheading": "Készíts egy fotót és oszd meg a közösséggel!", "landingPageTakePhotoButtonText": "Kezdjünk bele", "footerMadeWithText": "Ezzel készült ", "footerMadeWithFlutterLinkText": "Flutter", "footerMadeWithFirebaseLinkText": "Firebase", "footerGoogleIOLinkText": "Google I∕O", "footerCodelabLinkText": "Codelab", "footerHowItsMadeLinkText": "Hogyan készült", "footerTermsOfServiceLinkText": "Felhasználási feltételek", "footerPrivacyPolicyLinkText": "Adatvédelmi irányelvek", "sharePageHeading": "Oszd meg a fotód a közösséggel!", "sharePageSubheading": "Oszd meg a fotód a közösséggel!", "sharePageSuccessHeading": "Fotó megosztva!", "sharePageSuccessSubheading": "Köszönjük, hogy a Flutter webalkalmazásunkat használtad! A fotód közzé lett téve ezen az egyedi webcímen", "sharePageSuccessCaption1": "A fotód elérhető lesz azon a webcímen 30 napig, majd automatikusan törölve lesz. A fotód korai törléséhez vedd fel a kapcsolatot a ", "sharePageSuccessCaption2": "[email protected]", "sharePageSuccessCaption3": " e-mail címen, és feltétlenül add meg az egyedi webcímet a törléshez.", "sharePageRetakeButtonText": "Készíts egy új fotót", "sharePageShareButtonText": "Megosztás", "sharePageDownloadButtonText": "Letöltés", "socialMediaShareLinkText": "Éppen készítettem egy szelfit a #IOPhotoBooth-nál. Még látjuk egymást a #GoogleIO-n!", "previewPageCameraNotAllowedText": "Megtagadtad a hozzáférést a kamerádhoz. Kérjük adj hozzáférést, hogy használhasd az alkalmazást.", "sharePageSocialMediaShareClarification1": "Ha a közösségi médiában szeretnéd megosztani a fotód, akkor 30 napig elérhető lesz ezen az egyedi webcímen, majd automatikusan törölve lesz. A fotók amelyek nem kerülnek megosztásra, nem lesznek eltárolva. A fotód korai törléséhez vedd fel a kapcsolatot a ", "sharePageSocialMediaShareClarification2": "[email protected]", "sharePageSocialMediaShareClarification3": " e-mail címen, és feltétlenül add meg az egyedi webcímet a törléshez.", "sharePageCopyLinkButton": "Másolás", "sharePageLinkedCopiedButton": "Másolva", "sharePageErrorHeading": "Gondjaink akadtak a fotód feldolgozásával", "sharePageErrorSubheading": "Kérjük ellenőrizd, hogy eszközöd és böngésződ naprakész-e. Hogyha a probléma továbbra is jelen van vedd fel a kapcsolatot a [email protected] e-mail címen.", "shareDialogHeading": "Oszd meg a fotód!", "shareDialogSubheading": "Tudasd mindenkivel, hogy részt veszel a Google I∕O-n azzal, hogy megosztod a fotódat és frissíted a profilképedet az esemény alatt.", "shareErrorDialogHeading": "Hoppá!", "shareErrorDialogTryAgainButton": "Menj vissza", "shareErrorDialogSubheading": "Valami hiba történt és nem tudtuk betölteni a fotódat.", "sharePageProgressOverlayHeading": "Éppen tökéletesítjük a fotódat Flutterrel! ", "sharePageProgressOverlaySubheading": "Kérjük, ne zárd be ezt a lapot.", "shareDialogTwitterButtonText": "Twitter", "shareDialogFacebookButtonText": "Facebook", "photoBoothCameraAccessDeniedHeadline": "Kamera hozzáférés megtagadva", "photoBoothCameraAccessDeniedSubheadline": "Ahhoz, hogy fotót készíthess, adj hozzáférést a böngésződnek a kamerádhoz.", "photoBoothCameraNotFoundHeadline": "Nem találjuk a kamerádat.", "photoBoothCameraNotFoundSubheadline1": "Úgy tűnik, hogy az eszközöd nem rendelkezik kamerával, vagy az nem működik.", "photoBoothCameraNotFoundSubheadline2": "Ahhoz, hogy fotót készíthess, kérjük látogasd meg az I∕O Photo Booth-ot egy kamerával rendelkező eszközről.", "photoBoothCameraErrorHeadline": "Hoppá! Valami hiba történt", "photoBoothCameraErrorSubheadline1": "Kérjük frissítsd a lapot a ", "photoBoothCameraErrorSubheadline2": "Hogyha a probléma továbbra is jelen van vedd fel a kapcsolatot a [email protected] e-mail címen.", "photoBoothCameraNotSupportedHeadline": "Hoppá! Valami hiba történt", "photoBoothCameraNotSupportedSubheadline": "Kérjük ellenőrizd, hogy eszközöd és böngésződ naprakész-e.", "stickersDrawerTitle": "Kellékek hozzáadása", "openStickersTooltip": "Kellékek hozzáadása", "retakeButtonTooltip": "Újrafotózás", "clearStickersButtonTooltip": "Kellékek törlése", "charactersCaptionText": "Barátok hozzáadása", "sharePageLearnMoreAboutTextPart1": "Tudj meg többet a ", "sharePageLearnMoreAboutTextPart2": " és ", "sharePageLearnMoreAboutTextPart3": " technológiákról, vagy tekintsd meg a ", "sharePageLearnMoreAboutTextPart4": "nyílt forráskódot", "goToGoogleIOButtonText": "Menj a Google I∕O-ra", "clearStickersDialogHeading": "Törlöd a kellékeket?", "clearStickersDialogSubheading": "Törölni szeretnéd az összes kelléket a képernyőről?", "clearStickersDialogCancelButtonText": "Nem, vigyél vissza", "clearStickersDialogConfirmButtonText": "Igen, kellékek törlése", "propsReminderText": "Kellékek hozzáadása", "stickersNextConfirmationHeading": "Készen állsz a kész fotó megtekintésére?", "stickersNextConfirmationSubheading": "Ha elhagyod ezt a képernyőt, nem fogsz tudni további módosításokat végrehajtani", "stickersNextConfirmationCancelButtonText": "Nem, még alkotok", "stickersNextConfirmationConfirmButtonText": "Igen, mutasd meg", "stickersRetakeConfirmationHeading": "Biztos vagy benne?", "stickersRetakeConfirmationSubheading": "Az újrafotózás eltűnteti a hozzáadott kellékeket", "stickersRetakeConfirmationCancelButtonText": "Nem, maradok itt", "stickersRetakeConfirmationConfirmButtonText": "Igen, újrafotózom", "shareRetakeConfirmationHeading": "Készen állsz egy új fotó elkészítésére?", "shareRetakeConfirmationSubheading": "Ne felejtsd el letölteni vagy megosztani ezt először", "shareRetakeConfirmationCancelButtonText": "Nem, maradok itt", "shareRetakeConfirmationConfirmButtonText": "Igen, újrafotózom", "shutterButtonLabelText": "Fotó készítése", "stickersNextButtonLabelText": "Végleges fotó elkészítése", "dashButtonLabelText": "Dash barát hozzáadása", "sparkyButtonLabelText": "Sparky barát hozzáadása", "dinoButtonLabelText": "Dínó barát hozzáadása", "androidButtonLabelText": "Android jetpack barát hozzáadása", "addStickersButtonLabelText": "Kellékek hozzáadása", "retakePhotoButtonLabelText": "Újrafotózás", "clearAllStickersButtonLabelText": "Kellékek törlése" }
photobooth/lib/l10n/arb/app_hu.arb/0
{ "file_path": "photobooth/lib/l10n/arb/app_hu.arb", "repo_id": "photobooth", "token_count": 2872 }
1,156
export 'landing_background.dart'; export 'landing_body.dart'; export 'landing_take_photo_button.dart';
photobooth/lib/landing/widgets/widgets.dart/0
{ "file_path": "photobooth/lib/landing/widgets/widgets.dart", "repo_id": "photobooth", "token_count": 37 }
1,157
import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:io_photobooth/l10n/l10n.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; class PhotoboothError extends StatelessWidget { const PhotoboothError({required this.error, super.key}); final CameraException error; @override Widget build(BuildContext context) { if (error is CameraNotAllowedException) { return const _PhotoboothCameraAccessDeniedError( key: Key('photoboothError_cameraAccessDenied'), ); } if (error is CameraNotFoundException) { return const _PhotoboothCameraNotFoundError( key: Key('photoboothError_cameraNotFound'), ); } if (error is CameraNotSupportedException) { return const _PhotoboothCameraNotSupportedError( key: Key('photoboothError_cameraNotSupported'), ); } return const _PhotoboothCameraUnknownError( key: Key('photoboothError_unknown'), ); } } class _PhotoboothCameraAccessDeniedError extends StatelessWidget { const _PhotoboothCameraAccessDeniedError({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return _PhotoboothErrorContent( children: [ SelectableText( l10n.photoBoothCameraAccessDeniedHeadline, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.photoBoothCameraAccessDeniedSubheadline, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ], ); } } class _PhotoboothCameraNotFoundError extends StatelessWidget { const _PhotoboothCameraNotFoundError({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return _PhotoboothErrorContent( children: [ SelectableText( l10n.photoBoothCameraNotFoundHeadline, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.photoBoothCameraNotFoundSubheadline1, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.photoBoothCameraNotFoundSubheadline2, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ], ); } } class _PhotoboothCameraUnknownError extends StatelessWidget { const _PhotoboothCameraUnknownError({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return _PhotoboothErrorContent( children: [ SelectableText( l10n.photoBoothCameraErrorHeadline, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.photoBoothCameraErrorSubheadline1, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.photoBoothCameraErrorSubheadline2, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ], ); } } class _PhotoboothCameraNotSupportedError extends StatelessWidget { const _PhotoboothCameraNotSupportedError({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; final theme = Theme.of(context); return _PhotoboothErrorContent( children: [ SelectableText( l10n.photoBoothCameraNotSupportedHeadline, style: theme.textTheme.displayLarge?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), const SizedBox(height: 24), SelectableText( l10n.photoBoothCameraNotSupportedSubheadline, style: theme.textTheme.displaySmall?.copyWith( color: PhotoboothColors.white, ), textAlign: TextAlign.center, ), ], ); } } class _PhotoboothErrorContent extends StatelessWidget { const _PhotoboothErrorContent({ required this.children, }); final List<Widget> children; @override Widget build(BuildContext context) { return Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 32), child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: children, ), ), ), ); } }
photobooth/lib/photobooth/widgets/photobooth_error.dart/0
{ "file_path": "photobooth/lib/photobooth/widgets/photobooth_error.dart", "repo_id": "photobooth", "token_count": 2343 }
1,158
import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; const _size = Size(173, 163); class AnimatedPhotoIndicator extends StatelessWidget { const AnimatedPhotoIndicator({super.key}); @override Widget build(BuildContext context) { return ResponsiveLayoutBuilder( small: (_, __) => const _AnimatedPhotoIndicator(scale: 0.6), medium: (_, __) => const _AnimatedPhotoIndicator(scale: 0.7), large: (_, __) => const _AnimatedPhotoIndicator(), ); } } class _AnimatedPhotoIndicator extends StatelessWidget { const _AnimatedPhotoIndicator({this.scale = 1.0}); final double scale; @override Widget build(BuildContext context) { return ConstrainedBox( constraints: BoxConstraints.loose( Size(_size.width * scale, _size.height * scale), ), child: const AnimatedSprite( sprites: Sprites( asset: 'photo_indicator_spritesheet.png', size: _size, frames: 51, stepTime: 0.05, ), showLoadingIndicator: false, ), ); } }
photobooth/lib/share/widgets/animated_photo_indicator.dart/0
{ "file_path": "photobooth/lib/share/widgets/animated_photo_indicator.dart", "repo_id": "photobooth", "token_count": 427 }
1,159
export 'animated_photo_indicator.dart'; export 'animated_photobooth_photo.dart'; export 'facebook_button.dart'; export 'share_background.dart'; export 'share_body.dart'; export 'share_button.dart'; export 'share_caption.dart'; export 'share_copyable_link.dart'; export 'share_heading.dart'; export 'share_preview_photo.dart'; export 'share_progress_overlay.dart'; export 'share_social_media_clarification.dart'; export 'share_state_listener.dart'; export 'share_subheading.dart'; export 'share_try_again_button.dart'; export 'twitter_button.dart';
photobooth/lib/share/widgets/widgets.dart/0
{ "file_path": "photobooth/lib/share/widgets/widgets.dart", "repo_id": "photobooth", "token_count": 193 }
1,160
import 'package:camera/camera.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; class MockCameraPlatform extends Mock with MockPlatformInterfaceMixin implements CameraPlatform {} class FakeCameraOptions extends Fake implements CameraOptions {} void main() { const textureId = 1; group('CameraController', () { late CameraPlatform platform; setUpAll(() { registerFallbackValue(FakeCameraOptions()); }); setUp(() { platform = MockCameraPlatform(); when(() => platform.init()).thenAnswer((_) async => {}); when(() => platform.create(any())).thenAnswer((_) async => textureId); CameraPlatform.instance = platform; }); test('initial state is uninitialized', () { final controller = CameraController(); expect(controller.value.status, equals(CameraStatus.uninitialized)); }); group('initialize', () { test('initializes textureId', () async { final controller = CameraController(); await controller.initialize(); expect(controller.textureId, equals(textureId)); }); test('initializes camera platform', () async { final controller = CameraController(); verifyNever(() => platform.init()); await controller.initialize(); verify(() => platform.init()).called(1); }); test('updates state to available on success', () async { final controller = CameraController(); await controller.initialize(); expect(controller.value.status, equals(CameraStatus.available)); }); test('updates state to unavailable on CameraException', () async { const exception = CameraUnknownException(); when(() => platform.create(any())).thenThrow(exception); final controller = CameraController(); await controller.initialize(); expect(controller.value.status, equals(CameraStatus.unavailable)); expect(controller.value.error, equals(exception)); }); test('updates state to unavailable on Exception', () async { final exception = Exception(); when(() => platform.create(any())).thenThrow(exception); final controller = CameraController(); await controller.initialize(); expect(controller.value.status, equals(CameraStatus.unavailable)); expect(controller.value.error, isA<CameraUnknownException>()); }); }); group('play', () { late CameraController controller; setUp(() async { controller = CameraController(); await controller.initialize(); }); test('invokes CameraPlatform.play', () { when(() => platform.play(any())).thenAnswer((_) async => {}); expect(controller.play(), completes); verify(() => platform.play(textureId)).called(1); }); }); group('stop', () { late CameraController controller; setUp(() async { controller = CameraController(); await controller.initialize(); }); test('invokes CameraPlatform.stop', () { when(() => platform.stop(any())).thenAnswer((_) async => {}); expect(controller.stop(), completes); verify(() => platform.stop(textureId)).called(1); }); }); group('takePicture', () { late CameraController controller; setUp(() async { controller = CameraController(); await controller.initialize(); }); test('invokes CameraPlatform.takePicture', () async { const image = CameraImage(data: '', width: 1, height: 1); when(() => platform.takePicture(any())).thenAnswer((_) async => image); expect(await controller.takePicture(), equals(image)); verify(() => platform.takePicture(textureId)).called(1); }); }); group('dispose', () { test('invokes CameraPlatform.dispose', () async { final controller = CameraController(); await controller.initialize(); when(() => platform.dispose(any())).thenAnswer((_) async => {}); await controller.dispose(); verify(() => platform.dispose(textureId)).called(1); expect(controller.value.status, equals(CameraStatus.uninitialized)); }); }); }); }
photobooth/packages/camera/camera/test/src/controller_test.dart/0
{ "file_path": "photobooth/packages/camera/camera/test/src/controller_test.dart", "repo_id": "photobooth", "token_count": 1533 }
1,161
@TestOn('chrome') library; import 'dart:html'; import 'package:camera_platform_interface/camera_platform_interface.dart'; import 'package:camera_web/camera_web.dart'; import 'package:flutter/widgets.dart' show Widget; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; class MockWindow extends Mock implements Window {} class MockNavigator extends Mock implements Navigator {} class MockMediaDevices extends Mock implements MediaDevices {} void main() { group('Camera', () { late int textureId; late Window window; late Navigator navigator; late MediaDevices mediaDevices; late VideoElement videoElement; setUp(() async { window = MockWindow(); navigator = MockNavigator(); mediaDevices = MockMediaDevices(); videoElement = VideoElement() ..src = 'https://www.w3schools.com/tags/mov_bbb.mp4' ..preload = 'true' ..width = 10 ..height = 10; when(() => window.navigator).thenReturn(navigator); when(() => navigator.mediaDevices).thenReturn(mediaDevices); when( () => mediaDevices.getUserMedia(any()), ).thenAnswer((_) async => videoElement.captureStream()); CameraPlatform.instance = CameraPlugin()..window = window; textureId = await CameraPlatform.instance.create(const CameraOptions()); }); testWidgets('$CameraPlugin is the live instance', (tester) async { expect(CameraPlatform.instance, isA<CameraPlugin>()); }); test('can init', () { expect(CameraPlatform.instance.init(), completes); }); test('can dispose', () { expect(CameraPlatform.instance.dispose(textureId), completes); }); test('can play', () async { expect(CameraPlatform.instance.play(textureId), completes); }); test('can stop', () async { expect(CameraPlatform.instance.stop(textureId), completes); }); test('can takePicture', () async { await CameraPlatform.instance.play(textureId); expect(CameraPlatform.instance.takePicture(textureId), completes); }); test('can build view', () { expect( CameraPlatform.instance.buildView(textureId), isInstanceOf<Widget>(), ); }); test('can getMediaDevices', () { expect(CameraPlatform.instance.getMediaDevices(), completes); }); test('can getDefaultDeviceId', () { expect(CameraPlatform.instance.getDefaultDeviceId(), completes); }); }); }
photobooth/packages/camera/camera_web/test/src/camera_web_test.dart/0
{ "file_path": "photobooth/packages/camera/camera_web/test/src/camera_web_test.dart", "repo_id": "photobooth", "token_count": 878 }
1,162
import 'package:platform_helper/platform_helper.dart'; // ignore: unnecessary_late late final _platformHelper = PlatformHelper(); /// Returns whether the current platform is running on a mobile device. bool get isMobile => _platformHelper.isMobile;
photobooth/packages/photobooth_ui/lib/src/platform/is_mobile.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/platform/is_mobile.dart", "repo_id": "photobooth", "token_count": 64 }
1,163
import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:platform_helper/platform_helper.dart'; /// {@template drag_update} /// Drag update model which includes the position and size. /// {@endtemplate} class DragUpdate { /// {@macro drag_update} const DragUpdate({ required this.angle, required this.position, required this.size, required this.constraints, }); /// The angle of the draggable asset. final double angle; /// The position of the draggable asset. final Offset position; /// The size of the draggable asset. final Size size; /// The constraints of the parent view. final Size constraints; } const _cornerDiameter = 15.0; const _floatingActionDiameter = 45.0; const _floatingActionPadding = 100.0; /// {@template draggable_resizable} /// A widget which allows a user to drag and resize the provided [child]. /// {@endtemplate} class DraggableResizable extends StatefulWidget { /// {@macro draggable_resizable} DraggableResizable({ required this.child, required this.size, BoxConstraints? constraints, this.onUpdate, this.onDelete, this.canTransform = false, PlatformHelper? platformHelper, super.key, }) : constraints = constraints ?? BoxConstraints.loose(Size.infinite), platformHelper = platformHelper ?? PlatformHelper(); /// The child which will be draggable/resizable. final Widget child; /// Drag/Resize value setter. final ValueSetter<DragUpdate>? onUpdate; /// Delete callback final VoidCallback? onDelete; /// Whether or not the asset can be dragged or resized. /// Defaults to false. final bool canTransform; /// The child's original size. final Size size; /// The child's constraints. /// Defaults to [BoxConstraints.loose(Size.infinite)]. final BoxConstraints constraints; /// Optional [PlatformHelper] instance. final PlatformHelper platformHelper; @override State<DraggableResizable> createState() => _DraggableResizableState(); } class _DraggableResizableState extends State<DraggableResizable> { late Size size; late BoxConstraints constraints; late double angle; late double angleDelta; late double baseAngle; bool get isTouchInputSupported => widget.platformHelper.isMobile; Offset position = Offset.zero; @override void initState() { super.initState(); size = widget.size; constraints = const BoxConstraints.expand(width: 1, height: 1); angle = 0; baseAngle = 0; angleDelta = 0; } @override Widget build(BuildContext context) { final aspectRatio = widget.size.width / widget.size.height; return LayoutBuilder( builder: (context, constraints) { position = position == Offset.zero ? Offset( constraints.maxWidth / 2 - (size.width / 2), constraints.maxHeight / 2 - (size.height / 2), ) : position; final normalizedWidth = size.width; final normalizedHeight = normalizedWidth / aspectRatio; final newSize = Size(normalizedWidth, normalizedHeight); if (widget.constraints.isSatisfiedBy(newSize)) size = newSize; final normalizedLeft = position.dx; final normalizedTop = position.dy; void onUpdate() { final normalizedPosition = Offset( normalizedLeft + (_floatingActionPadding / 2) + (_cornerDiameter / 2), normalizedTop + (_floatingActionPadding / 2) + (_cornerDiameter / 2), ); widget.onUpdate?.call( DragUpdate( position: normalizedPosition, size: size, constraints: Size(constraints.maxWidth, constraints.maxHeight), angle: angle, ), ); } void onDragTopLeft(Offset details) { final mid = (details.dx + details.dy) / 2; final newHeight = math.max<double>(size.height - (2 * mid), 0); final newWidth = math.max<double>(size.width - (2 * mid), 0); final updatedSize = Size(newWidth, newHeight); if (!widget.constraints.isSatisfiedBy(updatedSize)) return; final updatedPosition = Offset(position.dx + mid, position.dy + mid); setState(() { size = updatedSize; position = updatedPosition; }); onUpdate(); } void onDragTopRight(Offset details) { final mid = (details.dx + (details.dy * -1)) / 2; final newHeight = math.max<double>(size.height + (2 * mid), 0); final newWidth = math.max<double>(size.width + (2 * mid), 0); final updatedSize = Size(newWidth, newHeight); if (!widget.constraints.isSatisfiedBy(updatedSize)) return; final updatedPosition = Offset(position.dx - mid, position.dy - mid); setState(() { size = updatedSize; position = updatedPosition; }); onUpdate(); } void onDragBottomLeft(Offset details) { final mid = ((details.dx * -1) + details.dy) / 2; final newHeight = math.max<double>(size.height + (2 * mid), 0); final newWidth = math.max<double>(size.width + (2 * mid), 0); final updatedSize = Size(newWidth, newHeight); if (!widget.constraints.isSatisfiedBy(updatedSize)) return; final updatedPosition = Offset(position.dx - mid, position.dy - mid); setState(() { size = updatedSize; position = updatedPosition; }); onUpdate(); } void onDragBottomRight(Offset details) { final mid = (details.dx + details.dy) / 2; final newHeight = math.max<double>(size.height + (2 * mid), 0); final newWidth = math.max<double>(size.width + (2 * mid), 0); final updatedSize = Size(newWidth, newHeight); if (!widget.constraints.isSatisfiedBy(updatedSize)) return; final updatedPosition = Offset(position.dx - mid, position.dy - mid); setState(() { size = updatedSize; position = updatedPosition; }); onUpdate(); } final decoratedChild = Container( key: const Key('draggableResizable_child_container'), alignment: Alignment.center, height: normalizedHeight + _cornerDiameter + _floatingActionPadding, width: normalizedWidth + _cornerDiameter + _floatingActionPadding, child: Container( height: normalizedHeight, width: normalizedWidth, decoration: BoxDecoration( border: Border.all( width: 2, color: widget.canTransform ? PhotoboothColors.blue : PhotoboothColors.transparent, ), ), child: Center(child: widget.child), ), ); final topLeftCorner = _ResizePoint( key: const Key('draggableResizable_topLeft_resizePoint'), type: _ResizePointType.topLeft, onDrag: onDragTopLeft, ); final topRightCorner = _ResizePoint( key: const Key('draggableResizable_topRight_resizePoint'), type: _ResizePointType.topRight, onDrag: onDragTopRight, ); final bottomLeftCorner = _ResizePoint( key: const Key('draggableResizable_bottomLeft_resizePoint'), type: _ResizePointType.bottomLeft, onDrag: onDragBottomLeft, ); final bottomRightCorner = _ResizePoint( key: const Key('draggableResizable_bottomRight_resizePoint'), type: _ResizePointType.bottomRight, onDrag: onDragBottomRight, ); final deleteButton = _FloatingActionIcon( key: const Key('draggableResizable_delete_floatingActionIcon'), iconData: Icons.delete, onTap: widget.onDelete, ); final center = Offset( (_floatingActionDiameter + _cornerDiameter) / 2, (normalizedHeight / 2) + (_floatingActionDiameter / 2) + (_cornerDiameter / 2) + (_floatingActionPadding / 2), ); final rotateAnchor = GestureDetector( key: const Key('draggableResizable_rotate_gestureDetector'), onScaleStart: (details) { final offsetFromCenter = details.localFocalPoint - center; setState(() => angleDelta = baseAngle - offsetFromCenter.direction); }, onScaleUpdate: (details) { final offsetFromCenter = details.localFocalPoint - center; setState(() => angle = offsetFromCenter.direction + angleDelta); onUpdate(); }, onScaleEnd: (_) => setState(() => baseAngle = angle), child: _FloatingActionIcon( key: const Key('draggableResizable_rotate_floatingActionIcon'), iconData: Icons.rotate_90_degrees_ccw, onTap: () {}, ), ); if (this.constraints != constraints) { this.constraints = constraints; onUpdate(); } return Stack( children: <Widget>[ Positioned( top: normalizedTop, left: normalizedLeft, child: Transform( alignment: Alignment.center, transform: Matrix4.identity() ..scale(1.0) ..rotateZ(angle), child: _DraggablePoint( key: const Key('draggableResizable_child_draggablePoint'), onTap: onUpdate, onDrag: (d) { setState(() { position = Offset(position.dx + d.dx, position.dy + d.dy); }); onUpdate(); }, onScale: (s) { final updatedSize = Size( widget.size.width * s, widget.size.height * s, ); if (!widget.constraints.isSatisfiedBy(updatedSize)) return; final midX = position.dx + (size.width / 2); final midY = position.dy + (size.height / 2); final updatedPosition = Offset( midX - (updatedSize.width / 2), midY - (updatedSize.height / 2), ); setState(() { size = updatedSize; position = updatedPosition; }); onUpdate(); }, onRotate: (a) { setState(() => angle = a); onUpdate(); }, child: Stack( children: [ decoratedChild, if (widget.canTransform && widget.onDelete != null) Positioned( top: (normalizedHeight / 2) - (_floatingActionDiameter / 2) + (_cornerDiameter / 2) + (_floatingActionPadding / 2), left: normalizedWidth + (_floatingActionDiameter / 2) + (_floatingActionPadding / 2) - (_cornerDiameter / 2), child: deleteButton, ), if (widget.canTransform && !isTouchInputSupported) ...[ Positioned( top: _floatingActionPadding / 2, left: _floatingActionPadding / 2, child: topLeftCorner, ), Positioned( top: _floatingActionPadding / 2, left: normalizedWidth + _floatingActionPadding / 2, child: topRightCorner, ), Positioned( top: normalizedHeight + _floatingActionPadding / 2, left: _floatingActionPadding / 2, child: bottomLeftCorner, ), Positioned( top: normalizedHeight + _floatingActionPadding / 2, left: normalizedWidth + _floatingActionPadding / 2, child: bottomRightCorner, ), Positioned( top: 0, left: (normalizedWidth / 2) - (_floatingActionDiameter / 2) + (_cornerDiameter / 2) + (_floatingActionPadding / 2), child: rotateAnchor, ), ], ], ), ), ), ), ], ); }, ); } } enum _ResizePointType { topLeft, topRight, bottomLeft, bottomRight, } const _cursorLookup = <_ResizePointType, MouseCursor>{ _ResizePointType.topLeft: SystemMouseCursors.resizeUpLeft, _ResizePointType.topRight: SystemMouseCursors.resizeUpRight, _ResizePointType.bottomLeft: SystemMouseCursors.resizeDownLeft, _ResizePointType.bottomRight: SystemMouseCursors.resizeDownRight, }; class _ResizePoint extends StatelessWidget { const _ResizePoint({ required this.onDrag, required this.type, super.key, }); final ValueSetter<Offset> onDrag; final _ResizePointType type; MouseCursor get _cursor { return _cursorLookup[type]!; } @override Widget build(BuildContext context) { return MouseRegion( cursor: _cursor, child: _DraggablePoint( mode: _PositionMode.local, onDrag: onDrag, child: Container( width: _cornerDiameter, height: _cornerDiameter, decoration: BoxDecoration( border: Border.all(color: PhotoboothColors.blue, width: 2), shape: BoxShape.circle, ), child: Container( decoration: const BoxDecoration( color: PhotoboothColors.white, shape: BoxShape.circle, ), ), ), ), ); } } enum _PositionMode { local, global } class _DraggablePoint extends StatefulWidget { const _DraggablePoint({ required this.child, this.onDrag, this.onScale, this.onRotate, this.onTap, this.mode = _PositionMode.global, super.key, }); final Widget child; final _PositionMode mode; final ValueSetter<Offset>? onDrag; final ValueSetter<double>? onScale; final ValueSetter<double>? onRotate; final VoidCallback? onTap; @override _DraggablePointState createState() => _DraggablePointState(); } class _DraggablePointState extends State<_DraggablePoint> { late Offset initPoint; double baseScaleFactor = 1; double scaleFactor = 1; double baseAngle = 0; double angle = 0; @override Widget build(BuildContext context) { return GestureDetector( onTap: widget.onTap, onScaleStart: (details) { switch (widget.mode) { case _PositionMode.global: initPoint = details.focalPoint; break; case _PositionMode.local: initPoint = details.localFocalPoint; break; } if (details.pointerCount > 1) { baseAngle = angle; baseScaleFactor = scaleFactor; widget.onRotate?.call(baseAngle); widget.onScale?.call(baseScaleFactor); } }, onScaleUpdate: (details) { switch (widget.mode) { case _PositionMode.global: final dx = details.focalPoint.dx - initPoint.dx; final dy = details.focalPoint.dy - initPoint.dy; initPoint = details.focalPoint; widget.onDrag?.call(Offset(dx, dy)); break; case _PositionMode.local: final dx = details.localFocalPoint.dx - initPoint.dx; final dy = details.localFocalPoint.dy - initPoint.dy; initPoint = details.localFocalPoint; widget.onDrag?.call(Offset(dx, dy)); break; } if (details.pointerCount > 1) { scaleFactor = baseScaleFactor * details.scale; widget.onScale?.call(scaleFactor); angle = baseAngle + details.rotation; widget.onRotate?.call(angle); } }, child: widget.child, ); } } class _FloatingActionIcon extends StatelessWidget { const _FloatingActionIcon({ required this.iconData, this.onTap, super.key, }); final IconData iconData; final VoidCallback? onTap; @override Widget build(BuildContext context) { return Material( color: PhotoboothColors.white, clipBehavior: Clip.hardEdge, shape: const CircleBorder(), child: InkWell( onTap: onTap, child: SizedBox( height: _floatingActionDiameter, width: _floatingActionDiameter, child: Center( child: Icon( iconData, color: PhotoboothColors.blue, ), ), ), ), ); } }
photobooth/packages/photobooth_ui/lib/src/widgets/draggable_resizable.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/lib/src/widgets/draggable_resizable.dart", "repo_id": "photobooth", "token_count": 8444 }
1,164
import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; void main() { group('AnimatedFadeIn', () { testWidgets('fades in child', (tester) async { final key = UniqueKey(); final child = SizedBox(key: key); await tester.pumpWidget(AnimatedFadeIn(child: child)); var animatedOpacity = tester.widget<AnimatedOpacity>( find.byType(AnimatedOpacity), ); expect(animatedOpacity.opacity, equals(0.0)); await tester.pumpAndSettle(); animatedOpacity = tester.widget<AnimatedOpacity>( find.byType(AnimatedOpacity), ); expect(animatedOpacity.opacity, equals(1.0)); expect(find.byKey(key), findsOneWidget); }); }); }
photobooth/packages/photobooth_ui/test/src/widgets/animated_fade_in_test.dart/0
{ "file_path": "photobooth/packages/photobooth_ui/test/src/widgets/animated_fade_in_test.dart", "repo_id": "photobooth", "token_count": 323 }
1,165
include: package:very_good_analysis/analysis_options.yaml
photobooth/packages/photos_repository/analysis_options.yaml/0
{ "file_path": "photobooth/packages/photos_repository/analysis_options.yaml", "repo_id": "photobooth", "token_count": 16 }
1,166
// ignore_for_file: prefer_const_constructors import 'dart:convert'; import 'dart:ui' as ui; import 'package:bloc_test/bloc_test.dart'; import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/assets.g.dart'; import 'package:io_photobooth/footer/footer.dart'; import 'package:io_photobooth/photobooth/photobooth.dart'; import 'package:io_photobooth/stickers/stickers.dart'; import 'package:mocktail/mocktail.dart'; import 'package:photobooth_ui/photobooth_ui.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import '../../helpers/helpers.dart'; class MockCameraPlatform extends Mock with MockPlatformInterfaceMixin implements CameraPlatform {} class FakeCameraOptions extends Fake implements CameraOptions {} class MockImage extends Mock implements ui.Image {} class MockCameraImage extends Mock implements CameraImage {} class MockPhotoboothBloc extends MockBloc<PhotoboothEvent, PhotoboothState> implements PhotoboothBloc {} class FakePhotoboothEvent extends Fake implements PhotoboothEvent {} class FakePhotoboothState extends Fake implements PhotoboothState {} class FakeDragUpdate extends Fake implements DragUpdate {} void main() { setUpAll(() { registerFallbackValue(FakeCameraOptions()); registerFallbackValue(FakePhotoboothEvent()); registerFallbackValue(FakePhotoboothState()); registerFallbackValue(FakeDragUpdate()); }); const cameraId = 1; late CameraPlatform cameraPlatform; late CameraImage cameraImage; setUp(() { cameraImage = MockCameraImage(); cameraPlatform = MockCameraPlatform(); CameraPlatform.instance = cameraPlatform; when(() => cameraPlatform.buildView(any())).thenReturn(SizedBox()); when(() => cameraImage.width).thenReturn(4); when(() => cameraImage.height).thenReturn(3); when(() => cameraPlatform.init()).thenAnswer((_) async => {}); when( () => cameraPlatform.create(any()), ).thenAnswer((_) async => cameraId); when(() => cameraPlatform.play(any())).thenAnswer((_) async => {}); when(() => cameraPlatform.stop(any())).thenAnswer((_) async => {}); when(() => cameraPlatform.dispose(any())).thenAnswer((_) async => {}); when(() => cameraPlatform.takePicture(any())) .thenAnswer((_) async => cameraImage); }); group('PhotoboothPage', () { test('is routable', () { expect(PhotoboothPage.route(), isA<MaterialPageRoute<void>>()); }); testWidgets('displays a PhotoboothView', (tester) async { when(() => cameraPlatform.buildView(cameraId)).thenReturn(SizedBox()); await tester.pumpApp(PhotoboothPage()); await tester.pumpAndSettle(); expect(find.byType(PhotoboothView), findsOneWidget); }); }); group('PhotoboothView', () { late PhotoboothBloc photoboothBloc; setUp(() { photoboothBloc = MockPhotoboothBloc(); when(() => photoboothBloc.state).thenReturn(PhotoboothState()); }); testWidgets('renders Camera', (tester) async { await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); expect(find.byType(Camera), findsOneWidget); }); testWidgets('renders placeholder when initializing', (tester) async { await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); expect(find.byType(SizedBox), findsOneWidget); }); testWidgets('renders error when unavailable', (tester) async { when( () => cameraPlatform.create(any()), ).thenThrow(const CameraUnknownException()); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); expect(find.byType(PhotoboothError), findsOneWidget); verifyNever(() => cameraPlatform.play(any())); }); testWidgets( 'renders camera access denied error ' 'when cameraPlatform throws CameraNotAllowed exception', (tester) async { when( () => cameraPlatform.create(any()), ).thenThrow(const CameraNotAllowedException()); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); expect( find.byKey(Key('photoboothError_cameraAccessDenied')), findsOneWidget, ); verifyNever(() => cameraPlatform.play(any())); }); testWidgets( 'renders camera not found error ' 'when cameraPlatform throws CameraNotFound exception', (tester) async { when( () => cameraPlatform.create(any()), ).thenThrow(const CameraNotFoundException()); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); expect( find.byKey(Key('photoboothError_cameraNotFound')), findsOneWidget, ); verifyNever(() => cameraPlatform.play(any())); }); testWidgets( 'renders camera not supported error ' 'when cameraPlatform throws CameraNotSupported exception', (tester) async { when( () => cameraPlatform.create(any()), ).thenThrow(const CameraNotSupportedException()); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); expect( find.byKey(Key('photoboothError_cameraNotSupported')), findsOneWidget, ); verifyNever(() => cameraPlatform.play(any())); }); testWidgets( 'renders unknown error ' 'when cameraPlatform throws CameraUnknownException exception', (tester) async { when( () => cameraPlatform.create(any()), ).thenThrow(const CameraUnknownException()); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); expect( find.byKey(Key('photoboothError_unknown')), findsOneWidget, ); verifyNever(() => cameraPlatform.play(any())); }); testWidgets('renders error when not allowed', (tester) async { when( () => cameraPlatform.create(any()), ).thenThrow(const CameraNotAllowedException()); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); expect(find.byType(PhotoboothError), findsOneWidget); verifyNever(() => cameraPlatform.play(any())); }); testWidgets('renders preview when available', (tester) async { const key = Key('__target__'); const preview = SizedBox(key: key); when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); expect(find.byType(PhotoboothPreview), findsOneWidget); expect(find.byKey(key), findsOneWidget); }); testWidgets('renders landscape camera when orientation is landscape', (tester) async { when(() => cameraPlatform.buildView(cameraId)).thenReturn(SizedBox()); tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 400)); await tester.pumpApp(PhotoboothPage()); await tester.pumpAndSettle(); final aspectRatio = tester.widget<AspectRatio>(find.byType(AspectRatio)); expect(aspectRatio.aspectRatio, equals(PhotoboothAspectRatio.landscape)); }); testWidgets( 'adds PhotoCaptured with landscape aspect ratio ' 'when photo is snapped', (tester) async { const preview = SizedBox(); final image = CameraImage( data: 'data:image/png,${base64.encode(transparentImage)}', width: 1280, height: 720, ); tester.setDisplaySize(const Size(PhotoboothBreakpoints.large, 400)); when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview); when( () => cameraPlatform.takePicture(cameraId), ).thenAnswer((_) async => image); when(() => photoboothBloc.state).thenReturn( PhotoboothState(image: image), ); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); final photoboothPreview = tester.widget<PhotoboothPreview>( find.byType(PhotoboothPreview), ); photoboothPreview.onSnapPressed(); await tester.pumpAndSettle(); verify( () => photoboothBloc.add( PhotoCaptured( aspectRatio: PhotoboothAspectRatio.landscape, image: image, ), ), ).called(1); }); testWidgets('renders portrait camera when orientation is portrait', (tester) async { when(() => cameraPlatform.buildView(cameraId)).thenReturn(SizedBox()); tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000)); await tester.pumpApp(PhotoboothPage()); await tester.pumpAndSettle(); final aspectRatio = tester.widget<AspectRatio>(find.byType(AspectRatio)); expect(aspectRatio.aspectRatio, equals(PhotoboothAspectRatio.portrait)); }); testWidgets( 'adds PhotoCaptured with portrait aspect ratio ' 'when photo is snapped', (tester) async { const preview = SizedBox(); final image = CameraImage( data: 'data:image/png,${base64.encode(transparentImage)}', width: 1280, height: 720, ); tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000)); when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview); when( () => cameraPlatform.takePicture(cameraId), ).thenAnswer((_) async => image); when(() => photoboothBloc.state).thenReturn( PhotoboothState(image: image), ); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); final photoboothPreview = tester.widget<PhotoboothPreview>( find.byType(PhotoboothPreview), ); photoboothPreview.onSnapPressed(); await tester.pumpAndSettle(); verify( () => photoboothBloc.add( PhotoCaptured( aspectRatio: PhotoboothAspectRatio.portrait, image: image, ), ), ).called(1); }); testWidgets('navigates to StickersPage when photo is taken', (tester) async { const preview = SizedBox(); final image = CameraImage( data: 'data:image/png,${base64.encode(transparentImage)}', width: 1280, height: 720, ); tester.setDisplaySize(const Size(2500, 2500)); when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview); when( () => cameraPlatform.takePicture(cameraId), ).thenAnswer((_) async => image); when(() => photoboothBloc.state).thenReturn( PhotoboothState(image: image), ); await tester.pumpApp(PhotoboothView(), photoboothBloc: photoboothBloc); await tester.pumpAndSettle(); final photoboothPreview = tester.widget<PhotoboothPreview>( find.byType(PhotoboothPreview), ); photoboothPreview.onSnapPressed(); await tester.pumpAndSettle(); expect(find.byType(StickersPage), findsOneWidget); }); }); group('PhotoboothPreview', () { late PhotoboothBloc photoboothBloc; setUp(() { photoboothBloc = MockPhotoboothBloc(); when(() => photoboothBloc.state).thenReturn(PhotoboothState()); }); testWidgets('renders dash, sparky, dino, and android buttons', (tester) async { const key = Key('__target__'); const preview = SizedBox(key: key); when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); expect(find.byType(CharacterIconButton), findsNWidgets(4)); }); testWidgets('renders FlutterIconLink', (tester) async { const key = Key('__target__'); const preview = SizedBox(key: key); when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); expect(find.byType(FlutterIconLink), findsOneWidget); }); testWidgets('renders FirebaseIconLink', (tester) async { const key = Key('__target__'); const preview = SizedBox(key: key); when(() => cameraPlatform.buildView(cameraId)).thenReturn(preview); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); expect(find.byType(FirebaseIconLink), findsOneWidget); }); testWidgets('renders only android when only android is selected', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.android)], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); expect( find.byKey( const Key('photoboothPreview_android_draggableResizableAsset'), ), findsOneWidget, ); expect(find.byType(AnimatedAndroid), findsOneWidget); }); testWidgets('adds PhotoCharacterDragged when dragged', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.android)], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); await tester.drag( find.byKey( const Key('photoboothPreview_android_draggableResizableAsset'), ), Offset(10, 10), warnIfMissed: false, ); verify( () => photoboothBloc.add(any(that: isA<PhotoCharacterDragged>())), ); }); testWidgets('renders only dash when only dash is selected', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dash)], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); expect( find.byKey(const Key('photoboothPreview_dash_draggableResizableAsset')), findsOneWidget, ); expect(find.byType(AnimatedDash), findsOneWidget); }); testWidgets('adds PhotoCharacterDragged when dragged', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dash)], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); await tester.drag( find.byKey(const Key('photoboothPreview_dash_draggableResizableAsset')), Offset(10, 10), warnIfMissed: false, ); verify( () => photoboothBloc.add(any(that: isA<PhotoCharacterDragged>())), ); }); testWidgets('renders only sparky when only sparky is selected', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [ PhotoAsset(id: '0', asset: Assets.sparky), ], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); expect( find.byKey( const Key('photoboothPreview_sparky_draggableResizableAsset'), ), findsOneWidget, ); expect(find.byType(AnimatedSparky), findsOneWidget); }); testWidgets('renders only dino when only dino is selected', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.dino)], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); expect( find.byKey( const Key('photoboothPreview_dino_draggableResizableAsset'), ), findsOneWidget, ); expect(find.byType(AnimatedDino), findsOneWidget); }); testWidgets('adds PhotoCharacterDragged when dragged', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.sparky)], ), ); const preview = SizedBox(); tester.setDisplaySize(Size(2500, 2500)); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); await tester.drag( find.byKey( const Key('photoboothPreview_sparky_draggableResizableAsset'), ), Offset(10, 10), warnIfMissed: false, ); verify( () => photoboothBloc.add(any(that: isA<PhotoCharacterDragged>())), ); }); testWidgets('renders dash, sparky, dino, and android when all are selected', (tester) async { when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [ PhotoAsset(id: '0', asset: Assets.android), PhotoAsset(id: '1', asset: Assets.dash), PhotoAsset(id: '2', asset: Assets.sparky), PhotoAsset(id: '3', asset: Assets.dino), ], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); expect(find.byType(DraggableResizable), findsNWidgets(4)); expect(find.byType(AnimatedAndroid), findsOneWidget); expect(find.byType(AnimatedDash), findsOneWidget); expect(find.byType(AnimatedDino), findsOneWidget); expect(find.byType(AnimatedSparky), findsOneWidget); }); testWidgets( 'displays a LandscapeCharactersIconLayout ' 'when orientation is landscape', (tester) async { tester.setDisplaySize(landscapeDisplaySize); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview( preview: preview, onSnapPressed: () {}, ), ), ); await tester.pumpAndSettle(); expect(find.byType(LandscapeCharactersIconLayout), findsOneWidget); }); testWidgets( 'displays a PortraitCharactersIconLayout ' 'when orientation is portrait', (tester) async { tester.setDisplaySize(portraitDisplaySize); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); expect(find.byType(PortraitCharactersIconLayout), findsOneWidget); }); testWidgets('tapping on dash button adds PhotoCharacterToggled', (tester) async { const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); await tester.tap( find.byKey( const Key('photoboothView_dash_characterIconButton'), ), ); expect(tester.takeException(), isNull); verify( () => photoboothBloc.add( PhotoCharacterToggled(character: Assets.dash), ), ).called(1); }); testWidgets('tapping on sparky button adds PhotoCharacterToggled', (tester) async { const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); await tester.tap( find.byKey( const Key('photoboothView_sparky_characterIconButton'), ), ); expect(tester.takeException(), isNull); verify( () => photoboothBloc.add( PhotoCharacterToggled(character: Assets.sparky), ), ).called(1); }); testWidgets('tapping on android button adds PhotoCharacterToggled', (tester) async { const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); await tester.tap( find.byKey( const Key('photoboothView_android_characterIconButton'), ), ); expect(tester.takeException(), isNull); verify( () => photoboothBloc.add( PhotoCharacterToggled(character: Assets.android), ), ).called(1); }); testWidgets('tapping on dino button adds PhotoCharacterToggled', (tester) async { const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); await tester.tap( find.byKey( const Key('photoboothView_dino_characterIconButton'), ), ); expect(tester.takeException(), isNull); verify( () => photoboothBloc.add( PhotoCharacterToggled(character: Assets.dino), ), ).called(1); }); testWidgets('tapping on background adds PhotoTapped', (tester) async { const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); await tester.tap( find.byKey( const Key('photoboothPreview_background_gestureDetector'), ), ); expect(tester.takeException(), isNull); verify(() => photoboothBloc.add(PhotoTapped())).called(1); }); testWidgets( 'renders CharactersCaption on mobile when no character is selected', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000)); when(() => photoboothBloc.state).thenReturn(PhotoboothState()); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pumpAndSettle(); expect(find.byType(CharactersCaption), findsOneWidget); }); testWidgets( 'does not render CharactersCaption on mobile when ' 'any character is selected', (tester) async { tester.setDisplaySize(const Size(PhotoboothBreakpoints.small, 1000)); when(() => photoboothBloc.state).thenReturn( PhotoboothState( characters: const [PhotoAsset(id: '0', asset: Assets.android)], ), ); const preview = SizedBox(); await tester.pumpApp( BlocProvider.value( value: photoboothBloc, child: PhotoboothPreview(preview: preview, onSnapPressed: () {}), ), ); await tester.pump(); expect(find.byType(CharactersCaption), findsNothing); }); }); }
photobooth/test/photobooth/view/photobooth_page_test.dart/0
{ "file_path": "photobooth/test/photobooth/view/photobooth_page_test.dart", "repo_id": "photobooth", "token_count": 10538 }
1,167
// ignore_for_file: prefer_const_constructors import 'dart:typed_data'; import 'package:cross_file/cross_file.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_photobooth/share/share.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; void main() { const shareUrl = 'http://share-url.com'; final bytes = Uint8List.fromList([]); late ShareBloc shareBloc; setUpAll(() { registerFallbackValue(FakeShareEvent()); registerFallbackValue(FakeShareState()); }); setUp(() { shareBloc = MockShareBloc(); when(() => shareBloc.state).thenReturn(ShareState()); }); group('FacebookButton', () { testWidgets('pops when tapped', (tester) async { await tester.pumpApp(FacebookButton(), shareBloc: shareBloc); await tester.tap(find.byType(FacebookButton)); await tester.pumpAndSettle(); expect(find.byType(FacebookButton), findsNothing); }); testWidgets('adds ShareOnFacebook event when tapped', (tester) async { await tester.pumpApp(FacebookButton(), shareBloc: shareBloc); await tester.tap(find.byType(FacebookButton)); await tester.pumpAndSettle(); verify(() => shareBloc.add(ShareOnFacebookTapped())).called(1); }); testWidgets( 'does not add ShareOnFacebook event ' 'when tapped but state is upload success', (tester) async { when(() => shareBloc.state).thenReturn( ShareState( compositeStatus: ShareStatus.success, uploadStatus: ShareStatus.success, file: XFile.fromData(bytes), bytes: bytes, twitterShareUrl: shareUrl, facebookShareUrl: shareUrl, ), ); await tester.pumpApp(FacebookButton(), shareBloc: shareBloc); await tester.tap(find.byType(FacebookButton)); await tester.pumpAndSettle(); verifyNever(() => shareBloc.add(any())); }); }); }
photobooth/test/share/widgets/facebook_button_test.dart/0
{ "file_path": "photobooth/test/share/widgets/facebook_button_test.dart", "repo_id": "photobooth", "token_count": 756 }
1,168
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pinball/assets_manager/assets_manager.dart'; import 'package:pinball/gen/gen.dart'; import 'package:pinball/l10n/l10n.dart'; import 'package:pinball_ui/pinball_ui.dart'; /// {@template assets_loading_page} /// Widget used to indicate the loading progress of the different assets used /// in the game /// {@endtemplate} class AssetsLoadingPage extends StatelessWidget { /// {@macro assets_loading_page} const AssetsLoadingPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final l10n = context.l10n; final headline1 = Theme.of(context).textTheme.headline1; return Container( decoration: const CrtBackground(), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Assets.images.loadingGame.ioPinball.image(), ), const SizedBox(height: 40), AnimatedEllipsisText( l10n.loading, style: headline1, ), const SizedBox(height: 40), FractionallySizedBox( widthFactor: 0.8, child: BlocBuilder<AssetsManagerCubit, AssetsManagerState>( builder: (context, state) { return PinballLoadingIndicator(value: state.progress); }, ), ), ], ), ), ); } }
pinball/lib/assets_manager/views/assets_loading_page.dart/0
{ "file_path": "pinball/lib/assets_manager/views/assets_loading_page.dart", "repo_id": "pinball", "token_count": 718 }
1,169
part of 'game_bloc.dart'; @immutable abstract class GameEvent extends Equatable { const GameEvent(); } /// {@template round_lost_game_event} /// Event added when a user drops all balls off the screen and loses a round. /// {@endtemplate} class RoundLost extends GameEvent { /// {@macro round_lost_game_event} const RoundLost(); @override List<Object?> get props => []; } /// {@template scored_game_event} /// Event added when a user increases their score. /// {@endtemplate} class Scored extends GameEvent { /// {@macro scored_game_event} const Scored({ required this.points, }) : assert(points > 0, 'Points must be greater than 0'); final int points; @override List<Object?> get props => [points]; } class BonusActivated extends GameEvent { const BonusActivated(this.bonus); final GameBonus bonus; @override List<Object?> get props => [bonus]; } /// {@template multiplier_increased_game_event} /// Added when a multiplier is gained. /// {@endtemplate} class MultiplierIncreased extends GameEvent { /// {@macro multiplier_increased_game_event} const MultiplierIncreased(); @override List<Object?> get props => []; } class GameStarted extends GameEvent { const GameStarted(); @override List<Object?> get props => []; } class GameOver extends GameEvent { const GameOver(); @override List<Object?> get props => []; }
pinball/lib/game/bloc/game_event.dart/0
{ "file_path": "pinball/lib/game/bloc/game_event.dart", "repo_id": "pinball", "token_count": 432 }
1,170