text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
{ "scriptCategory": "dense", "timeOfDayFormat": "a h:mm", "openAppDrawerTooltip": "탐색 메뉴 열기", "backButtonTooltip": "뒤로", "closeButtonTooltip": "닫기", "deleteButtonTooltip": "삭제", "nextMonthTooltip": "다음 달", "previousMonthTooltip": "지난달", "nextPageTooltip": "다음 페이지", "previousPageTooltip": "이전 페이지", "firstPageTooltip": "첫 페이지", "lastPageTooltip": "마지막 페이지", "showMenuTooltip": "메뉴 표시", "aboutListTileTitle": "$applicationName 정보", "licensesPageTitle": "라이선스", "pageRowsInfoTitle": "$rowCount행 중 $firstRow~$lastRow행", "pageRowsInfoTitleApproximate": "약 $rowCount행 중 $firstRow~$lastRow행", "rowsPerPageTitle": "페이지당 행 수:", "tabLabel": "탭 $tabCount개 중 $tabIndex번째", "selectedRowCountTitleOne": "항목 1개 선택됨", "selectedRowCountTitleOther": "항목 $selectedRowCount개 선택됨", "cancelButtonLabel": "취소", "closeButtonLabel": "닫기", "continueButtonLabel": "계속", "copyButtonLabel": "복사", "cutButtonLabel": "잘라냄", "scanTextButtonLabel": "텍스트 스캔", "okButtonLabel": "확인", "pasteButtonLabel": "붙여넣기", "selectAllButtonLabel": "전체 선택", "viewLicensesButtonLabel": "라이선스 보기", "anteMeridiemAbbreviation": "오전", "postMeridiemAbbreviation": "오후", "timePickerHourModeAnnouncement": "시간 선택", "timePickerMinuteModeAnnouncement": "분 선택", "signedInLabel": "로그인됨", "hideAccountsLabel": "계정 숨기기", "showAccountsLabel": "계정 표시", "modalBarrierDismissLabel": "닫기", "drawerLabel": "탐색 메뉴", "popupMenuLabel": "팝업 메뉴", "dialogLabel": "대화상자", "alertDialogLabel": "알림", "searchFieldLabel": "검색", "reorderItemToStart": "시작으로 이동", "reorderItemToEnd": "끝으로 이동", "reorderItemUp": "위로 이동", "reorderItemDown": "아래로 이동", "reorderItemLeft": "왼쪽으로 이동", "reorderItemRight": "오른쪽으로 이동", "expandedIconTapHint": "접기", "collapsedIconTapHint": "펼치기", "remainingTextFieldCharacterCountOne": "1자 남음", "remainingTextFieldCharacterCountOther": "$remainingCount자 남음", "refreshIndicatorSemanticLabel": "새로고침", "moreButtonTooltip": "더보기", "dateSeparator": ".", "dateHelpText": "yyyy.mm.dd", "selectYearSemanticsLabel": "연도 선택", "unspecifiedDate": "날짜", "unspecifiedDateRange": "기간", "dateInputLabel": "날짜 입력", "dateRangeStartLabel": "시작일", "dateRangeEndLabel": "종료일", "dateRangeStartDateSemanticLabel": "시작일 $fullDate", "dateRangeEndDateSemanticLabel": "종료일 $fullDate", "invalidDateFormatLabel": "형식이 잘못되었습니다.", "invalidDateRangeLabel": "날짜 범위가 잘못되었습니다.", "dateOutOfRangeLabel": "범위를 벗어났습니다.", "saveButtonLabel": "저장", "datePickerHelpText": "날짜 선택", "dateRangePickerHelpText": "기간 선택", "calendarModeButtonLabel": "캘린더 모드로 전환", "inputDateModeButtonLabel": "입력 모드로 전환", "timePickerDialHelpText": "시간 선택", "timePickerInputHelpText": "시간 입력", "timePickerHourLabel": "시간", "timePickerMinuteLabel": "분", "invalidTimeLabel": "유효한 시간을 입력하세요.", "dialModeButtonLabel": "다이얼 선택 모드로 전환", "inputTimeModeButtonLabel": "텍스트 입력 모드로 전환", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "라이선스 1개", "licensesPackageDetailTextOther": "라이선스 $licenseCount개", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "백스페이스", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "채널 아래로", "keyboardKeyChannelUp": "채널 위로", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "꺼내기", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "메타", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PageUp", "keyboardKeyPower": "전원", "keyboardKeyPowerOff": "종료", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "선택", "keyboardKeySpace": "스페이스", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "메뉴 바 메뉴", "currentDateLabel": "오늘", "scrimLabel": "스크림", "bottomSheetLabel": "하단 시트", "scrimOnTapHint": "$modalRouteContentName 닫기", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "두 번 탭하여 접기", "expansionTileCollapsedHint": "두 번 탭하여 펼치기", "expansionTileExpandedTapHint": "접기", "expansionTileCollapsedTapHint": "자세히 알아보려면 펼치기", "expandedHint": "접힘", "collapsedHint": "펼침", "menuDismissLabel": "메뉴 닫기", "lookUpButtonLabel": "찾기", "searchWebButtonLabel": "웹 검색", "shareButtonLabel": "공유...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_ko.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ko.arb", "repo_id": "flutter", "token_count": 3016 }
725
{ "scriptCategory": "tall", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "ਨੈਵੀਗੇਸ਼ਨ ਮੀਨੂ ਖੋਲ੍ਹੋ", "backButtonTooltip": "ਪਿੱਛੇ", "closeButtonTooltip": "ਬੰਦ ਕਰੋ", "deleteButtonTooltip": "ਮਿਟਾਓ", "nextMonthTooltip": "ਅਗਲਾ ਮਹੀਨਾ", "previousMonthTooltip": "ਪਿਛਲਾ ਮਹੀਨਾ", "nextPageTooltip": "ਅਗਲਾ ਪੰਨਾ", "previousPageTooltip": "ਪਿਛਲਾ ਪੰਨਾ", "firstPageTooltip": "ਪਹਿਲਾ ਪੰਨਾ", "lastPageTooltip": "ਆਖਰੀ ਪੰਨਾ", "showMenuTooltip": "ਮੀਨੂ ਦਿਖਾਓ", "aboutListTileTitle": "$applicationName ਬਾਰੇ", "licensesPageTitle": "ਲਾਇਸੰਸ", "pageRowsInfoTitle": "$rowCount ਵਿੱਚੋਂ $firstRow–$lastRow", "pageRowsInfoTitleApproximate": "ਲਗਭਗ $rowCount ਵਿੱਚੋਂ $firstRow–$lastRow", "rowsPerPageTitle": "ਹਰ ਪੰਨੇ 'ਤੇ ਕਤਾਰਾਂ:", "tabLabel": "$tabCount ਵਿੱਚੋਂ $tabIndex ਟੈਬ", "selectedRowCountTitleOne": "1 ਆਈਟਮ ਚੁਣੀ ਗਈ", "selectedRowCountTitleOther": "$selectedRowCount ਆਈਟਮਾਂ ਚੁਣੀਆਂ ਗਈਆਂ", "cancelButtonLabel": "ਰੱਦ ਕਰੋ", "closeButtonLabel": "ਬੰਦ ਕਰੋ", "continueButtonLabel": "ਜਾਰੀ ਰੱਖੋ", "copyButtonLabel": "ਕਾਪੀ ਕਰੋ", "cutButtonLabel": "ਕੱਟ ਕਰੋ", "scanTextButtonLabel": "ਲਿਖਤ ਨੂੰ ਸਕੈਨ ਕਰੋ", "okButtonLabel": "ਠੀਕ ਹੈ", "pasteButtonLabel": "ਪੇਸਟ ਕਰੋ", "selectAllButtonLabel": "ਸਭ ਚੁਣੋ", "viewLicensesButtonLabel": "ਲਾਇਸੰਸ ਦੇਖੋ", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "ਘੰਟੇ ਚੁਣੋ", "timePickerMinuteModeAnnouncement": "ਮਿੰਟ ਚੁਣੋ", "modalBarrierDismissLabel": "ਖਾਰਜ ਕਰੋ", "signedInLabel": "ਸਾਈਨ-ਇਨ ਕੀਤਾ ਗਿਆ", "hideAccountsLabel": "ਖਾਤੇ ਲੁਕਾਓ", "showAccountsLabel": "ਖਾਤੇ ਦਿਖਾਓ", "drawerLabel": "ਨੈਵੀਗੇਸ਼ਨ ਮੀਨੂ", "popupMenuLabel": "ਪੌਪਅੱਪ ਮੀਨੂ", "dialogLabel": "ਵਿੰਡੋ", "alertDialogLabel": "ਸੁਚੇਤਨਾ", "searchFieldLabel": "ਖੋਜੋ", "reorderItemToStart": "ਸ਼ੁਰੂ ਵਿੱਚ ਲਿਜਾਓ", "reorderItemToEnd": "ਅੰਤ ਵਿੱਚ ਲਿਜਾਓ", "reorderItemUp": "ਉੱਪਰ ਲਿਜਾਓ", "reorderItemDown": "ਹੇਠਾਂ ਲਿਜਾਓ", "reorderItemLeft": "ਖੱਬੇ ਲਿਜਾਓ", "reorderItemRight": "ਸੱਜੇ ਲਿਜਾਓ", "expandedIconTapHint": "ਸਮੇਟੋ", "collapsedIconTapHint": "ਵਿਸਤਾਰ ਕਰੋ", "remainingTextFieldCharacterCountOne": "1 ਅੱਖਰ-ਚਿੰਨ੍ਹ ਬਾਕੀ", "remainingTextFieldCharacterCountOther": "$remainingCount ਅੱਖਰ-ਚਿੰਨ੍ਹ ਬਾਕੀ", "refreshIndicatorSemanticLabel": "ਰਿਫ੍ਰੈਸ਼ ਕਰੋ", "moreButtonTooltip": "ਹੋਰ", "dateSeparator": "/", "dateHelpText": "mm/dd/yyyy", "selectYearSemanticsLabel": "ਸਾਲ ਚੁਣੋ", "unspecifiedDate": "ਤਾਰੀਖ", "unspecifiedDateRange": "ਤਾਰੀਖ ਦੀ ਰੇਂਜ", "dateInputLabel": "ਤਾਰੀਖ ਦਾਖਲ ਕਰੋ", "dateRangeStartLabel": "ਸ਼ੁਰੂਆਤੀ ਤਾਰੀਖ", "dateRangeEndLabel": "ਸਮਾਪਤੀ ਦੀ ਤਾਰੀਖ", "dateRangeStartDateSemanticLabel": "ਸ਼ੁਰੂਆਤੀ ਤਾਰੀਖ $fullDate", "dateRangeEndDateSemanticLabel": "ਸਮਾਪਤੀ ਦੀ ਤਾਰੀਖ $fullDate", "invalidDateFormatLabel": "ਅਵੈਧ ਫਾਰਮੈਟ।", "invalidDateRangeLabel": "ਅਵੈਧ ਰੇਂਜ।", "dateOutOfRangeLabel": "ਰੇਂਜ-ਤੋਂ-ਬਾਹਰ।", "saveButtonLabel": "ਰੱਖਿਅਤ ਕਰੋ", "datePickerHelpText": "ਤਾਰੀਖ ਚੁਣੋ", "dateRangePickerHelpText": "ਰੇਂਜ ਚੁਣੋ", "calendarModeButtonLabel": "ਕੈਲੰਡਰ 'ਤੇ ਜਾਓ", "inputDateModeButtonLabel": "ਇਨਪੁੱਟ 'ਤੇ ਜਾਓ", "timePickerDialHelpText": "ਸਮਾਂ ਚੁਣੋ", "timePickerInputHelpText": "ਸਮਾਂ ਦਾਖਲ ਕਰੋ", "timePickerHourLabel": "ਘੰਟਾ", "timePickerMinuteLabel": "ਮਿੰਟ", "invalidTimeLabel": "ਵੈਧ ਸਮਾਂ ਦਾਖਲ ਕਰੋ", "dialModeButtonLabel": "ਡਾਇਲ ਚੋਣਕਾਰ ਮੋਡ 'ਤੇ ਜਾਓ", "inputTimeModeButtonLabel": "ਲਿਖਤ ਇਨਪੁੱਟ ਮੋਡ 'ਤੇ ਜਾਓ", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 ਲਾਇਸੰਸ", "licensesPackageDetailTextOther": "$licenseCount ਲਾਇਸੰਸ", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "ਮੀਨੂ ਬਾਰ ਮੀਨੂ", "currentDateLabel": "ਅੱਜ", "scrimLabel": "ਸਕ੍ਰਿਮ", "bottomSheetLabel": "ਹੇਠਲੀ ਸ਼ੀਟ", "scrimOnTapHint": "$modalRouteContentName ਨੂੰ ਬੰਦ ਕਰੋ", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "ਸਮੇਟਣ ਲਈ ਡਬਲ ਟੈਪ ਕਰੋ", "expansionTileCollapsedHint": "ਵਿਸਤਾਰ ਕਰਨ ਲਈ ਡਬਲ ਟੈਪ ਕਰੋ", "expansionTileExpandedTapHint": "ਸਮੇਟੋ", "expansionTileCollapsedTapHint": "ਹੋਰ ਵੇਰਵਿਆਂ ਲਈ ਵਿਸਤਾਰ ਕਰੋ", "expandedHint": "ਸਮੇਟਿਆ ਗਿਆ", "collapsedHint": "ਵਿਸਤਾਰ ਕੀਤਾ ਗਿਆ", "menuDismissLabel": "ਮੀਨੂ ਖਾਰਜ ਕਰੋ", "lookUpButtonLabel": "ਖੋਜੋ", "searchWebButtonLabel": "ਵੈੱਬ 'ਤੇ ਖੋਜੋ", "shareButtonLabel": "ਸਾਂਝਾ ਕਰੋ...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_pa.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_pa.arb", "repo_id": "flutter", "token_count": 3538 }
726
{ "scriptCategory": "tall", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "నావిగేషన్ మెనూను తెరువు", "backButtonTooltip": "వెనుకకు", "closeButtonTooltip": "మూసివేయి", "deleteButtonTooltip": "తొలగించండి", "nextMonthTooltip": "తర్వాత నెల", "previousMonthTooltip": "మునుపటి నెల", "nextPageTooltip": "తర్వాత పేజీ", "previousPageTooltip": "మునుపటి పేజీ", "firstPageTooltip": "మొదటి పేజీ", "lastPageTooltip": "చివరి పేజీ", "showMenuTooltip": "మెనూను చూపు", "aboutListTileTitle": "$applicationName గురించి", "licensesPageTitle": "లైసెన్స్‌లు", "pageRowsInfoTitle": "$rowCountలో $firstRow - $lastRow", "pageRowsInfoTitleApproximate": "$rowCountలో $firstRow–$lastRow", "rowsPerPageTitle": "పేజీకి ఉండే అడ్డు వరుసలు:", "tabLabel": "$tabCountలో $tabIndexవ ట్యాబ్", "selectedRowCountTitleOne": "1 అంశం ఎంచుకోబడింది", "selectedRowCountTitleOther": "$selectedRowCount అంశాలు ఎంచుకోబడ్డాయి", "cancelButtonLabel": "రద్దు చేయండి", "closeButtonLabel": "మూసివేయండి", "continueButtonLabel": "కొనసాగించండి", "copyButtonLabel": "కాపీ చేయి", "scanTextButtonLabel": "టెక్స్ట్‌ను స్కాన్ చేయండి", "cutButtonLabel": "కత్తిరించండి", "okButtonLabel": "సరే", "pasteButtonLabel": "పేస్ట్ చేయండి", "selectAllButtonLabel": "అన్నింటినీ ఎంచుకోండి", "viewLicensesButtonLabel": "లైసెన్స్‌లను చూడండి", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "గంటలను ఎంచుకోండి", "timePickerMinuteModeAnnouncement": "నిమిషాలను ఎంచుకోండి", "modalBarrierDismissLabel": "విస్మరించు", "signedInLabel": "సైన్ ఇన్ చేశారు", "hideAccountsLabel": "ఖాతాలను దాచు", "showAccountsLabel": "ఖాతాలను చూపు", "drawerLabel": "నావిగేషన్ మెనూ", "popupMenuLabel": "పాప్‌అప్ మెనూ", "dialogLabel": "డైలాగ్", "alertDialogLabel": "అలర్ట్", "searchFieldLabel": "వెతకండి", "reorderItemToStart": "ప్రారంభానికి తరలించండి", "reorderItemToEnd": "చివరకు తరలించండి", "reorderItemUp": "పైకి జరపండి", "reorderItemDown": "కిందికు జరుపు", "reorderItemLeft": "ఎడమవైపుగా జరపండి", "reorderItemRight": "కుడివైపుగా జరపండి", "expandedIconTapHint": "కుదించు", "collapsedIconTapHint": "విస్తరించు", "remainingTextFieldCharacterCountOne": "1 అక్షరం మిగిలి ఉంది", "remainingTextFieldCharacterCountOther": "$remainingCount అక్షరాలు మిగిలి ఉన్నాయి", "refreshIndicatorSemanticLabel": "రిఫ్రెష్ చేయండి", "moreButtonTooltip": "మరిన్ని", "dateSeparator": "/", "dateHelpText": "mm/dd/yyyy", "selectYearSemanticsLabel": "సంవత్సరాన్ని ఎంచుకోండి", "unspecifiedDate": "తేదీ", "unspecifiedDateRange": "తేదీల పరిధి", "dateInputLabel": "తేదీని ఎంటర్ చేయండి", "dateRangeStartLabel": "ప్రారంభ తేదీ", "dateRangeEndLabel": "ముగింపు తేదీ", "dateRangeStartDateSemanticLabel": "ప్రారంభ తేదీ $fullDate", "dateRangeEndDateSemanticLabel": "ముగింపు తేదీ $fullDate", "invalidDateFormatLabel": "ఫార్మాట్ చెల్లదు.", "invalidDateRangeLabel": "పరిధి చెల్లదు.", "dateOutOfRangeLabel": "పరిధి వెలుపల ఉంది.", "saveButtonLabel": "సేవ్ చేయండి", "datePickerHelpText": "తేదీ ఎంచుకోండి", "dateRangePickerHelpText": "పరిధిని ఎంచుకోండి", "calendarModeButtonLabel": "క్యాలెండర్‌కు మారండి", "inputDateModeButtonLabel": "ఇన్‌పుట్‌కు మారండి", "timePickerDialHelpText": "సమయాన్ని ఎంచుకోండి", "timePickerInputHelpText": "సమయాన్ని ఎంటర్ చేయండి", "timePickerHourLabel": "గంట", "timePickerMinuteLabel": "నిమిషం", "invalidTimeLabel": "చెల్లుబాటు అయ్యే సమయాన్ని ఎంటర్ చేయండి", "dialModeButtonLabel": "డయల్ పికర్ మోడ్‌కు మారుస్తుంది", "inputTimeModeButtonLabel": "టెక్స్ట్ ఇన్‌పుట్ మోడ్‌కు మారుస్తుంది", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 లైసెన్స్", "licensesPackageDetailTextOther": "$licenseCount లైసెన్స్‌లు", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "మెనూ బార్ మెనూ", "currentDateLabel": "నేడు", "scrimLabel": "స్క్రిమ్", "bottomSheetLabel": "దిగువున ఉన్న షీట్", "scrimOnTapHint": "$modalRouteContentName‌ను మూసివేయండి", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "కుదించడానికి డబుల్ ట్యాప్ చేయండి", "expansionTileCollapsedHint": "విస్తరించడానికి డబుల్ ట్యాప్ చేయండి", "expansionTileExpandedTapHint": "కుదించండి", "expansionTileCollapsedTapHint": "మరిన్ని వివరాల కోసం విస్తరించండి", "expandedHint": "కుదించబడింది", "collapsedHint": "విస్తరించబడింది", "menuDismissLabel": "మెనూను తీసివేయండి", "lookUpButtonLabel": "వెతకండి", "searchWebButtonLabel": "వెబ్‌లో సెర్చ్ చేయండి", "shareButtonLabel": "షేర్ చేయండి...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_te.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_te.arb", "repo_id": "flutter", "token_count": 5528 }
727
{ "reorderItemToStart": "Əvvələ köçürün", "reorderItemToEnd": "Sona köçürün", "reorderItemUp": "Yuxarı köçürün", "reorderItemDown": "Aşağı köçürün", "reorderItemLeft": "Sola köçürün", "reorderItemRight": "Sağa köçürün" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_az.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_az.arb", "repo_id": "flutter", "token_count": 126 }
728
{ "reorderItemToStart": "Déplacer au début", "reorderItemToEnd": "Déplacer à la fin", "reorderItemUp": "Déplacer vers le haut", "reorderItemDown": "Déplacer vers le bas", "reorderItemLeft": "Déplacer vers la gauche", "reorderItemRight": "Déplacer vers la droite" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_fr_CA.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_fr_CA.arb", "repo_id": "flutter", "token_count": 111 }
729
{ "reorderItemToStart": "\u0caa\u0ccd\u0cb0\u0cbe\u0cb0\u0c82\u0cad\u0c95\u0ccd\u0c95\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf", "reorderItemToEnd": "\u0c95\u0cca\u0ca8\u0cc6\u0c97\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf", "reorderItemUp": "\u0cae\u0cc7\u0cb2\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf", "reorderItemDown": "\u0c95\u0cc6\u0cb3\u0c97\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf", "reorderItemLeft": "\u0c8e\u0ca1\u0c95\u0ccd\u0c95\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf", "reorderItemRight": "\u0cac\u0cb2\u0c95\u0ccd\u0c95\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_kn.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_kn.arb", "repo_id": "flutter", "token_count": 424 }
730
{ "reorderItemToStart": "ଆରମ୍ଭକୁ ଯାଆନ୍ତୁ", "reorderItemToEnd": "ଶେଷକୁ ଯାଆନ୍ତୁ", "reorderItemUp": "ଉପରକୁ ନିଅନ୍ତୁ", "reorderItemDown": "ତଳକୁ ଯାଆନ୍ତୁ", "reorderItemLeft": "ବାମକୁ ଯାଆନ୍ତୁ", "reorderItemRight": "ଡାହାଣକୁ ଯାଆନ୍ତୁ" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_or.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_or.arb", "repo_id": "flutter", "token_count": 297 }
731
{ "reorderItemToStart": "தொடக்கத்திற்கு நகர்த்தவும்", "reorderItemToEnd": "இறுதிக்கு நகர்த்தவும்", "reorderItemUp": "மேலே நகர்த்தவும்", "reorderItemDown": "கீழே நகர்த்தவும்", "reorderItemLeft": "இடப்புறம் நகர்த்தவும்", "reorderItemRight": "வலப்புறம் நகர்த்தவும்" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_ta.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ta.arb", "repo_id": "flutter", "token_count": 417 }
732
// Copyright 2014 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:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; // A Future<ui.Image> that stores the resolved result. class _AsyncImage { _AsyncImage(Future<ui.Image> task) { _task = task.then((ui.Image image) { _result = image; }); } // Returns the resolved image. Future<ui.Image> result() async { if (_result != null) { return _result!; } await _task; assert(_result != null); return _result!; } late final Future<void> _task; ui.Image? _result; // Wait for a list of `_AsyncImage` and returns the list of its resolved // images. static Future<List<ui.Image>> resolveList(List<_AsyncImage> targets) { final Iterable<Future<ui.Image>> images = targets.map<Future<ui.Image>>( (_AsyncImage target) => target.result()); return Future.wait<ui.Image>(images); } } /// Records the frames of an animating widget, and later displays the frames as a /// grid in an animation sheet. /// /// This class does not support Web, because the animation sheet utilizes taking /// screenshots, which is unsupported on the Web. Tests that use this class must /// be noted with `skip: isBrowser`. /// (https://github.com/flutter/flutter/issues/56001) /// /// Using this class includes the following steps: /// /// * Create an instance of this class. /// * Register [dispose] to the test's tear down callbacks. /// * Pump frames that render the target widget wrapped in [record]. Every frame /// that has `recording` being true will be recorded. /// * Acquire the output image with [collate] and compare against the golden /// file. /// /// {@tool snippet} /// The following example shows how to record an animation sheet of an [InkWell] /// being pressed then released. /// /// ```dart /// testWidgets('Inkwell animation sheet', (WidgetTester tester) async { /// // Create instance /// final AnimationSheetBuilder animationSheet = AnimationSheetBuilder(frameSize: const Size(48, 24)); /// addTearDown(animationSheet.dispose); /// /// final Widget target = Material( /// child: Directionality( /// textDirection: TextDirection.ltr, /// child: InkWell( /// splashColor: Colors.blue, /// onTap: () {}, /// ), /// ), /// ); /// /// // Optional: setup before recording (`recording` is false) /// await tester.pumpWidget(animationSheet.record( /// target, /// recording: false, /// )); /// /// final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(InkWell))); /// /// // Start recording (`recording` is true) /// await tester.pumpFrames(animationSheet.record( /// target, /// recording: true, // ignore: avoid_redundant_argument_values /// ), const Duration(seconds: 1)); /// /// await gesture.up(); /// /// await tester.pumpFrames(animationSheet.record( /// target, /// recording: true, // ignore: avoid_redundant_argument_values /// ), const Duration(seconds: 1)); /// /// // Compare against golden file /// await expectLater( /// animationSheet.collate(800), /// matchesGoldenFile('inkwell.press.animation.png'), /// ); /// }, skip: isBrowser); // Animation sheet does not support browser https://github.com/flutter/flutter/issues/56001 /// ``` /// {@end-tool} /// /// See also: /// /// * [GoldenFileComparator], which introduces Golden File Testing. class AnimationSheetBuilder { /// Starts a session of building an animation sheet. /// /// The [frameSize] is a tight constraint for the child to be recorded, and must not /// be null. /// /// The [allLayers] controls whether to record elements drawn out of the subtree, /// and defaults to false. AnimationSheetBuilder({ required this.frameSize, this.allLayers = false, }) : assert(!kIsWeb); /// Dispose all recorded frames and result images. /// /// This method must be called before the test case ends (usually as a tear /// down callback) to properly deallocate the images. /// /// After this method is called, there will be no frames to [collate]. Future<void> dispose() async { final List<_AsyncImage> targets = <_AsyncImage>[ ..._recordedFrames, ..._results, ]; _recordedFrames.clear(); _results.clear(); for (final ui.Image image in await _AsyncImage.resolveList(targets)) { image.dispose(); } } /// The size of the child to be recorded. /// /// This size is applied as a tight layout constraint for the child, and is /// fixed throughout the building session. final Size frameSize; /// Whether the captured image comes from the entire tree, or only the /// subtree of [record]. /// /// If [allLayers] is false, then the [record] widget will capture the image /// composited by its subtree. If [allLayers] is true, then the [record] will /// capture the entire tree composited and clipped by [record]'s region. /// /// The two modes are identical if there is nothing in front of [record]. /// But in rare cases, what needs to be captured has to be rendered out of /// [record]'s subtree in its front. By setting [allLayers] to true, [record] /// captures everything within its region even if drawn outside of its /// subtree. /// /// Defaults to false. final bool allLayers; final List<_AsyncImage> _recordedFrames = <_AsyncImage>[]; /// Returns a widget that renders a widget in a box that can be recorded. /// /// The returned widget wraps `child` in a box with a fixed size specified by /// [frameSize]. The `key` is also applied to the returned widget. /// /// The frame is only recorded if the `recording` argument is true, or during /// a procedure that is wrapped within [recording]. In either case, the /// painted result of each frame will be stored and later available for /// [collate]. If neither condition is met, the frames are not recorded, which /// is useful during setup phases. /// /// See also: /// /// * [WidgetTester.pumpFrames], which renders a widget in a series of frames /// with a fixed time interval. Widget record(Widget child, { Key? key, bool recording = true, }) { return _AnimationSheetRecorder( key: key, size: frameSize, allLayers: allLayers, handleRecorded: !recording ? null : (Future<ui.Image> futureImage) { _recordedFrames.add(_AsyncImage(() async { final ui.Image image = await futureImage; assert(image.width == frameSize.width && image.height == frameSize.height, 'Unexpected size mismatch: frame has (${image.width}, ${image.height}) ' 'while `frameSize` is $frameSize.' ); return image; }())); }, child: child, ); } // The result images generated by `collate`. // // They're stored here to be disposed by [dispose]. final List<_AsyncImage> _results = <_AsyncImage>[]; /// Returns an result image by putting all frames together in a table. /// /// This method returns an image that arranges the captured frames in a table, /// which has `cellsPerRow` images per row with the order from left to right, /// top to bottom. /// /// The result image of this method is managed by [AnimationSheetBuilder], /// and should not be disposed by the caller. /// /// An example of using this method can be found at [AnimationSheetBuilder]. Future<ui.Image> collate(int cellsPerRow) async { assert(_recordedFrames.isNotEmpty, 'No frames are collected. Have you forgot to set `recording` to true?'); final _AsyncImage result = _AsyncImage(_collateFrames(_recordedFrames, frameSize, cellsPerRow)); _results.add(result); return result.result(); } } typedef _RecordedHandler = void Function(Future<ui.Image> image); class _AnimationSheetRecorder extends StatefulWidget { const _AnimationSheetRecorder({ this.handleRecorded, required this.child, required this.size, required this.allLayers, super.key, }); final _RecordedHandler? handleRecorded; final Widget child; final Size size; final bool allLayers; @override State<StatefulWidget> createState() => _AnimationSheetRecorderState(); } class _AnimationSheetRecorderState extends State<_AnimationSheetRecorder> { GlobalKey boundaryKey = GlobalKey(); void _record(Duration duration) { assert(widget.handleRecorded != null); final _RenderRootableRepaintBoundary boundary = boundaryKey.currentContext!.findRenderObject()! as _RenderRootableRepaintBoundary; if (widget.allLayers) { widget.handleRecorded!(boundary.allLayersToImage()); } else { widget.handleRecorded!(boundary.toImage()); } } @override Widget build(BuildContext context) { return Align( alignment: Alignment.topLeft, child: SizedBox.fromSize( size: widget.size, child: _RootableRepaintBoundary( key: boundaryKey, child: _PostFrameCallbacker( callback: widget.handleRecorded == null ? null : _record, child: widget.child, ), ), ), ); } } // Invokes `callback` and [markNeedsPaint] during the post-frame callback phase // of every frame. // // If `callback` is non-null, `_PostFrameCallbacker` adds a post-frame callback // every time it paints, during which it calls the provided `callback` then // invokes [markNeedsPaint]. // // If `callback` is null, `_PostFrameCallbacker` is equivalent to a proxy box. class _PostFrameCallbacker extends SingleChildRenderObjectWidget { const _PostFrameCallbacker({ super.child, this.callback, }); final FrameCallback? callback; @override _RenderPostFrameCallbacker createRenderObject(BuildContext context) => _RenderPostFrameCallbacker( callback: callback, ); @override void updateRenderObject(BuildContext context, _RenderPostFrameCallbacker renderObject) { renderObject.callback = callback; } } class _RenderPostFrameCallbacker extends RenderProxyBox { _RenderPostFrameCallbacker({ FrameCallback? callback, }) : _callback = callback; FrameCallback? get callback => _callback; FrameCallback? _callback; set callback(FrameCallback? value) { _callback = value; if (value != null) { markNeedsPaint(); } } @override void paint(PaintingContext context, Offset offset) { if (callback != null) { SchedulerBinding.instance.addPostFrameCallback((Duration duration) { callback!(duration); markNeedsPaint(); }); } super.paint(context, offset); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(FlagProperty('callback', value: callback != null, ifTrue: 'has a callback')); } } Future<ui.Image> _collateFrames(List<_AsyncImage> futureFrames, Size frameSize, int cellsPerRow) async { final List<ui.Image> frames = await _AsyncImage.resolveList(futureFrames); final int rowNum = (frames.length / cellsPerRow).ceil(); final ui.PictureRecorder recorder = ui.PictureRecorder(); final Canvas canvas = Canvas( recorder, Rect.fromLTWH(0, 0, frameSize.width * cellsPerRow, frameSize.height * rowNum), ); for (int i = 0; i < frames.length; i += 1) { canvas.drawImage( frames[i], Offset(frameSize.width * (i % cellsPerRow), frameSize.height * (i / cellsPerRow).floor()), Paint(), ); } final ui.Picture picture = recorder.endRecording(); final ui.Image image = await picture.toImage( (frameSize.width * cellsPerRow).toInt(), (frameSize.height * rowNum).toInt(), ); picture.dispose(); return image; } class _RenderRootableRepaintBoundary extends RenderRepaintBoundary { // Like [toImage], but captures an image of all layers (composited by // RenderView and its children) clipped by the region of this object. Future<ui.Image> allLayersToImage() { final TransformLayer rootLayer = _rootLayer(); final Matrix4 rootTransform = (rootLayer.transform ?? Matrix4.identity()).clone(); final Matrix4 transform = rootTransform.multiplied(getTransformTo(null)); final Rect rect = MatrixUtils.transformRect(transform, Offset.zero & size); // The scale was used to fit the actual device. Revert it since the target // is the logical display. Take transform[0] as the scale. return rootLayer.toImage(rect, pixelRatio: 1 / transform[0]); } TransformLayer _rootLayer() { Layer layer = this.layer!; while (layer.parent != null) { layer = layer.parent!; } return layer as TransformLayer; } } // A [RepaintBoundary], except that its render object has a `fullscreenToImage` method. class _RootableRepaintBoundary extends SingleChildRenderObjectWidget { /// Creates a widget that isolates repaints. const _RootableRepaintBoundary({ super.key, super.child }); @override _RenderRootableRepaintBoundary createRenderObject(BuildContext context) => _RenderRootableRepaintBoundary(); }
flutter/packages/flutter_test/lib/src/animation_sheet.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/animation_sheet.dart", "repo_id": "flutter", "token_count": 4283 }
733
// Copyright 2014 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. // See also test_async_utils.dart which has some stack manipulation code. import 'package:flutter/foundation.dart'; /// Report call site for `expect()` call. Returns the number of frames that /// should be elided if a stack were to be modified to hide the expect call, or /// zero if no such call was found. /// /// If the head of the stack trace consists of a failure as a result of calling /// the test_widgets [expect] function, this will fill the given /// FlutterErrorBuilder with the precise file and line number that called that /// function. int reportExpectCall(StackTrace stack, List<DiagnosticsNode> information) { final RegExp line0 = RegExp(r'^#0 +fail \(.+\)$'); final RegExp line1 = RegExp(r'^#1 +_expect \(.+\)$'); final RegExp line2 = RegExp(r'^#2 +expect \(.+\)$'); final RegExp line3 = RegExp(r'^#3 +expect \(.+\)$'); final RegExp line4 = RegExp(r'^#4 +[^(]+ \((.+?):([0-9]+)(?::[0-9]+)?\)$'); final List<String> stackLines = stack.toString().split('\n'); if (line0.firstMatch(stackLines[0]) != null && line1.firstMatch(stackLines[1]) != null && line2.firstMatch(stackLines[2]) != null && line3.firstMatch(stackLines[3]) != null) { final Match expectMatch = line4.firstMatch(stackLines[4])!; assert(expectMatch.groupCount == 2); information.add(DiagnosticsStackTrace.singleFrame( 'This was caught by the test expectation on the following line', frame: '${expectMatch.group(1)} line ${expectMatch.group(2)}', )); return 4; } return 0; }
flutter/packages/flutter_test/lib/src/stack_manipulation.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/stack_manipulation.dart", "repo_id": "flutter", "token_count": 580 }
734
include: ../../analysis_options.yaml linter: rules: # Tests try to catch errors all the time, so we don't worry about these lints for tests: avoid_catches_without_on_clauses: false avoid_catching_errors: false
flutter/packages/flutter_test/test/analysis_options.yaml/0
{ "file_path": "flutter/packages/flutter_test/test/analysis_options.yaml", "repo_id": "flutter", "token_count": 76 }
735
// Copyright 2014 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'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; const List<String> platforms = <String>['linux', 'macos', 'android', 'fuchsia']; void _verifyKeyEvent<T extends KeyEvent>(KeyEvent event, PhysicalKeyboardKey physical, LogicalKeyboardKey logical, String? character) { expect(event, isA<T>()); expect(event.physicalKey, physical); expect(event.logicalKey, logical); expect(event.character, character); expect(event.synthesized, false); } void _verifyRawKeyEvent<T extends RawKeyEvent>(RawKeyEvent event, PhysicalKeyboardKey physical, LogicalKeyboardKey logical, String? character) { expect(event, isA<T>()); expect(event.physicalKey, physical); expect(event.logicalKey, logical); expect(event.character, character); } Future<void> _shouldThrow<T extends Error>(AsyncValueGetter<void> func) async { bool hasError = false; try { await func(); } catch (e) { expect(e, isA<T>()); hasError = true; } finally { expect(hasError, true); } } void main() { testWidgets('default transit mode is keyDataThenRawKeyData', (WidgetTester tester) async { expect(KeyEventSimulator.transitMode, KeyDataTransitMode.keyDataThenRawKeyData); }); testWidgets('debugKeyEventSimulatorTransitModeOverride overrides default transit mode', (WidgetTester tester) async { debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.rawKeyData; expect(KeyEventSimulator.transitMode, KeyDataTransitMode.rawKeyData); // Unsetting debugKeyEventSimulatorTransitModeOverride can't be called in a // tear down callback because TestWidgetsFlutterBinding._verifyInvariants // is called before tear down callbacks. debugKeyEventSimulatorTransitModeOverride = null; }); testWidgets('simulates keyboard events (RawEvent)', (WidgetTester tester) async { debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.rawKeyData; final List<RawKeyEvent> events = <RawKeyEvent>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( RawKeyboardListener( focusNode: focusNode, onKey: events.add, child: Container(), ), ); focusNode.requestFocus(); await tester.idle(); for (final String platform in platforms) { await tester.sendKeyEvent(LogicalKeyboardKey.shiftLeft, platform: platform); await tester.sendKeyEvent(LogicalKeyboardKey.shift, platform: platform); await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA, platform: platform); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA, platform: platform); await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad1, platform: platform); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad1, platform: platform); await tester.idle(); expect(events.length, 8); for (int i = 0; i < events.length; ++i) { final bool isEven = i.isEven; if (isEven) { expect(events[i].runtimeType, equals(RawKeyDownEvent)); } else { expect(events[i].runtimeType, equals(RawKeyUpEvent)); } if (i < 4) { expect(events[i].data.isModifierPressed(ModifierKey.shiftModifier, side: KeyboardSide.left), equals(isEven)); } } events.clear(); } await tester.pumpWidget(Container()); debugKeyEventSimulatorTransitModeOverride = null; }); testWidgets('simulates keyboard events (KeyData then RawKeyEvent)', (WidgetTester tester) async { debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.keyDataThenRawKeyData; final List<KeyEvent> events = <KeyEvent>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( KeyboardListener( focusNode: focusNode, onKeyEvent: events.add, child: Container(), ), ); focusNode.requestFocus(); await tester.idle(); // Key press shiftLeft await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); expect(events.length, 1); _verifyKeyEvent<KeyDownEvent>(events[0], PhysicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftLeft, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.shiftLeft})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.shiftLeft); expect(events.length, 1); _verifyKeyEvent<KeyRepeatEvent>(events[0], PhysicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftLeft, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.shiftLeft})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.shiftLeft})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); expect(events.length, 1); _verifyKeyEvent<KeyUpEvent>(events[0], PhysicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftLeft, null); expect(HardwareKeyboard.instance.physicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); // Key press keyA await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA); expect(events.length, 1); _verifyKeyEvent<KeyDownEvent>(events[0], PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, 'a'); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.keyA})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.keyA})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA); _verifyKeyEvent<KeyRepeatEvent>(events[0], PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, 'a'); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.keyA})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.keyA})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA); _verifyKeyEvent<KeyUpEvent>(events[0], PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, null); expect(HardwareKeyboard.instance.physicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); // Key press keyA with physical keyQ await tester.sendKeyDownEvent(LogicalKeyboardKey.keyA, physicalKey: PhysicalKeyboardKey.keyQ); expect(events.length, 1); _verifyKeyEvent<KeyDownEvent>(events[0], PhysicalKeyboardKey.keyQ, LogicalKeyboardKey.keyA, 'a'); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.keyQ})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.keyA})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.keyA, physicalKey: PhysicalKeyboardKey.keyQ); _verifyKeyEvent<KeyRepeatEvent>(events[0], PhysicalKeyboardKey.keyQ, LogicalKeyboardKey.keyA, 'a'); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.keyQ})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.keyA})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyUpEvent(LogicalKeyboardKey.keyA, physicalKey: PhysicalKeyboardKey.keyQ); _verifyKeyEvent<KeyUpEvent>(events[0], PhysicalKeyboardKey.keyQ, LogicalKeyboardKey.keyA, null); expect(HardwareKeyboard.instance.physicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); // Key press numpad1 await tester.sendKeyDownEvent(LogicalKeyboardKey.numpad1); _verifyKeyEvent<KeyDownEvent>(events[0], PhysicalKeyboardKey.numpad1, LogicalKeyboardKey.numpad1, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numpad1})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numpad1})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.numpad1); _verifyKeyEvent<KeyRepeatEvent>(events[0], PhysicalKeyboardKey.numpad1, LogicalKeyboardKey.numpad1, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numpad1})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numpad1})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyUpEvent(LogicalKeyboardKey.numpad1); _verifyKeyEvent<KeyUpEvent>(events[0], PhysicalKeyboardKey.numpad1, LogicalKeyboardKey.numpad1, null); expect(HardwareKeyboard.instance.physicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); // Key press numLock (1st time) await tester.sendKeyDownEvent(LogicalKeyboardKey.numLock); _verifyKeyEvent<KeyDownEvent>(events[0], PhysicalKeyboardKey.numLock, LogicalKeyboardKey.numLock, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.lockModesEnabled, equals(<KeyboardLockMode>{KeyboardLockMode.numLock})); events.clear(); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.numLock); _verifyKeyEvent<KeyRepeatEvent>(events[0], PhysicalKeyboardKey.numLock, LogicalKeyboardKey.numLock, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.lockModesEnabled, equals(<KeyboardLockMode>{KeyboardLockMode.numLock})); events.clear(); await tester.sendKeyUpEvent(LogicalKeyboardKey.numLock); _verifyKeyEvent<KeyUpEvent>(events[0], PhysicalKeyboardKey.numLock, LogicalKeyboardKey.numLock, null); expect(HardwareKeyboard.instance.physicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.lockModesEnabled, equals(<KeyboardLockMode>{KeyboardLockMode.numLock})); events.clear(); // Key press numLock (2nd time) await tester.sendKeyDownEvent(LogicalKeyboardKey.numLock); _verifyKeyEvent<KeyDownEvent>(events[0], PhysicalKeyboardKey.numLock, LogicalKeyboardKey.numLock, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyRepeatEvent(LogicalKeyboardKey.numLock); _verifyKeyEvent<KeyRepeatEvent>(events[0], PhysicalKeyboardKey.numLock, LogicalKeyboardKey.numLock, null); expect(HardwareKeyboard.instance.physicalKeysPressed, equals(<PhysicalKeyboardKey>{PhysicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.logicalKeysPressed, equals(<LogicalKeyboardKey>{LogicalKeyboardKey.numLock})); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.sendKeyUpEvent(LogicalKeyboardKey.numLock); _verifyKeyEvent<KeyUpEvent>(events[0], PhysicalKeyboardKey.numLock, LogicalKeyboardKey.numLock, null); expect(HardwareKeyboard.instance.physicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.logicalKeysPressed, isEmpty); expect(HardwareKeyboard.instance.lockModesEnabled, isEmpty); events.clear(); await tester.idle(); await tester.pumpWidget(Container()); debugKeyEventSimulatorTransitModeOverride = null; }); testWidgets('simulates using the correct transit mode: rawKeyData', (WidgetTester tester) async { debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.rawKeyData; final List<Object> events = <Object>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( Focus( focusNode: focusNode, onKey: (FocusNode node, RawKeyEvent event) { events.add(event); return KeyEventResult.ignored; }, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: Container(), ), ); focusNode.requestFocus(); await tester.idle(); // A (physical keyA, logical keyA) is pressed. await simulateKeyDownEvent(LogicalKeyboardKey.keyA); expect(events.length, 2); expect(events[0], isA<KeyEvent>()); _verifyKeyEvent<KeyDownEvent>(events[0] as KeyEvent, PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, 'a'); expect(events[1], isA<RawKeyEvent>()); _verifyRawKeyEvent<RawKeyDownEvent>(events[1] as RawKeyEvent, PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, 'a'); events.clear(); // A (physical keyA, logical keyB) is released. // // Since this event was synthesized and regularized before being sent to // HardwareKeyboard, this event will be accepted. await simulateKeyUpEvent(LogicalKeyboardKey.keyB, physicalKey: PhysicalKeyboardKey.keyA); expect(events.length, 2); expect(events[0], isA<KeyEvent>()); _verifyKeyEvent<KeyUpEvent>(events[0] as KeyEvent, PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, null); expect(events[1], isA<RawKeyEvent>()); _verifyRawKeyEvent<RawKeyUpEvent>(events[1] as RawKeyEvent, PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyB, null); events.clear(); // Manually switch the transit mode to `keyDataThenRawKeyData`. This will // never happen in real applications so the assertion error can verify that // the transit mode is correctly applied. debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.keyDataThenRawKeyData; await _shouldThrow<AssertionError>(() => simulateKeyUpEvent(LogicalKeyboardKey.keyB, physicalKey: PhysicalKeyboardKey.keyA)); debugKeyEventSimulatorTransitModeOverride = null; }); testWidgets('simulates using the correct transit mode: keyDataThenRawKeyData', (WidgetTester tester) async { debugKeyEventSimulatorTransitModeOverride = KeyDataTransitMode.keyDataThenRawKeyData; final List<Object> events = <Object>[]; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( Focus( focusNode: focusNode, onKey: (FocusNode node, RawKeyEvent event) { events.add(event); return KeyEventResult.ignored; }, onKeyEvent: (FocusNode node, KeyEvent event) { events.add(event); return KeyEventResult.ignored; }, child: Container(), ), ); focusNode.requestFocus(); await tester.idle(); // A (physical keyA, logical keyA) is pressed. await simulateKeyDownEvent(LogicalKeyboardKey.keyA); expect(events.length, 2); expect(events[0], isA<KeyEvent>()); _verifyKeyEvent<KeyDownEvent>(events[0] as KeyEvent, PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, 'a'); expect(events[1], isA<RawKeyEvent>()); _verifyRawKeyEvent<RawKeyDownEvent>(events[1] as RawKeyEvent, PhysicalKeyboardKey.keyA, LogicalKeyboardKey.keyA, 'a'); events.clear(); // A (physical keyA, logical keyB) is released. // // Since this event is transmitted to HardwareKeyboard as-is, it will be rejected due to // inconsistent logical key. This does not indicate behavioral difference, // since KeyData is will never send malformed data sequence in real applications. await _shouldThrow<AssertionError>(() => simulateKeyUpEvent(LogicalKeyboardKey.keyB, physicalKey: PhysicalKeyboardKey.keyA)); debugKeyEventSimulatorTransitModeOverride = null; }); testWidgets('Key events are simulated using the default target platform', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/133955. final List<RawKeyEvent> events = <RawKeyEvent>[]; final FocusNode focusNode = FocusNode(); await tester.pumpWidget( RawKeyboardListener( focusNode: focusNode, onKey: events.add, child: Container(), ), ); focusNode.requestFocus(); await tester.idle(); await tester.sendKeyDownEvent(LogicalKeyboardKey.shift); expect(events.length, 1); final Type expectedType = isBrowser ? RawKeyEventDataWeb : switch (defaultTargetPlatform) { TargetPlatform.android => RawKeyEventDataAndroid, TargetPlatform.fuchsia => RawKeyEventDataFuchsia, TargetPlatform.iOS => RawKeyEventDataIos, TargetPlatform.linux => RawKeyEventDataLinux, TargetPlatform.macOS => RawKeyEventDataMacOs, TargetPlatform.windows => RawKeyEventDataWindows, }; expect(events.first.data.runtimeType, expectedType); }, variant: TargetPlatformVariant.all()); }
flutter/packages/flutter_test/test/event_simulation_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/event_simulation_test.dart", "repo_id": "flutter", "token_count": 6323 }
736
// Copyright 2014 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. // TODO(gspencergoog): Remove this tag once this test's state leaks/test // dependencies have been fixed. // https://github.com/flutter/flutter/issues/85160 // Fails with "flutter test --test-randomize-ordering-seed=20210721" @Tags(<String>['no-shuffle']) library; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('enterText works', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: TextField(), ), ), ); final EditableTextState state = tester.state(find.byType(EditableText)); expect(state.textEditingValue.text, ''); await tester.enterText(find.byType(EditableText), 'let there be text'); expect(state.textEditingValue.text, 'let there be text'); expect(state.textEditingValue.selection.isCollapsed, isTrue); expect(state.textEditingValue.selection.baseOffset, 17); }); testWidgets('receiveAction() forwards exception when exception occurs during action processing', (WidgetTester tester) async { // Setup a widget that can receive focus so that we can open the keyboard. const Widget widget = MaterialApp( home: Material( child: TextField(), ), ); await tester.pumpWidget(widget); // Keyboard must be shown for receiveAction() to function. await tester.showKeyboard(find.byType(TextField)); // Register a handler for the text input channel that throws an error. This // error should be reported within a PlatformException by TestTextInput. SystemChannels.textInput.setMethodCallHandler((MethodCall call) { throw FlutterError('A fake error occurred during action processing.'); }); await expectLater( () => tester.testTextInput.receiveAction(TextInputAction.done), throwsA(isA<PlatformException>()), ); }); testWidgets('selectors are called on macOS', (WidgetTester tester) async { List<dynamic>? selectorNames; await SystemChannels.textInput.invokeMethod('TextInput.setClient', <dynamic>[1, <String, dynamic>{}]); await SystemChannels.textInput.invokeMethod('TextInput.show'); SystemChannels.textInput.setMethodCallHandler((MethodCall call) async { if (call.method == 'TextInputClient.performSelectors') { selectorNames = (call.arguments as List<dynamic>)[1] as List<dynamic>; } }); await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); await tester.sendKeyDownEvent(LogicalKeyboardKey.arrowUp); await SystemChannels.textInput.invokeMethod('TextInput.clearClient'); if (defaultTargetPlatform == TargetPlatform.macOS) { expect(selectorNames, <dynamic>['moveBackward:', 'moveToBeginningOfParagraph:']); } else { expect(selectorNames, isNull); } }, variant: TargetPlatformVariant.all()); testWidgets('selector is called for ctrl + backspace on macOS', (WidgetTester tester) async { List<dynamic>? selectorNames; await SystemChannels.textInput.invokeMethod('TextInput.setClient', <dynamic>[1, <String, dynamic>{}]); await SystemChannels.textInput.invokeMethod('TextInput.show'); SystemChannels.textInput.setMethodCallHandler((MethodCall call) async { if (call.method == 'TextInputClient.performSelectors') { selectorNames = (call.arguments as List<dynamic>)[1] as List<dynamic>; } }); await tester.sendKeyDownEvent(LogicalKeyboardKey.control); await tester.sendKeyDownEvent(LogicalKeyboardKey.backspace); await tester.sendKeyUpEvent(LogicalKeyboardKey.backspace); await tester.sendKeyUpEvent(LogicalKeyboardKey.control); await SystemChannels.textInput.invokeMethod('TextInput.clearClient'); if (defaultTargetPlatform == TargetPlatform.macOS) { expect(selectorNames, <dynamic>['deleteBackwardByDecomposingPreviousCharacter:']); } else { expect(selectorNames, isNull); } }, variant: TargetPlatformVariant.all()); }
flutter/packages/flutter_test/test/test_text_input_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/test_text_input_test.dart", "repo_id": "flutter", "token_count": 1417 }
737
// Copyright 2014 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:ui'; import 'package:clock/src/clock.dart'; import 'package:flutter_test/flutter_test.dart'; void main() async { TestWidgetsFlutterBinding binding = AutomatedTestWidgetsFlutterBinding.ensureInitialized(); binding.runTest( () async { // This will be unchanged as there is no equivalent API. binding.addTime(Duration(seconds: 30)); await binding.runAsync( () async {}, // Changes made in https://github.com/flutter/flutter/pull/89952 additionalTime: Duration(seconds: 25), ); }, () { }, // This timeout will be removed and not replaced since there is no // equivalent API at this layer. timeout: Duration(minutes: 30), ); }
flutter/packages/flutter_test/test_fixes/flutter_test/binding/test_widgets_flutter_binding.dart/0
{ "file_path": "flutter/packages/flutter_test/test_fixes/flutter_test/binding/test_widgets_flutter_binding.dart", "repo_id": "flutter", "token_count": 300 }
738
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } }
flutter/packages/flutter_tools/gradle/settings.gradle.kts/0
{ "file_path": "flutter/packages/flutter_tools/gradle/settings.gradle.kts", "repo_id": "flutter", "token_count": 66 }
739
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="catalog - expansion_tile_sample" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/catalog/lib/expansion_tile_sample.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___expansion_tile_sample.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___expansion_tile_sample.xml.copy.tmpl", "repo_id": "flutter", "token_count": 99 }
740
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="manual_tests - color_testing_demo" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/color_testing_demo.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___color_testing_demo.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___color_testing_demo.xml.copy.tmpl", "repo_id": "flutter", "token_count": 103 }
741
// Copyright 2014 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:process/process.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/process.dart'; import '../base/user_messages.dart'; import '../device.dart'; import 'adb.dart'; import 'android_device.dart'; import 'android_sdk.dart'; import 'android_workflow.dart'; /// Device discovery for Android physical devices and emulators. /// /// This class primarily delegates to the `adb` command line tool provided by /// the Android SDK to discover instances of connected android devices. /// /// See also: /// * [AndroidDevice], the type of discovered device. class AndroidDevices extends PollingDeviceDiscovery { AndroidDevices({ required AndroidWorkflow androidWorkflow, required ProcessManager processManager, required Logger logger, AndroidSdk? androidSdk, required FileSystem fileSystem, required Platform platform, required UserMessages userMessages, }) : _androidWorkflow = androidWorkflow, _androidSdk = androidSdk, _processUtils = ProcessUtils( logger: logger, processManager: processManager, ), _processManager = processManager, _logger = logger, _fileSystem = fileSystem, _platform = platform, _userMessages = userMessages, super('Android devices'); final AndroidWorkflow _androidWorkflow; final ProcessUtils _processUtils; final AndroidSdk? _androidSdk; final ProcessManager _processManager; final Logger _logger; final FileSystem _fileSystem; final Platform _platform; final UserMessages _userMessages; @override bool get supportsPlatform => _androidWorkflow.appliesToHostPlatform; @override bool get canListAnything => _androidWorkflow.canListDevices; @override Future<List<Device>> pollingGetDevices({ Duration? timeout }) async { if (_doesNotHaveAdb()) { return <AndroidDevice>[]; } String text; try { text = (await _processUtils.run(<String>[_androidSdk!.adbPath!, 'devices', '-l'], throwOnError: true, )).stdout.trim(); } on ProcessException catch (exception) { throwToolExit( 'Unable to run "adb", check your Android SDK installation and ' '$kAndroidHome environment variable: ${exception.executable}', ); } final List<AndroidDevice> devices = <AndroidDevice>[]; _parseADBDeviceOutput( text, devices: devices, ); return devices; } @override Future<List<String>> getDiagnostics() async { if (_doesNotHaveAdb()) { return <String>[]; } final RunResult result = await _processUtils.run(<String>[_androidSdk!.adbPath!, 'devices', '-l']); if (result.exitCode != 0) { return <String>[]; } final List<String> diagnostics = <String>[]; _parseADBDeviceOutput( result.stdout, diagnostics: diagnostics, ); return diagnostics; } bool _doesNotHaveAdb() { return _androidSdk == null || _androidSdk.adbPath == null || !_processManager.canRun(_androidSdk.adbPath); } // 015d172c98400a03 device usb:340787200X product:nakasi model:Nexus_7 device:grouper static final RegExp _kDeviceRegex = RegExp(r'^(\S+)\s+(\S+)(.*)'); /// Parse the given `adb devices` output in [text], and fill out the given list /// of devices and possible device issue diagnostics. Either argument can be null, /// in which case information for that parameter won't be populated. void _parseADBDeviceOutput( String text, { List<AndroidDevice>? devices, List<String>? diagnostics, }) { // Check for error messages from adb if (!text.contains('List of devices')) { diagnostics?.add(text); return; } for (final String line in text.trim().split('\n')) { // Skip lines like: * daemon started successfully * if (line.startsWith('* daemon ')) { continue; } // Skip lines about adb server and client version not matching if (line.startsWith(RegExp(r'adb server (version|is out of date)'))) { diagnostics?.add(line); continue; } if (line.startsWith('List of devices')) { continue; } if (_kDeviceRegex.hasMatch(line)) { final Match match = _kDeviceRegex.firstMatch(line)!; final String deviceID = match[1]!; final String deviceState = match[2]!; String? rest = match[3]; final Map<String, String> info = <String, String>{}; if (rest != null && rest.isNotEmpty) { rest = rest.trim(); for (final String data in rest.split(' ')) { if (data.contains(':')) { final List<String> fields = data.split(':'); info[fields[0]] = fields[1]; } } } final String? model = info['model']; if (model != null) { info['model'] = cleanAdbDeviceName(model); } switch (deviceState) { case 'unauthorized': diagnostics?.add( 'Device $deviceID is not authorized.\n' 'You might need to check your device for an authorization dialog.' ); case 'offline': diagnostics?.add('Device $deviceID is offline.'); default: devices?.add(AndroidDevice( deviceID, productID: info['product'], modelID: info['model'] ?? deviceID, deviceCodeName: info['device'], androidSdk: _androidSdk!, fileSystem: _fileSystem, logger: _logger, platform: _platform, processManager: _processManager, )); } } else { diagnostics?.add( 'Unexpected failure parsing device information from adb output:\n' '$line\n' '${_userMessages.flutterToolBugInstructions}'); } } } @override List<String> get wellKnownIds => const <String>[]; }
flutter/packages/flutter_tools/lib/src/android/android_device_discovery.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/android_device_discovery.dart", "repo_id": "flutter", "token_count": 2472 }
742
// Copyright 2014 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:meta/meta.dart'; import '../../base/file_system.dart'; import '../../base/project_migrator.dart'; import '../../project.dart'; import '../gradle_utils.dart'; /// Replacement value for https://developer.android.com/reference/tools/gradle-api/8.0/com/android/build/api/dsl/BaseFlavor#minSdkVersion(kotlin.Int) /// that instead of using a value defaults to the version defined by the /// flutter sdk as the minimum supported by flutter. @visibleForTesting const String replacementMinSdkText = 'minSdkVersion flutter.minSdkVersion'; @visibleForTesting const String appGradleNotFoundWarning = 'Module level build.gradle file not found, skipping minSdkVersion migration.'; class MinSdkVersionMigration extends ProjectMigrator { MinSdkVersionMigration( AndroidProject project, super.logger, ) : _project = project; final AndroidProject _project; @override void migrate() { // Skip applying migration in modules as the FlutterExtension is not applied. if (_project.isModule) { return; } try { processFileLines(_project.appGradleFile); } on FileSystemException { // Skip if we cannot find the app level build.gradle file. logger.printTrace(appGradleNotFoundWarning); } } @override String migrateFileContents(String fileContents) { return fileContents.replaceAll( tooOldMinSdkVersionMatch, replacementMinSdkText, ); } }
flutter/packages/flutter_tools/lib/src/android/migrations/min_sdk_version_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/migrations/min_sdk_version_migration.dart", "repo_id": "flutter", "token_count": 510 }
743
// Copyright 2014 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:file/local.dart' as local_fs; import 'package:meta/meta.dart'; import 'common.dart'; import 'io.dart'; import 'platform.dart'; import 'process.dart'; import 'signals.dart'; // package:file/local.dart must not be exported. This exposes LocalFileSystem, // which we override to ensure that temporary directories are cleaned up when // the tool is killed by a signal. export 'package:file/file.dart'; /// Exception indicating that a file that was expected to exist was not found. class FileNotFoundException implements IOException { const FileNotFoundException(this.path); final String path; @override String toString() => 'File not found: $path'; } /// Various convenience file system methods. class FileSystemUtils { FileSystemUtils({ required FileSystem fileSystem, required Platform platform, }) : _fileSystem = fileSystem, _platform = platform; final FileSystem _fileSystem; final Platform _platform; /// Appends a number to a filename in order to make it unique under a /// directory. File getUniqueFile(Directory dir, String baseName, String ext) { return _getUniqueFile(dir, baseName, ext); } /// Appends a number to a directory name in order to make it unique under a /// directory. Directory getUniqueDirectory(Directory dir, String baseName) { final FileSystem fs = dir.fileSystem; int i = 1; while (true) { final String name = '${baseName}_${i.toString().padLeft(2, '0')}'; final Directory directory = fs.directory(_fileSystem.path.join(dir.path, name)); if (!directory.existsSync()) { return directory; } i += 1; } } /// Escapes [path]. /// /// On Windows it replaces all '\' with '\\'. On other platforms, it returns the /// path unchanged. String escapePath(String path) => _platform.isWindows ? path.replaceAll(r'\', r'\\') : path; /// Returns true if the file system [entity] has not been modified since the /// latest modification to [referenceFile]. /// /// Returns true, if [entity] does not exist. /// /// Returns false, if [entity] exists, but [referenceFile] does not. bool isOlderThanReference({ required FileSystemEntity entity, required File referenceFile, }) { if (!entity.existsSync()) { return true; } return referenceFile.existsSync() && referenceFile.statSync().modified.isAfter(entity.statSync().modified); } /// Return the absolute path of the user's home directory. String? get homeDirPath { String? path = _platform.isWindows ? _platform.environment['USERPROFILE'] : _platform.environment['HOME']; if (path != null) { path = _fileSystem.path.absolute(path); } return path; } } /// Return a relative path if [fullPath] is contained by the cwd, else return an /// absolute path. String getDisplayPath(String fullPath, FileSystem fileSystem) { final String cwd = fileSystem.currentDirectory.path + fileSystem.path.separator; return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath; } /// Creates `destDir` if needed, then recursively copies `srcDir` to /// `destDir`, invoking [onFileCopied], if specified, for each /// source/destination file pair. /// /// Skips files if [shouldCopyFile] returns `false`. /// Does not recurse over directories if [shouldCopyDirectory] returns `false`. /// /// If [followLinks] is false, then any symbolic links found are reported as /// [Link] objects, rather than as directories or files, and are not recursed into. /// /// If [followLinks] is true, then working links are reported as directories or /// files, depending on what they point to. void copyDirectory( Directory srcDir, Directory destDir, { bool Function(File srcFile, File destFile)? shouldCopyFile, bool Function(Directory)? shouldCopyDirectory, void Function(File srcFile, File destFile)? onFileCopied, bool followLinks = true, }) { if (!srcDir.existsSync()) { throw Exception('Source directory "${srcDir.path}" does not exist, nothing to copy'); } if (!destDir.existsSync()) { destDir.createSync(recursive: true); } for (final FileSystemEntity entity in srcDir.listSync(followLinks: followLinks)) { final String newPath = destDir.fileSystem.path.join(destDir.path, entity.basename); if (entity is Link) { final Link newLink = destDir.fileSystem.link(newPath); newLink.createSync(entity.targetSync()); } else if (entity is File) { final File newFile = destDir.fileSystem.file(newPath); if (shouldCopyFile != null && !shouldCopyFile(entity, newFile)) { continue; } newFile.writeAsBytesSync(entity.readAsBytesSync()); onFileCopied?.call(entity, newFile); } else if (entity is Directory) { if (shouldCopyDirectory != null && !shouldCopyDirectory(entity)) { continue; } copyDirectory( entity, destDir.fileSystem.directory(newPath), shouldCopyFile: shouldCopyFile, onFileCopied: onFileCopied, followLinks: followLinks, ); } else { throw Exception('${entity.path} is neither File nor Directory, was ${entity.runtimeType}'); } } } File _getUniqueFile(Directory dir, String baseName, String ext) { final FileSystem fs = dir.fileSystem; int i = 1; while (true) { final String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext'; final File file = fs.file(dir.fileSystem.path.join(dir.path, name)); if (!file.existsSync()) { file.createSync(recursive: true); return file; } i += 1; } } /// Appends a number to a filename in order to make it unique under a /// directory. File getUniqueFile(Directory dir, String baseName, String ext) { return _getUniqueFile(dir, baseName, ext); } /// This class extends [local_fs.LocalFileSystem] in order to clean up /// directories and files that the tool creates under the system temporary /// directory when the tool exits either normally or when killed by a signal. class LocalFileSystem extends local_fs.LocalFileSystem { LocalFileSystem(this._signals, this._fatalSignals, this.shutdownHooks); @visibleForTesting LocalFileSystem.test({ required Signals signals, List<ProcessSignal> fatalSignals = Signals.defaultExitSignals, }) : this(signals, fatalSignals, ShutdownHooks()); Directory? _systemTemp; final Map<ProcessSignal, Object> _signalTokens = <ProcessSignal, Object>{}; final ShutdownHooks shutdownHooks; Future<void> dispose() async { _tryToDeleteTemp(); for (final MapEntry<ProcessSignal, Object> signalToken in _signalTokens.entries) { await _signals.removeHandler(signalToken.key, signalToken.value); } _signalTokens.clear(); } final Signals _signals; final List<ProcessSignal> _fatalSignals; void _tryToDeleteTemp() { try { if (_systemTemp?.existsSync() ?? false) { _systemTemp?.deleteSync(recursive: true); } } on FileSystemException { // ignore } _systemTemp = null; } // This getter returns a fresh entry under /tmp, like // /tmp/flutter_tools.abcxyz, then the rest of the tool creates /tmp entries // under that, like /tmp/flutter_tools.abcxyz/flutter_build_stuff.123456. // Right before exiting because of a signal or otherwise, we delete // /tmp/flutter_tools.abcxyz, not the whole of /tmp. @override Directory get systemTempDirectory { if (_systemTemp == null) { if (!superSystemTempDirectory.existsSync()) { throwToolExit('Your system temp directory (${superSystemTempDirectory.path}) does not exist. ' 'Did you set an invalid override in your environment? See issue https://github.com/flutter/flutter/issues/74042 for more context.' ); } _systemTemp = superSystemTempDirectory.createTempSync('flutter_tools.') ..createSync(recursive: true); // Make sure that the temporary directory is cleaned up if the tool is // killed by a signal. for (final ProcessSignal signal in _fatalSignals) { final Object token = _signals.addHandler( signal, (ProcessSignal _) { _tryToDeleteTemp(); }, ); _signalTokens[signal] = token; } // Make sure that the temporary directory is cleaned up when the tool // exits normally. shutdownHooks.addShutdownHook( _tryToDeleteTemp, ); } return _systemTemp!; } // This only exist because the memory file system does not support a systemTemp that does not exists #74042 @visibleForTesting Directory get superSystemTempDirectory => super.systemTempDirectory; }
flutter/packages/flutter_tools/lib/src/base/file_system.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/file_system.dart", "repo_id": "flutter", "token_count": 2932 }
744
// Copyright 2014 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:math' as math; import 'package:file/file.dart'; import 'package:intl/intl.dart'; import 'package:path/path.dart' as path; // flutter_ignore: package_path_import import '../convert.dart'; /// A path jointer for URL paths. final path.Context urlContext = path.url; /// Convert `foo_bar` to `fooBar`. String camelCase(String str) { int index = str.indexOf('_'); while (index != -1 && index < str.length - 2) { str = str.substring(0, index) + str.substring(index + 1, index + 2).toUpperCase() + str.substring(index + 2); index = str.indexOf('_'); } return str; } /// Convert `fooBar` to `foo-bar`. String kebabCase(String str) { return snakeCase(str, '-'); } final RegExp _upperRegex = RegExp(r'[A-Z]'); /// Convert `fooBar` to `foo_bar`. String snakeCase(String str, [ String sep = '_' ]) { return str.replaceAllMapped(_upperRegex, (Match m) => '${m.start == 0 ? '' : sep}${m[0]!.toLowerCase()}'); } abstract interface class CliEnum implements Enum { String get cliName; String get helpText; static Map<String, String> allowedHelp<T extends CliEnum>(List<T> values) => Map<String, String>.fromEntries( values.map( (T e) => MapEntry<String, String>(e.cliName, e.helpText), ), ); } /// Converts `fooBar` to `FooBar`. /// /// This uses [toBeginningOfSentenceCase](https://pub.dev/documentation/intl/latest/intl/toBeginningOfSentenceCase.html), /// with the input and return value of non-nullable. String sentenceCase(String str, [String? locale]) { if (str.isEmpty) { return str; } // TODO(christopherfujino): Remove this check after the next release of intl return ArgumentError.checkNotNull(toBeginningOfSentenceCase(str, locale)); } /// Converts `foo_bar` to `Foo Bar`. String snakeCaseToTitleCase(String snakeCaseString) { return snakeCaseString.split('_').map(camelCase).map(sentenceCase).join(' '); } /// Return the plural of the given word (`cat(s)`). String pluralize(String word, int count) => count == 1 ? word : '${word}s'; String toPrettyJson(Object jsonable) { final String value = const JsonEncoder.withIndent(' ').convert(jsonable); return '$value\n'; } final NumberFormat kSecondsFormat = NumberFormat('0.0'); final NumberFormat kMillisecondsFormat = NumberFormat.decimalPattern(); String getElapsedAsSeconds(Duration duration) { final double seconds = duration.inMilliseconds / Duration.millisecondsPerSecond; return '${kSecondsFormat.format(seconds)}s'; } String getElapsedAsMilliseconds(Duration duration) { return '${kMillisecondsFormat.format(duration.inMilliseconds)}ms'; } /// Return a String - with units - for the size in MB of the given number of bytes. String getSizeAsMB(int bytesLength) { return '${(bytesLength / (1024 * 1024)).toStringAsFixed(1)}MB'; } /// A class to maintain a list of items, fire events when items are added or /// removed, and calculate a diff of changes when a new list of items is /// available. class ItemListNotifier<T> { ItemListNotifier(): _items = <T>{}; ItemListNotifier.from(List<T> items) : _items = Set<T>.of(items); Set<T> _items; final StreamController<T> _addedController = StreamController<T>.broadcast(); final StreamController<T> _removedController = StreamController<T>.broadcast(); Stream<T> get onAdded => _addedController.stream; Stream<T> get onRemoved => _removedController.stream; List<T> get items => _items.toList(); void updateWithNewList(List<T> updatedList) { final Set<T> updatedSet = Set<T>.of(updatedList); final Set<T> addedItems = updatedSet.difference(_items); final Set<T> removedItems = _items.difference(updatedSet); _items = updatedSet; addedItems.forEach(_addedController.add); removedItems.forEach(_removedController.add); } void removeItem(T item) { if (_items.remove(item)) { _removedController.add(item); } } /// Close the streams. void dispose() { _addedController.close(); _removedController.close(); } } class SettingsFile { SettingsFile(); SettingsFile.parse(String contents) { for (String line in contents.split('\n')) { line = line.trim(); if (line.startsWith('#') || line.isEmpty) { continue; } final int index = line.indexOf('='); if (index != -1) { values[line.substring(0, index)] = line.substring(index + 1); } } } SettingsFile.parseFromFile(File file) : this.parse(file.readAsStringSync()); final Map<String, String> values = <String, String>{}; void writeContents(File file) { file.parent.createSync(recursive: true); file.writeAsStringSync(values.keys.map<String>((String key) { return '$key=${values[key]}'; }).join('\n')); } } /// Given a data structure which is a Map of String to dynamic values, return /// the same structure (`Map<String, dynamic>`) with the correct runtime types. Map<String, Object?>? castStringKeyedMap(Object? untyped) { final Map<dynamic, dynamic>? map = untyped as Map<dynamic, dynamic>?; return map?.cast<String, Object?>(); } /// Smallest column that will be used for text wrapping. If the requested column /// width is smaller than this, then this is what will be used. const int kMinColumnWidth = 10; /// Wraps a block of text into lines no longer than [columnWidth]. /// /// Tries to split at whitespace, but if that's not good enough to keep it under /// the limit, then it splits in the middle of a word. If [columnWidth] (minus /// any indent) is smaller than [kMinColumnWidth], the text is wrapped at that /// [kMinColumnWidth] instead. /// /// Preserves indentation (leading whitespace) for each line (delimited by '\n') /// in the input, and will indent wrapped lines that same amount, adding /// [indent] spaces in addition to any existing indent. /// /// If [hangingIndent] is supplied, then that many additional spaces will be /// added to each line, except for the first line. The [hangingIndent] is added /// to the specified [indent], if any. This is useful for wrapping /// text with a heading prefix (e.g. "Usage: "): /// /// ```dart /// String prefix = "Usage: "; /// print(prefix + wrapText(invocation, indent: 2, hangingIndent: prefix.length, columnWidth: 40)); /// ``` /// /// yields: /// ``` /// Usage: app main_command <subcommand> /// [arguments] /// ``` /// /// If [outputPreferences.wrapText] is false, then the text will be returned /// unchanged. If [shouldWrap] is specified, then it overrides the /// [outputPreferences.wrapText] setting. /// /// If the amount of indentation (from the text, [indent], and [hangingIndent]) /// is such that less than [kMinColumnWidth] characters can fit in the /// [columnWidth], then the indent is truncated to allow the text to fit. String wrapText(String text, { required int columnWidth, required bool shouldWrap, int? hangingIndent, int? indent, }) { assert(columnWidth >= 0); if (text.isEmpty) { return ''; } indent ??= 0; hangingIndent ??= 0; final List<String> splitText = text.split('\n'); final List<String> result = <String>[]; for (final String line in splitText) { String trimmedText = line.trimLeft(); final String leadingWhitespace = line.substring(0, line.length - trimmedText.length); List<String> notIndented; if (hangingIndent != 0) { // When we have a hanging indent, we want to wrap the first line at one // width, and the rest at another (offset by hangingIndent), so we wrap // them twice and recombine. final List<String> firstLineWrap = _wrapTextAsLines( trimmedText, columnWidth: columnWidth - leadingWhitespace.length - indent, shouldWrap: shouldWrap, ); notIndented = <String>[firstLineWrap.removeAt(0)]; trimmedText = trimmedText.substring(notIndented[0].length).trimLeft(); if (trimmedText.isNotEmpty) { notIndented.addAll(_wrapTextAsLines( trimmedText, columnWidth: columnWidth - leadingWhitespace.length - indent - hangingIndent, shouldWrap: shouldWrap, )); } } else { notIndented = _wrapTextAsLines( trimmedText, columnWidth: columnWidth - leadingWhitespace.length - indent, shouldWrap: shouldWrap, ); } String? hangingIndentString; final String indentString = ' ' * indent; result.addAll(notIndented.map<String>( (String line) { // Don't return any lines with just whitespace on them. if (line.isEmpty) { return ''; } String truncatedIndent = '$indentString${hangingIndentString ?? ''}$leadingWhitespace'; if (truncatedIndent.length > columnWidth - kMinColumnWidth) { truncatedIndent = truncatedIndent.substring(0, math.max(columnWidth - kMinColumnWidth, 0)); } final String result = '$truncatedIndent$line'; hangingIndentString ??= ' ' * hangingIndent!; return result; }, )); } return result.join('\n'); } // Used to represent a run of ANSI control sequences next to a visible // character. class _AnsiRun { _AnsiRun(this.original, this.character); String original; String character; } /// Wraps a block of text into lines no longer than [columnWidth], starting at the /// [start] column, and returning the result as a list of strings. /// /// Tries to split at whitespace, but if that's not good enough to keep it /// under the limit, then splits in the middle of a word. Preserves embedded /// newlines, but not indentation (it trims whitespace from each line). /// /// If [columnWidth] is not specified, then the column width will be the width of the /// terminal window by default. If the stdout is not a terminal window, then the /// default will be [outputPreferences.wrapColumn]. /// /// The [columnWidth] is clamped to [kMinColumnWidth] at minimum (so passing negative /// widths is fine, for instance). /// /// If [outputPreferences.wrapText] is false, then the text will be returned /// split at the newlines, but not wrapped. If [shouldWrap] is specified, /// then it overrides the [outputPreferences.wrapText] setting. List<String> _wrapTextAsLines(String text, { int start = 0, required int columnWidth, required bool shouldWrap, }) { if (text.isEmpty) { return <String>['']; } assert(start >= 0); // Splits a string so that the resulting list has the same number of elements // as there are visible characters in the string, but elements may include one // or more adjacent ANSI sequences. Joining the list elements again will // reconstitute the original string. This is useful for manipulating "visible" // characters in the presence of ANSI control codes. List<_AnsiRun> splitWithCodes(String input) { final RegExp characterOrCode = RegExp('(\u001b\\[[0-9;]*m|.)', multiLine: true); List<_AnsiRun> result = <_AnsiRun>[]; final StringBuffer current = StringBuffer(); for (final Match match in characterOrCode.allMatches(input)) { current.write(match[0]); if (match[0]!.length < 4) { // This is a regular character, write it out. result.add(_AnsiRun(current.toString(), match[0]!)); current.clear(); } } // If there's something accumulated, then it must be an ANSI sequence, so // add it to the end of the last entry so that we don't lose it. if (current.isNotEmpty) { if (result.isNotEmpty) { result.last.original += current.toString(); } else { // If there is nothing in the string besides control codes, then just // return them as the only entry. result = <_AnsiRun>[_AnsiRun(current.toString(), '')]; } } return result; } String joinRun(List<_AnsiRun> list, int start, [ int? end ]) { return list.sublist(start, end).map<String>((_AnsiRun run) => run.original).join().trim(); } final List<String> result = <String>[]; final int effectiveLength = math.max(columnWidth - start, kMinColumnWidth); for (final String line in text.split('\n')) { // If the line is short enough, even with ANSI codes, then we can just add // it and move on. if (line.length <= effectiveLength || !shouldWrap) { result.add(line); continue; } final List<_AnsiRun> splitLine = splitWithCodes(line); if (splitLine.length <= effectiveLength) { result.add(line); continue; } int currentLineStart = 0; int? lastWhitespace; // Find the start of the current line. for (int index = 0; index < splitLine.length; ++index) { if (splitLine[index].character.isNotEmpty && _isWhitespace(splitLine[index])) { lastWhitespace = index; } if (index - currentLineStart >= effectiveLength) { // Back up to the last whitespace, unless there wasn't any, in which // case we just split where we are. if (lastWhitespace != null) { index = lastWhitespace; } result.add(joinRun(splitLine, currentLineStart, index)); // Skip any intervening whitespace. while (index < splitLine.length && _isWhitespace(splitLine[index])) { index++; } currentLineStart = index; lastWhitespace = null; } } result.add(joinRun(splitLine, currentLineStart)); } return result; } /// Returns true if the code unit at [index] in [text] is a whitespace /// character. /// /// Based on: https://en.wikipedia.org/wiki/Whitespace_character#Unicode bool _isWhitespace(_AnsiRun run) { final int rune = run.character.isNotEmpty ? run.character.codeUnitAt(0) : 0x0; return rune >= 0x0009 && rune <= 0x000D || rune == 0x0020 || rune == 0x0085 || rune == 0x1680 || rune == 0x180E || rune >= 0x2000 && rune <= 0x200A || rune == 0x2028 || rune == 0x2029 || rune == 0x202F || rune == 0x205F || rune == 0x3000 || rune == 0xFEFF; } final RegExp _interpolationRegex = RegExp(r'\$\{([^}]*)\}'); /// Given a string that possibly contains string interpolation sequences /// (so for example, something like `ping -n 1 ${host}`), replace all those /// interpolation sequences with the matching value given in [replacementValues]. /// /// If the value could not be found inside [replacementValues], an empty /// string will be substituted instead. /// /// However, if the dollar sign inside the string is preceded with a backslash, /// the sequences won't be substituted at all. /// /// Example: /// ```dart /// final interpolated = _interpolateString(r'ping -n 1 ${host}', {'host': 'raspberrypi'}); /// print(interpolated); // will print 'ping -n 1 raspberrypi' /// /// final interpolated2 = _interpolateString(r'ping -n 1 ${_host}', {'host': 'raspberrypi'}); /// print(interpolated2); // will print 'ping -n 1 ' /// ``` String interpolateString(String toInterpolate, Map<String, String> replacementValues) { return toInterpolate.replaceAllMapped(_interpolationRegex, (Match match) { /// The name of the variable to be inserted into the string. /// Example: If the source string is 'ping -n 1 ${host}', /// `name` would be 'host' final String name = match.group(1)!; return replacementValues.containsKey(name) ? replacementValues[name]! : ''; }); } /// Given a list of strings possibly containing string interpolation sequences /// (so for example, something like `['ping', '-n', '1', '${host}']`), replace /// all those interpolation sequences with the matching value given in [replacementValues]. /// /// If the value could not be found inside [replacementValues], an empty /// string will be substituted instead. /// /// However, if the dollar sign inside the string is preceded with a backslash, /// the sequences won't be substituted at all. /// /// Example: /// ```dart /// final interpolated = _interpolateString(['ping', '-n', '1', r'${host}'], {'host': 'raspberrypi'}); /// print(interpolated); // will print '[ping, -n, 1, raspberrypi]' /// /// final interpolated2 = _interpolateString(['ping', '-n', '1', r'${_host}'], {'host': 'raspberrypi'}); /// print(interpolated2); // will print '[ping, -n, 1, ]' /// ``` List<String> interpolateStringList(List<String> toInterpolate, Map<String, String> replacementValues) { return toInterpolate.map((String s) => interpolateString(s, replacementValues)).toList(); } /// Returns the first line-based match for [regExp] in [file]. /// /// Assumes UTF8 encoding. Match? firstMatchInFile(File file, RegExp regExp) { if (!file.existsSync()) { return null; } for (final String line in file.readAsLinesSync()) { final Match? match = regExp.firstMatch(line); if (match != null) { return match; } } return null; } /// Tests for shallow equality on two sets. bool setEquals<T>(Set<T>? a, Set<T>? b) { if (a == null) { return b == null; } if (b == null || a.length != b.length) { return false; } if (identical(a, b)) { return true; } for (final T value in a) { if (!b.contains(value)) { return false; } } return true; } /// Tests for shallow equality on two lists. bool listEquals<T>(List<T> a, List<T> b) { if (identical(a, b)) { return true; } if (a.length != b.length) { return false; } for (int index = 0; index < a.length; index++) { if (a[index] != b[index]) { return false; } } return true; }
flutter/packages/flutter_tools/lib/src/base/utils.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/utils.dart", "repo_id": "flutter", "token_count": 6087 }
745
// Copyright 2014 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 '../../base/file_system.dart'; import '../depfile.dart'; /// Unpack the engine artifact list [artifacts] from [engineSourcePath], ICU /// data (if provided), and [clientSourcePaths] (if provided) into a directory /// [outputDirectory]. /// /// Returns a [Depfile] including all copied files. /// /// Throws an [Exception] if [artifacts] includes missing files, directories, /// or links. Depfile unpackDesktopArtifacts({ required FileSystem fileSystem, required List<String> artifacts, required Directory outputDirectory, required String engineSourcePath, List<String>? clientSourcePaths, String? icuDataPath, }) { final List<File> inputs = <File>[]; final List<File> outputs = <File>[]; for (final String artifact in artifacts) { final String entityPath = fileSystem.path.join(engineSourcePath, artifact); final FileSystemEntityType entityType = fileSystem.typeSync(entityPath); if (entityType == FileSystemEntityType.notFound || entityType == FileSystemEntityType.directory || entityType == FileSystemEntityType.link) { throw Exception('Unsupported file type "$entityType" for $entityPath'); } assert(entityType == FileSystemEntityType.file); final String outputPath = fileSystem.path.join( outputDirectory.path, fileSystem.path.relative(entityPath, from: engineSourcePath), ); final File destinationFile = fileSystem.file(outputPath); if (!destinationFile.parent.existsSync()) { destinationFile.parent.createSync(recursive: true); } final File inputFile = fileSystem.file(entityPath); inputFile.copySync(destinationFile.path); inputs.add(inputFile); outputs.add(destinationFile); } if (icuDataPath != null) { final File inputFile = fileSystem.file(icuDataPath); final File outputFile = fileSystem.file(fileSystem.path.join(outputDirectory.path, inputFile.basename)); inputFile.copySync(outputFile.path); inputs.add(inputFile); outputs.add(outputFile); } if (clientSourcePaths == null) { return Depfile(inputs, outputs); } for (final String clientSourcePath in clientSourcePaths) { final Directory clientSourceDirectory = fileSystem.directory(clientSourcePath); if (!clientSourceDirectory.existsSync()) { throw Exception('Missing clientSourceDirectory: $clientSourcePath'); } for (final File input in clientSourceDirectory .listSync(recursive: true) .whereType<File>()) { final String outputPath = fileSystem.path.join( outputDirectory.path, fileSystem.path.relative(input.path, from: clientSourceDirectory.parent.path), ); final File destinationFile = fileSystem.file(outputPath); if (!destinationFile.parent.existsSync()) { destinationFile.parent.createSync(recursive: true); } final File inputFile = fileSystem.file(input); inputFile.copySync(destinationFile.path); inputs.add(inputFile); outputs.add(destinationFile); } } return Depfile(inputs, outputs); }
flutter/packages/flutter_tools/lib/src/build_system/targets/desktop.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/desktop.dart", "repo_id": "flutter", "token_count": 1024 }
746
// Copyright 2014 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 'base/file_system.dart'; import 'base/utils.dart'; import 'platform_plugins.dart'; import 'project.dart'; /// Represents a CMake-based sub-project. /// /// This defines interfaces common to Windows and Linux projects. abstract class CmakeBasedProject { /// The parent of this project. FlutterProject get parent; /// Whether the subproject (either Windows or Linux) exists in the Flutter project. bool existsSync(); /// The native project CMake specification. File get cmakeFile; /// Contains definitions for the Flutter library and the tool. File get managedCmakeFile; /// Contains definitions for FLUTTER_ROOT, LOCAL_ENGINE, and more flags for /// the build. File get generatedCmakeConfigFile; /// Included CMake with rules and variables for plugin builds. File get generatedPluginCmakeFile; /// The directory to write plugin symlinks. Directory get pluginSymlinkDirectory; } /// The Windows sub project. class WindowsProject extends FlutterProjectPlatform implements CmakeBasedProject { WindowsProject.fromFlutter(this.parent); @override final FlutterProject parent; @override String get pluginConfigKey => WindowsPlugin.kConfigKey; String get _childDirectory => 'windows'; @override bool existsSync() => _editableDirectory.existsSync() && cmakeFile.existsSync(); @override File get cmakeFile => _editableDirectory.childFile('CMakeLists.txt'); @override File get managedCmakeFile => managedDirectory.childFile('CMakeLists.txt'); @override File get generatedCmakeConfigFile => ephemeralDirectory.childFile('generated_config.cmake'); @override File get generatedPluginCmakeFile => managedDirectory.childFile('generated_plugins.cmake'); /// The native entrypoint's CMake specification. File get runnerCmakeFile => runnerDirectory.childFile('CMakeLists.txt'); /// The native entrypoint's file that adds Flutter to the window. File get runnerFlutterWindowFile => runnerDirectory.childFile('flutter_window.cpp'); /// The native entrypoint's resource file. Used to configure things /// like the application icon, name, and version. File get runnerResourceFile => runnerDirectory.childFile('Runner.rc'); @override Directory get pluginSymlinkDirectory => ephemeralDirectory.childDirectory('.plugin_symlinks'); Directory get _editableDirectory => parent.directory.childDirectory(_childDirectory); /// The directory in the project that is managed by Flutter. As much as /// possible, files that are edited by Flutter tooling after initial project /// creation should live here. Directory get managedDirectory => _editableDirectory.childDirectory('flutter'); /// The subdirectory of [managedDirectory] that contains files that are /// generated on the fly. All generated files that are not intended to be /// checked in should live here. Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral'); /// The directory in the project that is owned by the app. As much as /// possible, Flutter tooling should not edit files in this directory after /// initial project creation. Directory get runnerDirectory => _editableDirectory.childDirectory('runner'); Future<void> ensureReadyForPlatformSpecificTooling() async {} } /// The Linux sub project. class LinuxProject extends FlutterProjectPlatform implements CmakeBasedProject { LinuxProject.fromFlutter(this.parent); @override final FlutterProject parent; @override String get pluginConfigKey => LinuxPlugin.kConfigKey; static final RegExp _applicationIdPattern = RegExp(r'''^\s*set\s*\(\s*APPLICATION_ID\s*"(.*)"\s*\)\s*$'''); Directory get _editableDirectory => parent.directory.childDirectory('linux'); /// The directory in the project that is managed by Flutter. As much as /// possible, files that are edited by Flutter tooling after initial project /// creation should live here. Directory get managedDirectory => _editableDirectory.childDirectory('flutter'); /// The subdirectory of [managedDirectory] that contains files that are /// generated on the fly. All generated files that are not intended to be /// checked in should live here. Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral'); @override bool existsSync() => _editableDirectory.existsSync(); @override File get cmakeFile => _editableDirectory.childFile('CMakeLists.txt'); @override File get managedCmakeFile => managedDirectory.childFile('CMakeLists.txt'); @override File get generatedCmakeConfigFile => ephemeralDirectory.childFile('generated_config.cmake'); @override File get generatedPluginCmakeFile => managedDirectory.childFile('generated_plugins.cmake'); @override Directory get pluginSymlinkDirectory => ephemeralDirectory.childDirectory('.plugin_symlinks'); Future<void> ensureReadyForPlatformSpecificTooling() async {} String? get applicationId { return firstMatchInFile(cmakeFile, _applicationIdPattern)?.group(1); } }
flutter/packages/flutter_tools/lib/src/cmake_project.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/cmake_project.dart", "repo_id": "flutter", "token_count": 1354 }
747
// Copyright 2014 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 '../base/analyze_size.dart'; import '../base/common.dart'; import '../build_info.dart'; import '../cache.dart'; import '../features.dart'; import '../globals.dart' as globals; import '../macos/build_macos.dart'; import '../project.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; import 'build.dart'; /// A command to build a macOS desktop target through a build shell script. class BuildMacosCommand extends BuildSubCommand { BuildMacosCommand({ required super.logger, required bool verboseHelp, }) : super(verboseHelp: verboseHelp) { addCommonDesktopBuildOptions(verboseHelp: verboseHelp); usesFlavorOption(); argParser .addFlag('config-only', help: 'Update the project configuration without performing a build. ' 'This can be used in CI/CD process that create an archive to avoid ' 'performing duplicate work.' ); } @override final String name = 'macos'; @override bool get hidden => !featureFlags.isMacOSEnabled || !globals.platform.isMacOS; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{ DevelopmentArtifact.macOS, }; @override String get description => 'Build a macOS desktop application.'; @override bool get supported => globals.platform.isMacOS; bool get configOnly => boolArg('config-only'); @override Future<FlutterCommandResult> runCommand() async { final BuildInfo buildInfo = await getBuildInfo(); final FlutterProject flutterProject = FlutterProject.current(); if (!featureFlags.isMacOSEnabled) { throwToolExit('"build macos" is not currently supported. To enable, run "flutter config --enable-macos-desktop".'); } if (!supported) { throwToolExit('"build macos" only supported on macOS hosts.'); } displayNullSafetyMode(buildInfo); await buildMacOS( flutterProject: flutterProject, buildInfo: buildInfo, targetOverride: targetFile, verboseLogging: globals.logger.isVerbose, configOnly: configOnly, sizeAnalyzer: SizeAnalyzer( fileSystem: globals.fs, logger: globals.logger, appFilenamePattern: 'App', flutterUsage: globals.flutterUsage, analytics: analytics, ), ); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/build_macos.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/build_macos.dart", "repo_id": "flutter", "token_count": 850 }
748
// Copyright 2014 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:args/args.dart'; import 'package:meta/meta.dart'; import 'package:package_config/package_config_types.dart'; import '../android/android_device.dart'; import '../application_package.dart'; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/signals.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../dart/package_map.dart'; import '../device.dart'; import '../drive/drive_service.dart'; import '../drive/web_driver_service.dart' show Browser; import '../globals.dart' as globals; import '../ios/devices.dart'; import '../macos/macos_ipad_device.dart'; import '../resident_runner.dart'; import '../runner/flutter_command.dart' show FlutterCommandCategory, FlutterCommandResult, FlutterOptions; import '../web/web_device.dart'; import 'run.dart'; /// Runs integration (a.k.a. end-to-end) tests. /// /// An integration test is a program that runs in a separate process from your /// Flutter application. It connects to the application and acts like a user, /// performing taps, scrolls, reading out widget properties and verifying their /// correctness. /// /// This command takes a target Flutter application that you would like to test /// as the `--target` option (defaults to `lib/main.dart`). It then looks for a /// corresponding test file within the `test_driver` directory. The test file is /// expected to have the same name but contain the `_test.dart` suffix. The /// `_test.dart` file would generally be a Dart program that uses /// `package:flutter_driver` and exercises your application. Most commonly it /// is a test written using `package:test`, but you are free to use something /// else. /// /// The app and the test are launched simultaneously. Once the test completes /// the application is stopped and the command exits. If all these steps are /// successful the exit code will be `0`. Otherwise, you will see a non-zero /// exit code. class DriveCommand extends RunCommandBase { DriveCommand({ bool verboseHelp = false, @visibleForTesting FlutterDriverFactory? flutterDriverFactory, @visibleForTesting this.signalsToHandle = const <ProcessSignal>{ProcessSignal.sigint, ProcessSignal.sigterm}, required FileSystem fileSystem, required Logger logger, required Platform platform, required this.signals, }) : _flutterDriverFactory = flutterDriverFactory, _fileSystem = fileSystem, _logger = logger, _fsUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform), super(verboseHelp: verboseHelp) { requiresPubspecYaml(); addEnableExperimentation(hide: !verboseHelp); // By default, the drive app should not publish the VM service port over mDNS // to prevent a local network permission dialog on iOS 14+, // which cannot be accepted or dismissed in a CI environment. addPublishPort(enabledByDefault: false, verboseHelp: verboseHelp); argParser ..addFlag('keep-app-running', help: 'Will keep the Flutter application running when done testing.\n' 'By default, "flutter drive" stops the application after tests are finished, ' 'and "--keep-app-running" overrides this. On the other hand, if "--use-existing-app" ' 'is specified, then "flutter drive" instead defaults to leaving the application ' 'running, and "--no-keep-app-running" overrides it.', ) ..addOption('use-existing-app', help: 'Connect to an already running instance via the given Dart VM Service URL. ' 'If this option is given, the application will not be automatically started, ' 'and it will only be stopped if "--no-keep-app-running" is explicitly set.', valueHelp: 'url', ) ..addOption('driver', help: 'The test file to run on the host (as opposed to the target file to run on ' 'the device).\n' 'By default, this file has the same base name as the target file, but in the ' '"test_driver/" directory instead, and with "_test" inserted just before the ' 'extension, so e.g. if the target is "lib/main.dart", the driver will be ' '"test_driver/main_test.dart".', valueHelp: 'path', ) ..addFlag('build', defaultsTo: true, help: '(deprecated) Build the app before running. To use an existing app, pass the "--${FlutterOptions.kUseApplicationBinary}" ' 'flag with an existing APK.', ) ..addOption('screenshot', valueHelp: 'path/to/directory', help: 'Directory location to write screenshots on test failure.', ) ..addOption('driver-port', defaultsTo: '4444', help: 'The port where Webdriver server is launched at.', valueHelp: '4444' ) ..addFlag('headless', defaultsTo: true, help: 'Whether the driver browser is going to be launched in headless mode.', ) ..addOption( 'browser-name', defaultsTo: Browser.chrome.cliName, help: 'Name of the browser where tests will be executed.', allowed: Browser.values.map((Browser e) => e.cliName), allowedHelp: CliEnum.allowedHelp(Browser.values), ) ..addOption('browser-dimension', defaultsTo: '1600,1024', help: 'The dimension of the browser when running a Flutter Web test. ' 'This will affect screenshot and all offset-related actions.', valueHelp: 'width,height', ) ..addFlag('android-emulator', defaultsTo: true, help: 'Whether to perform Flutter Driver testing using an Android Emulator. ' 'Works only if "browser-name" is set to "android-chrome".') ..addOption('chrome-binary', help: 'Location of the Chrome binary. ' 'Works only if "browser-name" is set to "chrome".') ..addOption('write-sksl-on-exit', help: 'Attempts to write an SkSL file when the drive process is finished ' 'to the provided file, overwriting it if necessary.') ..addMultiOption('test-arguments', help: 'Additional arguments to pass to the ' 'Dart VM running The test script.') ..addOption('profile-memory', help: 'Launch devtools and profile application memory, writing ' 'The output data to the file path provided to this argument as JSON.', valueHelp: 'profile_memory.json') ..addOption('timeout', help: 'Timeout the test after the given number of seconds. If the ' '"--screenshot" option is provided, a screenshot will be taken ' 'before exiting. Defaults to no timeout.', valueHelp: '360'); } final Signals signals; /// The [ProcessSignal]s that will lead to a screenshot being taken (if the option is provided). final Set<ProcessSignal> signalsToHandle; // `pub` must always be run due to the test script running from source, // even if an application binary is used. Default to true unless the user explicitly // specified not to. @override bool get shouldRunPub { if (argResults!.wasParsed('pub') && !boolArg('pub')) { return false; } return true; } FlutterDriverFactory? _flutterDriverFactory; final FileSystem _fileSystem; final Logger _logger; final FileSystemUtils _fsUtils; Timer? timeoutTimer; Map<ProcessSignal, Object>? screenshotTokens; @override final String name = 'drive'; @override final String description = 'Run integration tests for the project on an attached device or emulator.'; @override String get category => FlutterCommandCategory.project; @override final List<String> aliases = <String>['driver']; String? get userIdentifier => stringArg(FlutterOptions.kDeviceUser); String? get screenshot => stringArg('screenshot'); @override bool get startPausedDefault => true; @override bool get cachePubGet => false; String? get applicationBinaryPath => stringArg(FlutterOptions.kUseApplicationBinary); Future<Device?> get targetedDevice async { return findTargetDevice( includeDevicesUnsupportedByProject: applicationBinaryPath == null, ); } // Wireless iOS devices need `publish-port` to be enabled because it requires mDNS. // If the flag wasn't provided as an actual argument and it's a wireless device, // change it to be enabled. @override Future<bool> get disablePortPublication async { final ArgResults? localArgResults = argResults; final Device? device = await targetedDevice; final bool isWirelessIOSDevice = device is IOSDevice && device.isWirelesslyConnected; if (isWirelessIOSDevice && localArgResults != null && !localArgResults.wasParsed('publish-port')) { _logger.printTrace('A wireless iOS device is being used. Changing `publish-port` to be enabled.'); return false; } return !boolArg('publish-port'); } @override Future<void> validateCommand() async { if (userIdentifier != null) { final Device? device = await findTargetDevice(); if (device is! AndroidDevice) { throwToolExit('--${FlutterOptions.kDeviceUser} is only supported for Android'); } if (device is MacOSDesignedForIPadDevice) { throwToolExit('Mac Designed for iPad is currently not supported for flutter drive.'); } } return super.validateCommand(); } @override Future<FlutterCommandResult> runCommand() async { final String? testFile = _getTestFile(); if (testFile == null) { throwToolExit(null); } if (await _fileSystem.type(testFile) != FileSystemEntityType.file) { throwToolExit('Test file not found: $testFile'); } final Device? device = await targetedDevice; if (device == null) { throwToolExit(null); } if (screenshot != null && !device.supportsScreenshot) { _logger.printError('Screenshot not supported for ${device.name}.'); } final bool web = device is WebServerDevice || device is ChromiumDevice; _flutterDriverFactory ??= FlutterDriverFactory( applicationPackageFactory: ApplicationPackageFactory.instance!, logger: _logger, processUtils: globals.processUtils, dartSdkPath: globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), devtoolsLauncher: DevtoolsLauncher.instance!, ); final PackageConfig packageConfig = await loadPackageConfigWithLogging( _fileSystem.file('.packages'), logger: _logger, throwOnError: false, ); final DriverService driverService = _flutterDriverFactory!.createDriverService(web); final BuildInfo buildInfo = await getBuildInfo(); final DebuggingOptions debuggingOptions = await createDebuggingOptions(web); final File? applicationBinary = applicationBinaryPath == null ? null : _fileSystem.file(applicationBinaryPath); bool screenshotTaken = false; try { if (stringArg('use-existing-app') == null) { await driverService.start( buildInfo, device, debuggingOptions, ipv6 ?? false, applicationBinary: applicationBinary, route: route, userIdentifier: userIdentifier, mainPath: targetFile, platformArgs: <String, Object>{ if (traceStartup) 'trace-startup': traceStartup, if (web) '--no-launch-chrome': true, } ); } else { final Uri? uri = Uri.tryParse(stringArg('use-existing-app')!); if (uri == null) { throwToolExit('Invalid VM Service URI: ${stringArg('use-existing-app')}'); } await driverService.reuseApplication( uri, device, debuggingOptions, ipv6 ?? false, ); } final Future<int> testResultFuture = driverService.startTest( testFile, stringsArg('test-arguments'), <String, String>{}, packageConfig, chromeBinary: stringArg('chrome-binary'), headless: boolArg('headless'), webBrowserFlags: stringsArg(FlutterOptions.kWebBrowserFlag), browserDimension: stringArg('browser-dimension')!.split(','), browserName: stringArg('browser-name'), driverPort: stringArg('driver-port') != null ? int.tryParse(stringArg('driver-port')!) : null, androidEmulator: boolArg('android-emulator'), profileMemory: stringArg('profile-memory'), ); if (screenshot != null) { // If the test is sent a signal or times out, take a screenshot _registerScreenshotCallbacks(device, _fileSystem.directory(screenshot)); } final int testResult = await testResultFuture; if (timeoutTimer != null) { timeoutTimer!.cancel(); } _unregisterScreenshotCallbacks(); if (testResult != 0 && screenshot != null) { // Take a screenshot while the app is still running. await _takeScreenshot(device, _fileSystem.directory(screenshot)); screenshotTaken = true; } if (boolArg('keep-app-running')) { _logger.printStatus('Leaving the application running.'); } else { final File? skslFile = stringArg('write-sksl-on-exit') != null ? _fileSystem.file(stringArg('write-sksl-on-exit')) : null; await driverService.stop(userIdentifier: userIdentifier, writeSkslOnExit: skslFile); } if (testResult != 0) { throwToolExit(null); } } on Exception catch (_) { // On exceptions, including ToolExit, take a screenshot on the device // unless a screenshot was already taken on test failure. if (!screenshotTaken && screenshot != null) { await _takeScreenshot(device, _fileSystem.directory(screenshot)); } rethrow; } return FlutterCommandResult.success(); } int? get _timeoutSeconds { final String? timeoutString = stringArg('timeout'); if (timeoutString == null) { return null; } final int? timeoutSeconds = int.tryParse(timeoutString); if (timeoutSeconds == null || timeoutSeconds <= 0) { throwToolExit( 'Invalid value "$timeoutString" provided to the option --timeout: ' 'expected a positive integer representing seconds.', ); } return timeoutSeconds; } void _registerScreenshotCallbacks(Device device, Directory screenshotDir) { _logger.printTrace('Registering signal handlers...'); final Map<ProcessSignal, Object> tokens = <ProcessSignal, Object>{}; for (final ProcessSignal signal in signalsToHandle) { tokens[signal] = signals.addHandler( signal, (ProcessSignal signal) { _unregisterScreenshotCallbacks(); _logger.printError('Caught $signal'); return _takeScreenshot(device, screenshotDir); }, ); } screenshotTokens = tokens; final int? timeoutSeconds = _timeoutSeconds; if (timeoutSeconds != null) { timeoutTimer = Timer( Duration(seconds: timeoutSeconds), () { _unregisterScreenshotCallbacks(); _takeScreenshot(device, screenshotDir); throwToolExit('Timed out after $timeoutSeconds seconds'); } ); } } void _unregisterScreenshotCallbacks() { if (screenshotTokens != null) { _logger.printTrace('Unregistering signal handlers...'); for (final MapEntry<ProcessSignal, Object> entry in screenshotTokens!.entries) { signals.removeHandler(entry.key, entry.value); } } timeoutTimer?.cancel(); } String? _getTestFile() { if (argResults!['driver'] != null) { return stringArg('driver'); } // If the --driver argument wasn't provided, then derive the value from // the target file. String appFile = _fileSystem.path.normalize(targetFile); // This command extends `flutter run` and therefore CWD == package dir final String packageDir = _fileSystem.currentDirectory.path; // Make appFile path relative to package directory because we are looking // for the corresponding test file relative to it. if (!_fileSystem.path.isRelative(appFile)) { if (!_fileSystem.path.isWithin(packageDir, appFile)) { _logger.printError( 'Application file $appFile is outside the package directory $packageDir' ); return null; } appFile = _fileSystem.path.relative(appFile, from: packageDir); } final List<String> parts = _fileSystem.path.split(appFile); if (parts.length < 2) { _logger.printError( 'Application file $appFile must reside in one of the sub-directories ' 'of the package structure, not in the root directory.' ); return null; } // Look for the test file inside `test_driver/` matching the sub-path, e.g. // if the application is `lib/foo/bar.dart`, the test file is expected to // be `test_driver/foo/bar_test.dart`. final String pathWithNoExtension = _fileSystem.path.withoutExtension(_fileSystem.path.joinAll( <String>[packageDir, 'test_driver', ...parts.skip(1)])); return '${pathWithNoExtension}_test${_fileSystem.path.extension(appFile)}'; } Future<void> _takeScreenshot(Device device, Directory outputDirectory) async { if (!device.supportsScreenshot) { return; } try { outputDirectory.createSync(recursive: true); final File outputFile = _fsUtils.getUniqueFile( outputDirectory, 'drive', 'png', ); await device.takeScreenshot(outputFile); _logger.printStatus('Screenshot written to ${outputFile.path}'); } on Exception catch (error) { _logger.printError('Error taking screenshot: $error'); } } }
flutter/packages/flutter_tools/lib/src/commands/drive.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/drive.dart", "repo_id": "flutter", "token_count": 6502 }
749
// Copyright 2014 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:collection'; import 'package:meta/meta.dart'; import '../base/common.dart'; import '../base/context.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/net.dart'; import '../base/task_queue.dart'; import '../cache.dart'; import '../dart/pub.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../runner/flutter_command.dart'; import '../update_packages_pins.dart'; import '../version.dart'; class UpdatePackagesCommand extends FlutterCommand { UpdatePackagesCommand() { argParser ..addFlag( 'force-upgrade', help: 'Attempt to update all the dependencies to their latest versions.\n' 'This will actually modify the pubspec.yaml files in your checkout.', negatable: false, ) ..addOption( 'cherry-pick-package', help: 'Attempt to update only the specified package. The "-cherry-pick-version" version must be specified also.', ) ..addOption( 'cherry-pick-version', help: 'Attempt to update the package to the specified version. The "--cherry-pick-package" option must be specified also.', ) ..addFlag( 'paths', help: 'Finds paths in the dependency chain leading from package specified ' 'in "--from" to package specified in "--to".', negatable: false, ) ..addOption( 'from', help: 'Used with "--dependency-path". Specifies the package to begin ' 'searching dependency path from.', ) ..addOption( 'to', help: 'Used with "--dependency-path". Specifies the package that the ' 'sought-after dependency path leads to.', ) ..addFlag( 'transitive-closure', help: 'Prints the dependency graph that is the transitive closure of ' 'packages the Flutter SDK depends on.', negatable: false, ) ..addFlag( 'consumer-only', help: 'Only prints the dependency graph that is the transitive closure ' 'that a consumer of the Flutter SDK will observe (when combined ' 'with transitive-closure).', negatable: false, ) ..addFlag( 'verify-only', help: 'Verifies the package checksum without changing or updating deps.', negatable: false, ) ..addFlag( 'offline', help: 'Use cached packages instead of accessing the network.', negatable: false, ) ..addFlag( 'crash', help: 'For Flutter CLI testing only, forces this command to throw an unhandled exception.', negatable: false, ) ..addOption( 'jobs', abbr: 'j', help: 'Causes the "pub get" runs to happen concurrently on this many ' 'CPUs. Defaults to the number of CPUs that this machine has.', ) ..addOption( 'synthetic-package-path', help: 'Write the synthetic monolithic pub package generated to do ' 'version solving to a persistent path. By default, a temporary ' 'directory that is deleted before the command exits. By ' 'providing this path, a Flutter maintainer can inspect further ' 'exactly how version solving was achieved.', ); } @override final String name = 'update-packages'; @override final String description = 'Update the packages inside the Flutter repo. ' 'This is intended for CI and repo maintainers. ' 'Normal Flutter developers should not have to ' 'use this command.'; @override final List<String> aliases = <String>['upgrade-packages']; @override final bool hidden = true; // Lazy-initialize the net utilities with values from the context. late final Net _net = Net( httpClientFactory: context.get<HttpClientFactory>(), logger: globals.logger, platform: globals.platform, ); Future<void> _downloadCoverageData() async { final String urlBase = globals.platform.environment[kFlutterStorageBaseUrl] ?? 'https://storage.googleapis.com'; final Uri coverageUri = Uri.parse('$urlBase/flutter_infra_release/flutter/coverage/lcov.info'); final List<int>? data = await _net.fetchUrl( coverageUri, maxAttempts: 3, ); if (data == null) { throwToolExit('Failed to fetch coverage data from $coverageUri'); } final String coverageDir = globals.fs.path.join( Cache.flutterRoot!, 'packages/flutter/coverage', ); globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.base.info')) ..createSync(recursive: true) ..writeAsBytesSync(data, flush: true); globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.info')) ..createSync(recursive: true) ..writeAsBytesSync(data, flush: true); } late final Directory _syntheticPackageDir = (() { final String? optionPath = stringArg('synthetic-package-path'); if (optionPath == null) { return globals.fs.systemTempDirectory.createTempSync('flutter_update_packages.'); } final Directory syntheticPackageDir = globals.fs.directory(optionPath); if (!syntheticPackageDir.existsSync()) { syntheticPackageDir.createSync(recursive: true); } globals.printStatus( 'The synthetic package with all pub dependencies across the repo will ' 'be written to ${syntheticPackageDir.absolute.path}.', ); return syntheticPackageDir; })(); @override Future<FlutterCommandResult> runCommand() async { final List<Directory> packages = runner!.getRepoPackages(); final bool forceUpgrade = boolArg('force-upgrade'); final bool isPrintPaths = boolArg('paths'); final bool isPrintTransitiveClosure = boolArg('transitive-closure'); final bool isVerifyOnly = boolArg('verify-only'); final bool isConsumerOnly = boolArg('consumer-only'); final bool offline = boolArg('offline'); final String? cherryPickPackage = stringArg('cherry-pick-package'); final String? cherryPickVersion = stringArg('cherry-pick-version'); if (boolArg('crash')) { throw StateError('test crash please ignore.'); } if (forceUpgrade && offline) { throwToolExit( '--force-upgrade cannot be used with the --offline flag' ); } if (forceUpgrade && cherryPickPackage != null) { throwToolExit( '--force-upgrade cannot be used with the --cherry-pick-package flag' ); } if (forceUpgrade && isPrintPaths) { throwToolExit( '--force-upgrade cannot be used with the --paths flag' ); } if (forceUpgrade && isPrintTransitiveClosure) { throwToolExit( '--force-upgrade cannot be used with the --transitive-closure flag' ); } if (cherryPickPackage != null && offline) { throwToolExit( '--cherry-pick-package cannot be used with the --offline flag' ); } if (cherryPickPackage != null && cherryPickVersion == null) { throwToolExit( '--cherry-pick-version is required when using --cherry-pick-package flag' ); } if (isPrintPaths && (stringArg('from') == null || stringArg('to') == null)) { throwToolExit( 'The --from and --to flags are required when using the --paths flag' ); } if (!isPrintPaths && (stringArg('from') != null || stringArg('to') != null)) { throwToolExit( 'The --from and --to flags are only allowed when using the --paths flag' ); } if (isPrintTransitiveClosure && isPrintPaths) { throwToolExit( 'The --transitive-closure flag cannot be used with the --paths flag' ); } // "consumer" packages are those that constitute our public API (e.g. flutter, flutter_test, flutter_driver, flutter_localizations, integration_test). if (isConsumerOnly) { if (!isPrintTransitiveClosure) { throwToolExit( '--consumer-only can only be used with the --transitive-closure flag' ); } // Only retain flutter, flutter_test, flutter_driver, and flutter_localizations. const List<String> consumerPackages = <String>['flutter', 'flutter_test', 'flutter_driver', 'flutter_localizations', 'integration_test']; // ensure we only get flutter/packages packages.retainWhere((Directory directory) { return consumerPackages.any((String package) { return directory.path.endsWith('packages${globals.fs.path.separator}$package'); }); }); } if (isVerifyOnly) { _verifyPubspecs(packages); return FlutterCommandResult.success(); } if (forceUpgrade) { // This feature attempts to collect all the packages used across all the // pubspec.yamls in the repo (including via transitive dependencies), and // find the latest version of each that can be used while keeping each // such package fixed at a single version across all the pubspec.yamls. globals.printStatus('Upgrading packages...'); } // First, collect the dependencies: final List<PubspecYaml> pubspecs = <PubspecYaml>[]; final Map<String, PubspecDependency> explicitDependencies = <String, PubspecDependency>{}; final Map<String, PubspecDependency> allDependencies = <String, PubspecDependency>{}; final Set<String> specialDependencies = <String>{}; _collectDependencies( packages: packages, pubspecs: pubspecs, explicitDependencies: explicitDependencies, allDependencies: allDependencies, specialDependencies: specialDependencies, printPaths: forceUpgrade || isPrintPaths || isPrintTransitiveClosure || cherryPickPackage != null, ); final Iterable<PubspecDependency> baseDependencies; if (cherryPickPackage != null) { if (!allDependencies.containsKey(cherryPickPackage)) { throwToolExit( 'Package "$cherryPickPackage" is not currently a dependency, and therefore cannot be upgraded.' ); } if (cherryPickVersion != null) { globals.printStatus('Pinning package "$cherryPickPackage" to version "$cherryPickVersion"...'); } else { globals.printStatus('Upgrading package "$cherryPickPackage"...'); } final List<PubspecDependency> adjustedDependencies = <PubspecDependency>[]; for (final String package in allDependencies.keys) { if (package == cherryPickPackage) { assert(cherryPickVersion != null); final PubspecDependency pubspec = allDependencies[cherryPickPackage]!; adjustedDependencies.add(pubspec.copyWith(version: cherryPickVersion)); } else { adjustedDependencies.add(allDependencies[package]!); } } baseDependencies = adjustedDependencies; } else if (forceUpgrade) { baseDependencies = explicitDependencies.values; } else { baseDependencies = allDependencies.values; } // Now that we have all the dependencies we care about, we are going to // create a fake package and then run either "pub upgrade", if requested, // followed by "pub get" on it. If upgrading, the pub tool will attempt to // bring these dependencies up to the most recent possible versions while // honoring all their constraints. If not upgrading the pub tool will only // attempt to download any necessary package versions to the pub cache to // warm the cache. final PubDependencyTree tree = PubDependencyTree(); // object to collect results await _pubGetAllDependencies( tempDir: _syntheticPackageDir, dependencies: baseDependencies, pubspecs: pubspecs, tree: tree, doUpgrade: forceUpgrade, isolateEnvironment: forceUpgrade || isPrintPaths || isPrintTransitiveClosure || cherryPickPackage != null, reportDependenciesToTree: forceUpgrade || isPrintPaths || isPrintTransitiveClosure || cherryPickPackage != null, ); // Only delete the synthetic package if it was done in a temp directory if (stringArg('synthetic-package-path') == null) { _syntheticPackageDir.deleteSync(recursive: true); } if (forceUpgrade || isPrintTransitiveClosure || isPrintPaths || cherryPickPackage != null) { _processPubspecs( tree: tree, pubspecs: pubspecs, specialDependencies: specialDependencies, ); if (isPrintTransitiveClosure) { tree._dependencyTree.forEach((String from, Set<String> to) { globals.printStatus('$from -> $to'); }); return FlutterCommandResult.success(); } if (isPrintPaths) { showDependencyPaths(from: stringArg('from')!, to: stringArg('to')!, tree: tree); return FlutterCommandResult.success(); } globals.printStatus('Updating workspace...'); _updatePubspecs( tree: tree, pubspecs: pubspecs, specialDependencies: specialDependencies, ); } await _runPubGetOnPackages(packages); return FlutterCommandResult.success(); } void _verifyPubspecs(List<Directory> packages) { bool needsUpdate = false; globals.printStatus('Verifying pubspecs...'); for (final Directory directory in packages) { final PubspecYaml pubspec = PubspecYaml(directory); globals.printTrace('Reading pubspec.yaml from ${directory.path}'); if (pubspec.checksum.value == null) { // If the checksum is invalid or missing, we can just ask them run to run // upgrade again to compute it. globals.printWarning( 'Warning: pubspec in ${directory.path} has out of date dependencies. ' 'Please run "flutter update-packages --force-upgrade" to update them correctly.' ); needsUpdate = true; } // all dependencies in the pubspec sorted lexically. final Map<String, String> checksumDependencies = <String, String>{}; for (final PubspecLine data in pubspec.inputData) { if (data is PubspecDependency && data.kind == DependencyKind.normal) { checksumDependencies[data.name] = data.version; } } final String checksum = _computeChecksum(checksumDependencies.keys, (String name) => checksumDependencies[name]!); if (checksum != pubspec.checksum.value) { // If the checksum doesn't match, they may have added or removed some dependencies. // we need to run update-packages to recapture the transitive deps. globals.printWarning( 'Warning: pubspec in ${directory.path} has updated or new dependencies. ' 'Please run "flutter update-packages --force-upgrade" to update them correctly.' // DO NOT PRINT THE CHECKSUM HERE. // It causes people to ignore the requirement to actually run the script. ); needsUpdate = true; } else { // everything is correct in the pubspec. globals.printTrace('pubspec in ${directory.path} is up to date!'); } } if (needsUpdate) { throwToolExit( 'Warning: one or more pubspecs have invalid dependencies. ' 'Please run "flutter update-packages --force-upgrade" to update them correctly.', exitCode: 1, ); } globals.printStatus('All pubspecs were up to date.'); } void _collectDependencies({ required List<Directory> packages, required List<PubspecYaml> pubspecs, required Set<String> specialDependencies, required Map<String, PubspecDependency> explicitDependencies, required Map<String, PubspecDependency> allDependencies, required bool printPaths, }) { // Visit all the directories with pubspec.yamls we care about. for (final Directory directory in packages) { if (printPaths) { globals.printTrace('Reading pubspec.yaml from: ${directory.path}'); } final PubspecYaml pubspec = PubspecYaml(directory); // this parses the pubspec.yaml pubspecs.add(pubspec); // remember it for later for (final PubspecDependency dependency in pubspec.allDependencies) { if (allDependencies.containsKey(dependency.name)) { // If we've seen the dependency before, make sure that we are // importing it the same way. There's several ways to import a // dependency. Hosted (from pub via version number), by path (e.g. // pointing at the version of a package we get from the Dart SDK // that we download with Flutter), by SDK (e.g. the "flutter" // package is explicitly from "sdk: flutter"). // // This makes sure that we don't import a package in two different // ways, e.g. by saying "sdk: flutter" in one pubspec.yaml and // saying "path: ../../..." in another. final PubspecDependency previous = allDependencies[dependency.name]!; if (dependency.kind != previous.kind || dependency._lockTarget != previous._lockTarget) { throwToolExit( 'Inconsistent requirements around ${dependency.name}; ' 'saw ${dependency.kind} (${dependency._lockTarget}) in "${dependency.sourcePath}" ' 'and ${previous.kind} (${previous._lockTarget}) in "${previous.sourcePath}".' ); } if (dependency.version != previous.version) { globals.printError( 'Requiring multiple versions: multiple versions required by ${dependency.name}; ' 'saw ${dependency.version} in "${dependency.sourcePath}" ' 'and ${previous.version} in "${previous.sourcePath}".' ); } } allDependencies[dependency.name] = dependency; } for (final PubspecDependency dependency in pubspec.allExplicitDependencies) { if (explicitDependencies.containsKey(dependency.name)) { // If we've seen the dependency before, make sure that we are // importing it the same way. There's several ways to import a // dependency. Hosted (from pub via version number), by path (e.g. // pointing at the version of a package we get from the Dart SDK // that we download with Flutter), by SDK (e.g. the "flutter" // package is explicitly from "sdk: flutter"). // // This makes sure that we don't import a package in two different // ways, e.g. by saying "sdk: flutter" in one pubspec.yaml and // saying "path: ../../..." in another. final PubspecDependency previous = explicitDependencies[dependency.name]!; if (dependency.kind != previous.kind || dependency._lockTarget != previous._lockTarget) { throwToolExit( 'Inconsistent requirements around ${dependency.name}; ' 'saw ${dependency.kind} (${dependency._lockTarget}) in "${dependency.sourcePath}" ' 'and ${previous.kind} (${previous._lockTarget}) in "${previous.sourcePath}".' ); } } // Remember this dependency by name so we can look it up again. explicitDependencies[dependency.name] = dependency; // Normal dependencies are those we get from pub. The others we // already implicitly pin since we pull down one version of the // Flutter and Dart SDKs, so we track which those are here so that we // can omit them from our list of pinned dependencies later. if (dependency.kind != DependencyKind.normal) { specialDependencies.add(dependency.name); } } } } Future<void> _pubGetAllDependencies({ required Directory tempDir, required Iterable<PubspecDependency> dependencies, required List<PubspecYaml> pubspecs, required PubDependencyTree tree, required bool doUpgrade, required bool isolateEnvironment, required bool reportDependenciesToTree, }) async { Directory? temporaryFlutterSdk; final Directory syntheticPackageDir = tempDir.childDirectory('synthetic_package'); final File fakePackage = _pubspecFor(syntheticPackageDir); fakePackage.createSync(recursive: true); fakePackage.writeAsStringSync( generateFakePubspec( dependencies, doUpgrade: doUpgrade, ), ); if (isolateEnvironment) { // Create a synthetic flutter SDK so that transitive flutter SDK // constraints are not affected by this upgrade. temporaryFlutterSdk = createTemporaryFlutterSdk( globals.logger, globals.fs, globals.fs.directory(Cache.flutterRoot), pubspecs, tempDir, ); } // Run "pub get" on it in order to force the download of any // needed packages to the pub cache, upgrading if requested. // TODO(ianh): If this fails, the tool exits silently. // It can fail, e.g., if --cherry-pick-version is invalid. await pub.get( context: PubContext.updatePackages, project: FlutterProject.fromDirectory(syntheticPackageDir), upgrade: doUpgrade, offline: boolArg('offline'), flutterRootOverride: temporaryFlutterSdk?.path, outputMode: PubOutputMode.none, ); if (reportDependenciesToTree) { // Run "pub deps --style=compact" on the result. // We pipe all the output to tree.fill(), which parses it so that it can // create a graph of all the dependencies so that we can figure out the // transitive dependencies later. It also remembers which version was // selected for each package. await pub.batch( <String>['deps', '--style=compact'], context: PubContext.updatePackages, directory: syntheticPackageDir.path, filter: tree.fill, ); } } void _processPubspecs({ required PubDependencyTree tree, required List<PubspecYaml> pubspecs, required Set<String> specialDependencies, }) { for (final PubspecYaml pubspec in pubspecs) { final String package = pubspec.name; specialDependencies.add(package); tree._versions[package] = pubspec.version; for (final PubspecDependency dependency in pubspec.dependencies) { if (dependency.kind == DependencyKind.normal) { tree._dependencyTree[package] ??= <String>{}; tree._dependencyTree[package]!.add(dependency.name); } } } } bool _updatePubspecs({ required PubDependencyTree tree, required List<PubspecYaml> pubspecs, required Set<String> specialDependencies, }) { // Now that we have collected all the data, we can apply our dependency // versions to each pubspec.yaml that we collected. This mutates the // pubspec.yaml files. // // The specialDependencies argument is the set of package names to not pin // to specific versions because they are explicitly pinned by their // constraints. Here we list the names we earlier established we didn't // need to pin because they come from the Dart or Flutter SDKs. for (final PubspecYaml pubspec in pubspecs) { pubspec.apply(tree, specialDependencies); } return false; } Future<void> _runPubGetOnPackages(List<Directory> packages) async { final Stopwatch timer = Stopwatch()..start(); int count = 0; // Now we run pub get on each of the affected packages to update their // pubspec.lock files with the right transitive dependencies. // // This can be expensive, so we run them in parallel. If we hadn't already // warmed the cache above, running them in parallel could be dangerous due // to contention when unpacking downloaded dependencies, but since we have // downloaded all that we need, it is safe to run them in parallel. final Status status = globals.logger.startProgress( 'Running "flutter pub get" in affected packages...', ); try { // int.tryParse will not accept null, but will convert empty string to null final int? maxJobs = int.tryParse(stringArg('jobs') ?? ''); final TaskQueue<void> queue = TaskQueue<void>(maxJobs: maxJobs); for (final Directory dir in packages) { unawaited(queue.add(() async { final Stopwatch stopwatch = Stopwatch(); stopwatch.start(); await pub.get( context: PubContext.updatePackages, project: FlutterProject.fromDirectory(dir), // All dependencies should already have been downloaded by the fake // package, so the concurrent checks can all happen offline. offline: true, outputMode: PubOutputMode.none, ); stopwatch.stop(); final double seconds = stopwatch.elapsedMilliseconds / 1000.0; final String relativeDir = globals.fs.path.relative(dir.path, from: Cache.flutterRoot); globals.printStatus('Ran pub get in $relativeDir in ${seconds.toStringAsFixed(1)}s...'); })); count += 1; } unawaited(queue.add(() async { final Stopwatch stopwatch = Stopwatch(); await _downloadCoverageData(); stopwatch.stop(); final double seconds = stopwatch.elapsedMilliseconds / 1000.0; globals.printStatus('Downloaded lcov data for package:flutter in ${seconds.toStringAsFixed(1)}s...'); })); await queue.tasksComplete; status.stop(); // The exception is rethrown, so don't catch only Exceptions. } catch (exception) { // ignore: avoid_catches_without_on_clauses status.cancel(); rethrow; } final double seconds = timer.elapsedMilliseconds / 1000.0; globals.printStatus("\nRan 'pub get' $count time${count == 1 ? "" : "s"} and fetched coverage data in ${seconds.toStringAsFixed(1)}s."); } void showDependencyPaths({ required String from, required String to, required PubDependencyTree tree, }) { if (!tree.contains(from)) { throwToolExit('Package $from not found in the dependency tree.'); } if (!tree.contains(to)) { throwToolExit('Package $to not found in the dependency tree.'); } final Queue<_DependencyLink> traversalQueue = Queue<_DependencyLink>(); final Set<String> visited = <String>{}; final List<_DependencyLink> paths = <_DependencyLink>[]; traversalQueue.addFirst(_DependencyLink(from: null, to: from)); while (traversalQueue.isNotEmpty) { final _DependencyLink link = traversalQueue.removeLast(); if (link.to == to) { paths.add(link); } if (link.from != null) { visited.add(link.from!.to); } for (final String dependency in tree._dependencyTree[link.to]!) { if (!visited.contains(dependency)) { traversalQueue.addFirst(_DependencyLink(from: link, to: dependency)); } } } for (_DependencyLink? path in paths) { final StringBuffer buf = StringBuffer(); while (path != null) { buf.write(path.to); path = path.from; if (path != null) { buf.write(' <- '); } } globals.printStatus(buf.toString(), wrap: false); } if (paths.isEmpty) { globals.printStatus('No paths found from $from to $to'); } } } class _DependencyLink { _DependencyLink({ required this.from, required this.to, }); final _DependencyLink? from; final String to; @override String toString() => '${from?.to} -> $to'; } /// The various sections of a pubspec.yaml file. /// /// We care about the "dependencies", "dev_dependencies", and /// "dependency_overrides" sections, as well as the "name" and "version" fields /// in the pubspec header bucketed into [header]. The others are all bucketed /// into [other]. enum Section { header, dependencies, devDependencies, dependencyOverrides, builders, other } /// The various kinds of dependencies we know and care about. enum DependencyKind { // Dependencies that will be path or sdk dependencies but // for which we haven't yet parsed the data. unknown, // Regular dependencies with a specified version range. normal, // Dependency that uses an explicit path, e.g. into the Dart SDK. path, // Dependency defined as coming from an SDK (typically "sdk: flutter"). sdk, // A dependency that was "normal", but for which we later found a "path" or // "sdk" dependency in the dependency_overrides section. overridden, // A dependency that uses git. git, } /// This is the string we output next to each of our autogenerated transitive /// dependencies so that we can ignore them the next time we parse the /// pubspec.yaml file. const String kTransitiveMagicString= '# THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"'; /// This is the string output before a checksum of the packages used. const String kDependencyChecksum = '# PUBSPEC CHECKSUM: '; /// This class represents a pubspec.yaml file for the purposes of upgrading the /// dependencies as done by this file. class PubspecYaml { /// You create one of these by providing a directory, from which we obtain the /// pubspec.yaml and parse it into a line-by-line form. factory PubspecYaml(Directory directory) { final File file = _pubspecFor(directory); return _parse(file, file.readAsLinesSync()); } PubspecYaml._(this.file, this.name, this.version, this.inputData, this.checksum); final File file; // The actual pubspec.yaml file. /// The package name. final String name; /// The package version. final String? version; final List<PubspecLine> inputData; // Each line of the pubspec.yaml file, parsed(ish). /// The package checksum. /// /// If this was not found in the pubspec, a synthetic checksum is created /// with a value of `-1`. final PubspecChecksum checksum; /// This parses each line of a pubspec.yaml file (a list of lines) into /// slightly more structured data (in the form of a list of PubspecLine /// objects). We don't just use a YAML parser because we care about comments /// and also because we can just define the style of pubspec.yaml files we care /// about (since they're all under our control). static PubspecYaml _parse(File file, List<String> lines) { final String filename = file.path; String? packageName; String? packageVersion; PubspecChecksum? checksum; // the checksum value used to verify that dependencies haven't changed. final List<PubspecLine> result = <PubspecLine>[]; // The output buffer. Section section = Section.other; // Which section we're currently reading from. bool seenMain = false; // Whether we've seen the "dependencies:" section. bool seenDev = false; // Whether we've seen the "dev_dependencies:" section. // The masterDependencies map is used to keep track of the objects // representing actual dependencies we've seen so far in this file so that // if we see dependency overrides we can update the actual dependency so it // knows that it's not really a dependency. final Map<String, PubspecDependency> masterDependencies = <String, PubspecDependency>{}; // The "special" dependencies (the ones that use git: or path: or sdk: or // whatnot) have the style of having extra data after the line that declares // the dependency. So we track what is the "current" (or "last") dependency // that we are dealing with using this variable. PubspecDependency? lastDependency; for (int index = 0; index < lines.length; index += 1) { String line = lines[index]; if (lastDependency == null) { // First we look to see if we're transitioning to a new top-level section. // The PubspecHeader.parse static method can recognize those headers. final PubspecHeader? header = PubspecHeader.parse(line); // See if it's a header. if (header != null) { // It is! section = header.section; // The parser determined what kind of section it is. if (section == Section.header) { if (header.name == 'name') { packageName = header.value; } else if (header.name == 'version') { packageVersion = header.value; } } else if (section == Section.dependencies) { // If we're entering the "dependencies" section, we want to make sure that // it's the first section (of those we care about) that we've seen so far. if (seenMain) { throwToolExit('Two dependencies sections found in $filename. There should only be one.'); } if (seenDev) { throwToolExit('The dependencies section was after the dev_dependencies section in $filename. ' 'To enable one-pass processing, the dependencies section must come before the ' 'dev_dependencies section.'); } seenMain = true; } else if (section == Section.devDependencies) { // Similarly, if we're entering the dev_dependencies section, we should verify // that we've not seen one already. if (seenDev) { throwToolExit('Two dev_dependencies sections found in $filename. There should only be one.'); } seenDev = true; } result.add(header); } else if (section == Section.builders) { // Do nothing. // This line isn't a section header, and we're not in a section we care about. // We just stick the line into the output unmodified. result.add(PubspecLine(line)); } else if (section == Section.other) { if (line.contains(kDependencyChecksum)) { // This is the pubspec checksum. After computing it, we remove it from the output data // since it will be recomputed later. checksum = PubspecChecksum.parse(line); } else { // This line isn't a section header, and we're not in a section we care about. // We just stick the line into the output unmodified. result.add(PubspecLine(line)); } } else { // We're in a section we care about. Try to parse out the dependency: final PubspecDependency? dependency = PubspecDependency.parse(line, filename: filename, isDevDependency: seenDev); if (dependency != null) { // We got one! result.add(dependency); if (dependency.kind == DependencyKind.unknown) { // If we didn't get a version number, then we need to be ready to // read the next line as part of this dependency, so keep track of // this dependency object. lastDependency = dependency; } if (section != Section.dependencyOverrides) { // If we're not in the overrides section, then just remember the // dependency, in case it comes up again later in the overrides // section. // // First, make sure it's a unique dependency. Listing dependencies // twice doesn't make sense. if (masterDependencies.containsKey(dependency.name)) { throwToolExit('$filename contains two dependencies on ${dependency.name}.'); } masterDependencies[dependency.name] = dependency; } else { // If we _are_ in the overrides section, then go tell the version // we saw earlier (if any -- there might not be, we might be // overriding a transitive dependency) that we have overridden it, // so that later when we output the dependencies we can leave // the line unmodified. masterDependencies[dependency.name]?.markOverridden(dependency); } } else if (line.contains(kDependencyChecksum)) { // This is the pubspec checksum. After computing it, we remove it from the output data // since it will be recomputed later. checksum = PubspecChecksum.parse(line); } else { // We're in a section we care about but got a line we didn't // recognize. Maybe it's a comment or a blank line or something. // Just pass it through. result.add(PubspecLine(line)); } } } else { // If we're here it means the last line was a dependency that needed // extra information to be parsed from the next line. // // Try to parse the line by giving it to the last PubspecDependency // object we created. If parseLock fails to recognize the line, it will // throw. If it does recognize the line and needs the following lines in // its lockLine, it'll return false. // Otherwise it returns true. // // If it returns true, then it will have updated itself internally to // store the information from this line. if (!lastDependency.parseLock(line, filename, lockIsOverride: section == Section.dependencyOverrides)) { // Ok we're dealing with some "git:" dependency. Consume lines until // we are out of the git dependency, and stuff them into the lock // line. lastDependency._lockLine = line; lastDependency._lockIsOverride = section == Section.dependencyOverrides; do { index += 1; if (index == lines.length) { throw StateError('Invalid pubspec.yaml: a "git" dependency section terminated early.'); } line = lines[index]; lastDependency._lockLine = '${lastDependency._lockLine}\n$line'; } while (line.startsWith(' ')); } // We're done with this special dependency, so reset back to null so // we'll go in the top section next time instead. lastDependency = null; } } return PubspecYaml._(file, packageName!, packageVersion, result, checksum ?? PubspecChecksum(null, '')); } /// This returns all the explicit dependencies that this pubspec.yaml lists under dependencies. Iterable<PubspecDependency> get dependencies { // It works by iterating over the parsed data from _parse above, collecting // all the dependencies that were found, ignoring any that are flagged as as // overridden by subsequent entries in the same file and any that have the // magic comment flagging them as auto-generated transitive dependencies // that we added in a previous run. return inputData .whereType<PubspecDependency>() .where((PubspecDependency data) => data.kind != DependencyKind.overridden && !data.isTransitive && !data.isDevDependency); } /// This returns all regular dependencies and all dev dependencies. Iterable<PubspecDependency> get allExplicitDependencies { return inputData .whereType<PubspecDependency>() .where((PubspecDependency data) => data.kind != DependencyKind.overridden && !data.isTransitive); } /// This returns all dependencies. Iterable<PubspecDependency> get allDependencies { return inputData.whereType<PubspecDependency>(); } /// Take a dependency graph with explicit version numbers, and apply them to /// the pubspec.yaml, ignoring any that we know are special dependencies (those /// that depend on the Flutter or Dart SDK directly and are thus automatically /// pinned). void apply(PubDependencyTree versions, Set<String> specialDependencies) { final List<String> output = <String>[]; // the string data to output to the file, line by line final Set<String> directDependencies = <String>{}; // packages this pubspec directly depends on (i.e. not transitive) final Set<String> devDependencies = <String>{}; Section section = Section.other; // the section we're currently handling // the line number where we're going to insert the transitive dependencies. int? endOfDirectDependencies; // The line number where we're going to insert the transitive dev dependencies. int? endOfDevDependencies; // Walk the pre-parsed input file, outputting it unmodified except for // updating version numbers, removing the old transitive dependencies lines, // and adding our new transitive dependencies lines. We also do a little // cleanup, removing trailing spaces, removing double-blank lines, leading // blank lines, and trailing blank lines, and ensuring the file ends with a // newline. This cleanup lets us be a little more aggressive while building // the output. for (final PubspecLine data in inputData) { if (data is PubspecHeader) { // This line was a header of some sort. // // If we're leaving one of the sections in which we can list transitive // dependencies, then remember this as the current last known valid // place to insert our transitive dependencies. if (section == Section.dependencies) { endOfDirectDependencies = output.length; } if (section == Section.devDependencies) { endOfDevDependencies = output.length; } section = data.section; // track which section we're now in. output.add(data.line); // insert the header into the output } else if (data is PubspecDependency) { // This was a dependency of some sort. // How we handle this depends on the section. switch (section) { case Section.devDependencies: case Section.dependencies: // For the dependencies and dev_dependencies sections, we reinsert // the dependency if it wasn't one of our autogenerated transitive // dependency lines. if (!data.isTransitive) { // Assert that we haven't seen it in this file already. assert(!directDependencies.contains(data.name) && !devDependencies.contains(data.name)); if (data.kind == DependencyKind.normal) { // This is a regular dependency, so we need to update the // version number. // // We output data that matches the format that // PubspecDependency.parse can handle. The data.suffix is any // previously-specified trailing comment. assert(versions.contains(data.name), "versions doesn't contain ${data.name}"); output.add(' ${data.name}: ${versions.versionFor(data.name)}${data.suffix}'); } else { // If it wasn't a regular dependency, then we output the line // unmodified. If there was an additional line (e.g. an "sdk: // flutter" line) then we output that too. output.add(data.line); if (data.lockLine != null) { output.add(data.lockLine!); } } // Remember that we've dealt with this dependency so we don't // mention it again when doing the transitive dependencies. if (section == Section.dependencies) { directDependencies.add(data.name); } else { devDependencies.add(data.name); } } // Since we're in one of the places where we can list dependencies, // remember this as the current last known valid place to insert our // transitive dev dependencies. If the section is for regular dependencies, // then also remember the line for the end of direct dependencies. if (section == Section.dependencies) { endOfDirectDependencies = output.length; } endOfDevDependencies = output.length; case Section.builders: case Section.dependencyOverrides: case Section.header: case Section.other: // In other sections, pass everything through in its original form. output.add(data.line); if (data.lockLine != null) { output.add(data.lockLine!); } } } else { // Not a header, not a dependency, just pass that through unmodified. output.add(data.line); } } // If there are no dependencies or dev_dependencies sections, these will be // null. We have such files in our tests, so account for them here. endOfDirectDependencies ??= output.length; endOfDevDependencies ??= output.length; // Now include all the transitive dependencies and transitive dev dependencies. // The blocks of text to insert for each dependency section. final List<String> transitiveDependencyOutput = <String>[]; final List<String> transitiveDevDependencyOutput = <String>[]; // Which dependencies we need to handle for the transitive and dev dependency sections. final Set<String> transitiveDependencies = <String>{}; final Set<String> transitiveDevDependencies = <String>{}; // Merge the lists of dependencies we've seen in this file from dependencies, dev dependencies, // and the dependencies we know this file mentions that are already pinned // (and which didn't get special processing above). final Set<String> implied = <String>{ ...directDependencies, ...specialDependencies, ...devDependencies, }; // Create a new set to hold the list of packages we've already processed, so // that we don't redundantly process them multiple times. final Set<String> done = <String>{}; for (final String package in directDependencies) { transitiveDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied)); } for (final String package in devDependencies) { transitiveDevDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied)); } // Sort each dependency block lexically so that we don't get noisy diffs when upgrading. final List<String> transitiveDependenciesAsList = transitiveDependencies.toList()..sort(); final List<String> transitiveDevDependenciesAsList = transitiveDevDependencies.toList()..sort(); String computeTransitiveDependencyLineFor(String package) { return ' $package: ${versions.versionFor(package)} $kTransitiveMagicString'; } // Add a line for each transitive dependency and transitive dev dependency using our magic string to recognize them later. for (final String package in transitiveDependenciesAsList) { transitiveDependencyOutput.add(computeTransitiveDependencyLineFor(package)); } for (final String package in transitiveDevDependenciesAsList) { transitiveDevDependencyOutput.add(computeTransitiveDependencyLineFor(package)); } // Build a sorted list of all dependencies for the checksum. final Set<String> checksumDependencies = <String>{ ...directDependencies, ...devDependencies, ...transitiveDependenciesAsList, ...transitiveDevDependenciesAsList, }..removeAll(specialDependencies); // Add a blank line before and after each section to keep the resulting output clean. transitiveDependencyOutput ..insert(0, '') ..add(''); transitiveDevDependencyOutput ..insert(0, '') ..add(''); // Compute a new checksum from all sorted dependencies and their version and convert to a hex string. final String checksumString = _computeChecksum(checksumDependencies, versions.versionFor); // Insert the block of transitive dependency declarations into the output after [endOfDirectDependencies], // and the blocks of transitive dev dependency declarations into the output after [lastPossiblePlace]. Finally, // insert the [checksumString] at the very end. output ..insertAll(endOfDevDependencies, transitiveDevDependencyOutput) ..insertAll(endOfDirectDependencies, transitiveDependencyOutput) ..add('') ..add('$kDependencyChecksum$checksumString'); // Remove trailing lines. while (output.last.isEmpty) { output.removeLast(); } // Output the result to the pubspec.yaml file, skipping leading and // duplicate blank lines and removing trailing spaces. final StringBuffer contents = StringBuffer(); bool hadBlankLine = true; for (String line in output) { line = line.trimRight(); if (line == '') { if (!hadBlankLine) { contents.writeln(); } hadBlankLine = true; } else { contents.writeln(line); hadBlankLine = false; } } file.writeAsStringSync(contents.toString()); } } /// This is the base class for the objects that represent lines in the /// pubspec.yaml files. class PubspecLine { PubspecLine(this.line); /// The raw line as we saw it in the original file. This is used so that we can /// output the same line unmodified for the majority of lines. final String line; } /// A checksum of the non autogenerated dependencies. class PubspecChecksum extends PubspecLine { PubspecChecksum(this.value, String line) : super(line); /// The checksum value, computed using [Object.hash] over the direct, dev, /// and special dependencies sorted lexically. /// /// If the line cannot be parsed, [value] will be null. final String? value; /// Parses a [PubspecChecksum] from a line. /// /// The returned PubspecChecksum will have a null [value] if no checksum could /// be found on this line. This is a value that [_computeChecksum] cannot return. static PubspecChecksum parse(String line) { final List<String> tokens = line.split(kDependencyChecksum); if (tokens.length != 2) { return PubspecChecksum(null, line); } return PubspecChecksum(tokens.last.trim(), line); } } /// A header, e.g. "dependencies:". class PubspecHeader extends PubspecLine { PubspecHeader( super.line, this.section, { this.name, this.value, }); /// The section of the pubspec where the parse [line] appears. final Section section; /// The name in the pubspec line providing a name/value pair, such as "name" /// and "version". /// /// Example: /// /// The value of this field extracted from the following line is "version". /// /// ``` /// version: 0.16.5 /// ``` final String? name; /// The value in the pubspec line providing a name/value pair, such as "name" /// and "version". /// /// Example: /// /// The value of this field extracted from the following line is "0.16.5". /// /// ``` /// version: 0.16.5 /// ``` final String? value; static PubspecHeader? parse(String line) { // We recognize any line that: // * doesn't start with a space (i.e. is aligned on the left edge) // * ignoring trailing spaces and comments, ends with a colon // * has contents before the colon // We also try to recognize which of the kinds of Sections it is // by comparing those contents against known strings. if (line.startsWith(' ')) { return null; } final String strippedLine = _stripComments(line); if (!strippedLine.contains(':') || strippedLine.length <= 1) { return null; } final List<String> parts = strippedLine.split(':'); final String sectionName = parts.first; final String value = parts.last.trim(); switch (sectionName) { case 'dependencies': return PubspecHeader(line, Section.dependencies); case 'dev_dependencies': return PubspecHeader(line, Section.devDependencies); case 'dependency_overrides': return PubspecHeader(line, Section.dependencyOverrides); case 'builders': return PubspecHeader(line, Section.builders); case 'name': case 'version': return PubspecHeader(line, Section.header, name: sectionName, value: value); default: return PubspecHeader(line, Section.other); } } /// Returns the input after removing trailing spaces and anything after the /// first "#". static String _stripComments(String line) { final int hashIndex = line.indexOf('#'); if (hashIndex < 0) { return line.trimRight(); } return line.substring(0, hashIndex).trimRight(); } } /// A dependency, as represented by a line (or two) from a pubspec.yaml file. class PubspecDependency extends PubspecLine { PubspecDependency( super.line, this.name, this.suffix, { required this.isTransitive, required DependencyKind kind, required this.version, required this.sourcePath, required this.isDevDependency, }) : _kind = kind; static PubspecDependency? parse( String line, { required String filename, required bool isDevDependency, }) { // We recognize any line that: // * starts with exactly two spaces, no more or less // * has some content, then a colon // // If we recognize the line, then we look to see if there's anything after // the colon, ignoring comments. If there is, then this is a normal // dependency, otherwise it's an unknown one. // // We also try and save the version string, if any. This is used to verify // the checksum of package deps. // // We also look at the trailing comment, if any, to see if it is the magic // string that identifies the line as a transitive dependency that we // previously pinned, so we can ignore it. // // We remember the trailing comment, if any, so that we can reconstruct the // line later. We forget the specified version range, if any. if (line.length < 4 || line.startsWith(' ') || !line.startsWith(' ')) { return null; } final int colonIndex = line.indexOf(':'); final int hashIndex = line.indexOf('#'); if (colonIndex < 3) { // two spaces at 0 and 1, a character at 2 return null; } if (hashIndex >= 0 && hashIndex < colonIndex) { return null; } final String package = line.substring(2, colonIndex).trimRight(); assert(package.isNotEmpty); assert(line.startsWith(' $package')); String suffix = ''; bool isTransitive = false; String stripped; String version = ''; if (hashIndex >= 0) { assert(hashIndex > colonIndex); final String trailingComment = line.substring(hashIndex, line.length); assert(line.endsWith(trailingComment)); isTransitive = trailingComment == kTransitiveMagicString; suffix = ' $trailingComment'; stripped = line.substring(colonIndex + 1, hashIndex).trimRight(); } else { stripped = line.substring(colonIndex + 1, line.length).trimRight(); } if (colonIndex != -1) { version = line.substring(colonIndex + 1, hashIndex != -1 ? hashIndex : line.length).trim(); } return PubspecDependency( line, package, suffix, isTransitive: isTransitive, version: version, kind: stripped.isEmpty ? DependencyKind.unknown : DependencyKind.normal, sourcePath: filename, isDevDependency: isDevDependency, ); } final String name; // the package name final String suffix; // any trailing comment we found final String version; // the version string if found, or blank. final bool isTransitive; // whether the suffix matched kTransitiveMagicString final String sourcePath; // the filename of the pubspec.yaml file, for error messages final bool isDevDependency; // Whether this dependency is under the `dev dependencies` section. DependencyKind get kind => _kind; DependencyKind _kind = DependencyKind.normal; /// If we're a path or sdk dependency, the path or sdk in question. String? _lockTarget; /// If we were a two-line dependency, the second line (see the inherited [line] /// for the first). String? get lockLine => _lockLine; String? _lockLine; /// If we're a path or sdk dependency, whether we were found in a /// dependencies/dev_dependencies section, or a dependency_overrides section. /// We track this so that we can put ourselves in the right section when /// generating the fake pubspec.yaml. bool _lockIsOverride = false; static const String _pathPrefix = ' path: '; static const String _sdkPrefix = ' sdk: '; static const String _gitPrefix = ' git:'; PubspecDependency copyWith({ String? line, String? name, String? suffix, bool? isTransitive, DependencyKind? kind, String? version, String? sourcePath, bool? isDevDependency, }) { return PubspecDependency( line ?? this.line, name ?? this.name, suffix ?? this.suffix, isTransitive: isTransitive ?? this.isTransitive, kind: kind ?? this.kind, version: version ?? this.version, sourcePath: sourcePath ?? this.sourcePath, isDevDependency: isDevDependency ?? this.isDevDependency, ); } /// Whether the dependency points to a package in the Flutter SDK. /// /// There are two ways one can point to a Flutter package: /// /// - Using a "sdk: flutter" dependency. /// - Using a "path" dependency that points somewhere in the Flutter /// repository other than the "bin" directory. bool get pointsToSdk { if (_kind == DependencyKind.sdk) { return true; } final String? lockTarget = _lockTarget; if (_kind == DependencyKind.path && lockTarget != null && !globals.fs.path.isWithin(globals.fs.path.join(Cache.flutterRoot!, 'bin'), lockTarget) && globals.fs.path.isWithin(Cache.flutterRoot!, lockTarget)) { return true; } return false; } /// If parse decided we were a two-line dependency, this is called to parse the second line. /// We throw if we couldn't parse this line. /// We return true if we parsed it and stored the line in lockLine. /// We return false if we parsed it and it's a git dependency that needs the next few lines. bool parseLock(String line, String pubspecPath, { required bool lockIsOverride }) { assert(kind == DependencyKind.unknown); if (line.startsWith(_pathPrefix)) { // We're a path dependency; remember the (absolute) path. _lockTarget = globals.fs.path.canonicalize( globals.fs.path.absolute(globals.fs.path.dirname(pubspecPath), line.substring(_pathPrefix.length, line.length)) ); _kind = DependencyKind.path; } else if (line.startsWith(_sdkPrefix)) { // We're an SDK dependency. _lockTarget = line.substring(_sdkPrefix.length, line.length); _kind = DependencyKind.sdk; } else if (line.startsWith(_gitPrefix)) { // We're a git: dependency. We'll have to get the next few lines. _kind = DependencyKind.git; return false; } else { throwToolExit('Could not parse additional details for dependency $name; line was: "$line"'); } _lockIsOverride = lockIsOverride; _lockLine = line; return true; } void markOverridden(PubspecDependency sibling) { // This is called when we find a dependency is mentioned a second time, // first in dependencies/dev_dependencies, and then in dependency_overrides. // It is called on the one found in dependencies/dev_dependencies, so that // we'll later know to report our version as "any" in the fake pubspec.yaml // and unmodified in the official pubspec.yamls. assert(sibling.name == name); assert(sibling.sourcePath == sourcePath); assert(sibling.kind != DependencyKind.normal); _kind = DependencyKind.overridden; } /// This generates the entry for this dependency for the pubspec.yaml for the /// fake package that we'll use to get the version numbers figured out. /// /// When called with [allowUpgrade] as [true], the version constrains will be set /// to >= whatever the previous version was. If [allowUpgrade] is [false], then /// the previous version is used again as an exact pin. void describeForFakePubspec(StringBuffer dependencies, StringBuffer overrides, { bool allowUpgrade = true }) { final String versionToUse; // This should only happen when manually adding new dependencies; otherwise // versions should always be pinned exactly if (version.isEmpty || version == 'any') { versionToUse = 'any'; } else if (allowUpgrade) { // Must wrap in quotes for Yaml parsing versionToUse = "'>= $version'"; } else { versionToUse = version; } switch (kind) { case DependencyKind.unknown: case DependencyKind.overridden: assert(kind != DependencyKind.unknown); case DependencyKind.normal: if (!kManuallyPinnedDependencies.containsKey(name)) { dependencies.writeln(' $name: $versionToUse'); } case DependencyKind.path: if (_lockIsOverride) { dependencies.writeln(' $name: $versionToUse'); overrides.writeln(' $name:'); overrides.writeln(' path: $_lockTarget'); } else { dependencies.writeln(' $name:'); dependencies.writeln(' path: $_lockTarget'); } case DependencyKind.sdk: if (_lockIsOverride) { dependencies.writeln(' $name: $versionToUse'); overrides.writeln(' $name:'); overrides.writeln(' sdk: $_lockTarget'); } else { dependencies.writeln(' $name:'); dependencies.writeln(' sdk: $_lockTarget'); } case DependencyKind.git: if (_lockIsOverride) { dependencies.writeln(' $name: $versionToUse'); overrides.writeln(' $name:'); overrides.writeln(lockLine); } else { dependencies.writeln(' $name:'); dependencies.writeln(lockLine); } } } @override String toString() { return '$name: $version'; } } /// Generates the File object for the pubspec.yaml file of a given Directory. File _pubspecFor(Directory directory) { return directory.fileSystem.file( directory.fileSystem.path.join(directory.path, 'pubspec.yaml')); } /// Generates the source of a fake pubspec.yaml file given a list of /// dependencies. @visibleForTesting String generateFakePubspec( Iterable<PubspecDependency> dependencies, { bool doUpgrade = false }) { final StringBuffer result = StringBuffer(); final StringBuffer overrides = StringBuffer(); final bool verbose = doUpgrade; result.writeln('name: flutter_update_packages'); result.writeln('environment:'); result.writeln(" sdk: '>=2.12.0 <4.0.0'"); result.writeln('dependencies:'); overrides.writeln('dependency_overrides:'); if (kManuallyPinnedDependencies.isNotEmpty) { if (verbose) { globals.printStatus('WARNING: the following packages use hard-coded version constraints:'); } final Set<String> allTransitive = <String>{ for (final PubspecDependency dependency in dependencies) dependency.name, }; kManuallyPinnedDependencies.forEach((String package, String version) { // Don't add pinned dependency if it is not in the set of all transitive dependencies. if (!allTransitive.contains(package)) { if (verbose) { globals.printStatus(' - $package: $version (skipped because it was not a transitive dependency)'); } return; } result.writeln(' $package: $version'); if (verbose) { globals.printStatus(' - $package: $version'); } }); } for (final PubspecDependency dependency in dependencies) { if (!dependency.pointsToSdk) { dependency.describeForFakePubspec(result, overrides, allowUpgrade: doUpgrade); } } result.write(overrides.toString()); return result.toString(); } /// This object tracks the output of a call to "pub deps --style=compact". /// /// It ends up holding the full graph of dependencies, and the version number for /// each one. class PubDependencyTree { final Map<String, String?> _versions = <String, String?>{}; final Map<String, Set<String>> _dependencyTree = <String, Set<String>>{}; /// Handles the output from "pub deps --style=compact". /// /// That output is of this form: /// /// ``` /// package_name 0.0.0 /// /// dependencies: /// - analyzer 0.31.0-alpha.0 [watcher args package_config collection] /// - archive 1.0.31 [crypto args path] /// - args 0.13.7 /// - cli_util 0.1.2+1 [path] /// /// dev dependencies: /// - async 1.13.3 [collection] /// - barback 0.15.2+11 [stack_trace source_span pool async collection path] /// /// dependency overrides: /// - analyzer 0.31.0-alpha.0 [watcher args package_config collection] /// ``` /// /// We ignore all the lines that don't start with a hyphen. For each other /// line, we ignore any line that mentions a package we've already seen (this /// happens when the overrides section mentions something that was in the /// dependencies section). We ignore if something is a dependency or /// dev_dependency (pub won't use different versions for those two). /// /// We then parse out the package name, version number, and sub-dependencies for /// each entry, and store than in our _versions and _dependencyTree fields /// above. String? fill(String message) { if (message.startsWith('- ')) { final int space2 = message.indexOf(' ', 2); int space3 = message.indexOf(' ', space2 + 1); if (space3 < 0) { space3 = message.length; } final String package = message.substring(2, space2); if (!contains(package)) { // Some packages get listed in the dependency overrides section too. // We just ignore those. The data is the same either way. final String version = message.substring(space2 + 1, space3); List<String> dependencies; if (space3 < message.length) { assert(message[space3 + 1] == '['); assert(message[message.length - 1] == ']'); final String allDependencies = message.substring(space3 + 2, message.length - 1); dependencies = allDependencies.split(' '); } else { dependencies = const <String>[]; } _versions[package] = version; _dependencyTree[package] = Set<String>.of(dependencies); } } return null; } /// Whether we know about this package. bool contains(String package) { return _versions.containsKey(package); } /// The transitive closure of all the dependencies for the given package, /// excluding any listed in `seen`. Iterable<String> getTransitiveDependenciesFor( String package, { required Set<String> seen, required Set<String> exclude, List<String>? result, }) { result ??= <String>[]; final Set<String>? dependencies = _dependencyTree[package]; if (dependencies == null) { // We have no transitive dependencies extracted for flutter_sdk packages // because they were omitted from pubspec.yaml used for 'pub upgrade' run. return result; } for (final String dependency in dependencies) { if (!seen.contains(dependency)) { if (!exclude.contains(dependency)) { result.add(dependency); } seen.add(dependency); getTransitiveDependenciesFor(dependency, seen: seen, exclude: exclude, result: result); } } return result; } /// The version that a particular package ended up with. String versionFor(String package) { return _versions[package]!; } } // Produces a 16-bit checksum from the codePoints of the package name and // version strings using Fletcher's algorithm. String _computeChecksum(Iterable<String> names, String Function(String name) getVersion) { int lowerCheck = 0; int upperCheck = 0; final List<String> sortedNames = names.toList()..sort(); for (final String name in sortedNames) { final String version = getVersion(name); final String value = '$name: $version'; // Each code unit is 16 bits. for (final int codeUnit in value.codeUnits) { final int upper = codeUnit >> 8; final int lower = codeUnit & 0xFF; lowerCheck = (lowerCheck + upper) % 255; upperCheck = (upperCheck + lowerCheck) % 255; lowerCheck = (lowerCheck + lower) % 255; upperCheck = (upperCheck + lowerCheck) % 255; } } return ((upperCheck << 8) | lowerCheck).toRadixString(16).padLeft(4, '0'); } /// Create a synthetic Flutter SDK so that pub version solving does not get /// stuck on the old versions. @visibleForTesting Directory createTemporaryFlutterSdk( Logger logger, FileSystem fileSystem, Directory realFlutter, List<PubspecYaml> pubspecs, Directory tempDir, ) { final Set<String> currentPackages = <String>{}; for (final FileSystemEntity entity in realFlutter.childDirectory('packages').listSync()) { // Verify that a pubspec.yaml exists to ensure this isn't a left over directory. if (entity is Directory && entity.childFile('pubspec.yaml').existsSync()) { currentPackages.add(fileSystem.path.basename(entity.path)); } } final Map<String, PubspecYaml> pubspecsByName = <String, PubspecYaml>{}; for (final PubspecYaml pubspec in pubspecs) { pubspecsByName[pubspec.name] = pubspec; } final Directory directory = tempDir.childDirectory('flutter_upgrade_sdk') ..createSync(); // Fill in version info. realFlutter.childFile('version') .copySync(directory.childFile('version').path); final File versionJson = FlutterVersion.getVersionFile(realFlutter.fileSystem, realFlutter.path); final Directory binCacheDirectory = directory.childDirectory('bin').childDirectory('cache'); binCacheDirectory.createSync(recursive: true); versionJson.copySync(binCacheDirectory.childFile('flutter.version.json').path); // Directory structure should mirror the current Flutter SDK final Directory packages = directory.childDirectory('packages'); for (final String flutterPackage in currentPackages) { final File pubspecFile = packages .childDirectory(flutterPackage) .childFile('pubspec.yaml') ..createSync(recursive: true); final PubspecYaml? pubspecYaml = pubspecsByName[flutterPackage]; if (pubspecYaml == null) { logger.printWarning( "Unexpected package '$flutterPackage' found in packages directory", ); continue; } final StringBuffer output = StringBuffer('name: $flutterPackage\n'); // Fill in SDK dependency constraint. output.write(''' environment: sdk: '>=3.2.0-0 <4.0.0' '''); output.writeln('dependencies:'); for (final PubspecDependency dependency in pubspecYaml.dependencies) { if (dependency.isTransitive || dependency.isDevDependency) { continue; } if (dependency.kind == DependencyKind.sdk) { output.writeln(' ${dependency.name}:\n sdk: flutter'); continue; } output.writeln(' ${dependency.name}: any'); } pubspecFile.writeAsStringSync(output.toString()); } // Create the sky engine pubspec.yaml directory .childDirectory('bin') .childDirectory('cache') .childDirectory('pkg') .childDirectory('sky_engine') .childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(''' name: sky_engine version: 0.0.99 description: Dart SDK extensions for dart:ui homepage: http://flutter.io # sky_engine requires sdk_ext support in the analyzer which was added in 1.11.x environment: sdk: '>=3.2.0-0 <4.0.0' '''); return directory; }
flutter/packages/flutter_tools/lib/src/commands/update_packages.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/update_packages.dart", "repo_id": "flutter", "token_count": 25891 }
750
// Copyright 2014 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'; /// Parsing the output of "dart pub deps --json" /// /// expected structure: {"name": "package name", "source": "hosted", "dependencies": [...]} class DartDependencyPackage { DartDependencyPackage({ required this.name, required this.version, required this.source, required this.dependencies, }); factory DartDependencyPackage.fromHashMap(dynamic packageInfo) { String name = ''; String version = ''; String source = ''; List<dynamic> dependencies = <dynamic>[]; if (packageInfo is LinkedHashMap) { final LinkedHashMap<String, dynamic> info = packageInfo as LinkedHashMap<String, dynamic>; if (info.containsKey('name')) { name = info['name'] as String; } if (info.containsKey('version')) { version = info['version'] as String; } if (info.containsKey('source')) { source = info['source'] as String; } if (info.containsKey('dependencies')) { dependencies = info['dependencies'] as List<dynamic>; } } return DartDependencyPackage( name: name, version: version, source: source, dependencies: dependencies.map((dynamic e) => e.toString()).toList(), ); } final String name; final String version; final String source; final List<String> dependencies; } class DartPubJson { DartPubJson(this._json); final LinkedHashMap<String, dynamic> _json; final List<DartDependencyPackage> _packages = <DartDependencyPackage>[]; List<DartDependencyPackage> get packages { if (_packages.isNotEmpty) { return _packages; } if (_json.containsKey('packages')) { final List<dynamic> packagesInfo = _json['packages'] as List<dynamic>; for (final dynamic info in packagesInfo) { _packages.add(DartDependencyPackage.fromHashMap(info)); } } return _packages; } }
flutter/packages/flutter_tools/lib/src/dart_pub_json_formatter.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/dart_pub_json_formatter.dart", "repo_id": "flutter", "token_count": 752 }
751
// Copyright 2014 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:dds/dds.dart' as dds; import 'package:file/file.dart'; import 'package:meta/meta.dart'; import 'package:package_config/package_config_types.dart'; import 'package:vm_service/vm_service.dart' as vm_service; import '../application_package.dart'; import '../base/common.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../build_info.dart'; import '../device.dart'; import '../resident_runner.dart'; import '../sksl_writer.dart'; import '../vmservice.dart'; import 'web_driver_service.dart'; class FlutterDriverFactory { FlutterDriverFactory({ required ApplicationPackageFactory applicationPackageFactory, required Logger logger, required ProcessUtils processUtils, required String dartSdkPath, required DevtoolsLauncher devtoolsLauncher, }) : _applicationPackageFactory = applicationPackageFactory, _logger = logger, _processUtils = processUtils, _dartSdkPath = dartSdkPath, _devtoolsLauncher = devtoolsLauncher; final ApplicationPackageFactory _applicationPackageFactory; final Logger _logger; final ProcessUtils _processUtils; final String _dartSdkPath; final DevtoolsLauncher _devtoolsLauncher; /// Create a driver service for running `flutter drive`. DriverService createDriverService(bool web) { if (web) { return WebDriverService( logger: _logger, processUtils: _processUtils, dartSdkPath: _dartSdkPath, ); } return FlutterDriverService( logger: _logger, processUtils: _processUtils, dartSdkPath: _dartSdkPath, applicationPackageFactory: _applicationPackageFactory, devtoolsLauncher: _devtoolsLauncher, ); } } /// An interface for the `flutter driver` integration test operations. abstract class DriverService { /// Install and launch the application for the provided [device]. Future<void> start( BuildInfo buildInfo, Device device, DebuggingOptions debuggingOptions, bool ipv6, { File? applicationBinary, String? route, String? userIdentifier, String? mainPath, Map<String, Object> platformArgs = const <String, Object>{}, }); /// If --use-existing-app is provided, configured the correct VM Service URI. Future<void> reuseApplication( Uri vmServiceUri, Device device, DebuggingOptions debuggingOptions, bool ipv6, ); /// Start the test file with the provided [arguments] and [environment], returning /// the test process exit code. /// /// if [profileMemory] is provided, it will be treated as a file path to write a /// devtools memory profile. Future<int> startTest( String testFile, List<String> arguments, Map<String, String> environment, PackageConfig packageConfig, { bool? headless, String? chromeBinary, String? browserName, bool? androidEmulator, int? driverPort, List<String> webBrowserFlags, List<String>? browserDimension, String? profileMemory, }); /// Stop the running application and uninstall it from the device. /// /// If [writeSkslOnExit] is non-null, will connect to the VM Service /// and write SkSL to the file. This is only supported on mobile and /// desktop devices. Future<void> stop({ File? writeSkslOnExit, String? userIdentifier, }); } /// An implementation of the driver service that connects to mobile and desktop /// applications. class FlutterDriverService extends DriverService { FlutterDriverService({ required ApplicationPackageFactory applicationPackageFactory, required Logger logger, required ProcessUtils processUtils, required String dartSdkPath, required DevtoolsLauncher devtoolsLauncher, @visibleForTesting VMServiceConnector vmServiceConnector = connectToVmService, }) : _applicationPackageFactory = applicationPackageFactory, _logger = logger, _processUtils = processUtils, _dartSdkPath = dartSdkPath, _vmServiceConnector = vmServiceConnector, _devtoolsLauncher = devtoolsLauncher; static const int _kLaunchAttempts = 3; final ApplicationPackageFactory _applicationPackageFactory; final Logger _logger; final ProcessUtils _processUtils; final String _dartSdkPath; final VMServiceConnector _vmServiceConnector; final DevtoolsLauncher _devtoolsLauncher; Device? _device; ApplicationPackage? _applicationPackage; late String _vmServiceUri; late FlutterVmService _vmService; @override Future<void> start( BuildInfo buildInfo, Device device, DebuggingOptions debuggingOptions, bool ipv6, { File? applicationBinary, String? route, String? userIdentifier, Map<String, Object> platformArgs = const <String, Object>{}, String? mainPath, }) async { if (buildInfo.isRelease) { throwToolExit( 'Flutter Driver (non-web) does not support running in release mode.\n' '\n' 'Use --profile mode for testing application performance.\n' 'Use --debug (default) mode for testing correctness (with assertions).' ); } _device = device; final TargetPlatform targetPlatform = await device.targetPlatform; _applicationPackage = await _applicationPackageFactory.getPackageForPlatform( targetPlatform, buildInfo: buildInfo, applicationBinary: applicationBinary, ); int attempt = 0; LaunchResult? result; bool prebuiltApplication = applicationBinary != null; while (attempt < _kLaunchAttempts) { result = await device.startApp( _applicationPackage, mainPath: mainPath, route: route, debuggingOptions: debuggingOptions, platformArgs: platformArgs, userIdentifier: userIdentifier, prebuiltApplication: prebuiltApplication, ); if (result.started) { break; } // On attempts past 1, assume the application is built correctly and re-use it. attempt += 1; prebuiltApplication = true; _logger.printError('Application failed to start on attempt: $attempt'); } if (result == null || !result.started) { throwToolExit('Application failed to start. Will not run test. Quitting.', exitCode: 1); } return reuseApplication( result.vmServiceUri!, device, debuggingOptions, ipv6, ); } @override Future<void> reuseApplication( Uri vmServiceUri, Device device, DebuggingOptions debuggingOptions, bool ipv6, ) async { Uri uri; if (vmServiceUri.scheme == 'ws') { final List<String> segments = vmServiceUri.pathSegments.toList(); segments.remove('ws'); uri = vmServiceUri.replace(scheme: 'http', path: segments.join('/')); } else { uri = vmServiceUri; } _vmServiceUri = uri.toString(); _device = device; if (debuggingOptions.enableDds) { try { await device.dds.startDartDevelopmentService( uri, hostPort: debuggingOptions.ddsPort, ipv6: ipv6, disableServiceAuthCodes: debuggingOptions.disableServiceAuthCodes, logger: _logger, ); _vmServiceUri = device.dds.uri.toString(); } on dds.DartDevelopmentServiceException { // If there's another flutter_tools instance still connected to the target // application, DDS will already be running remotely and this call will fail. // This can be ignored to continue to use the existing remote DDS instance. } } _vmService = await _vmServiceConnector(uri, device: _device, logger: _logger); final DeviceLogReader logReader = await device.getLogReader(app: _applicationPackage); logReader.logLines.listen(_logger.printStatus); final vm_service.VM vm = await _vmService.service.getVM(); logReader.appPid = vm.pid; } @override Future<int> startTest( String testFile, List<String> arguments, Map<String, String> environment, PackageConfig packageConfig, { bool? headless, String? chromeBinary, String? browserName, bool? androidEmulator, int? driverPort, List<String> webBrowserFlags = const <String>[], List<String>? browserDimension, String? profileMemory, }) async { if (profileMemory != null) { unawaited(_devtoolsLauncher.launch( Uri.parse(_vmServiceUri), additionalArguments: <String>['--record-memory-profile=$profileMemory'], )); // When profiling memory the original launch future will never complete. await _devtoolsLauncher.processStart; } try { final int result = await _processUtils.stream(<String>[ _dartSdkPath, ...<String>[...arguments, testFile, '-rexpanded'], ], environment: <String, String>{ 'VM_SERVICE_URL': _vmServiceUri, ...environment, }); return result; } finally { if (profileMemory != null) { await _devtoolsLauncher.close(); } } } @override Future<void> stop({ File? writeSkslOnExit, String? userIdentifier, }) async { if (writeSkslOnExit != null) { final FlutterView flutterView = (await _vmService.getFlutterViews()).first; final Map<String, Object?>? result = await _vmService.getSkSLs( viewId: flutterView.id ); await sharedSkSlWriter(_device!, result, outputFile: writeSkslOnExit, logger: _logger); } // If the application package is available, stop and uninstall. final ApplicationPackage? package = _applicationPackage; if (package != null) { if (!await _device!.stopApp(package, userIdentifier: userIdentifier)) { _logger.printError('Failed to stop app'); } if (!await _device!.uninstallApp(package, userIdentifier: userIdentifier)) { _logger.printError('Failed to uninstall app'); } } else if (_device!.supportsFlutterExit) { // Otherwise use the VM Service URI to stop the app as a best effort approach. final vm_service.VM vm = await _vmService.service.getVM(); final vm_service.IsolateRef isolateRef = vm.isolates! .firstWhere((vm_service.IsolateRef element) { return !element.isSystemIsolate!; }); unawaited(_vmService.flutterExit(isolateId: isolateRef.id!)); } else { _logger.printTrace('No application package for $_device, leaving app running'); } await _device!.dispose(); } }
flutter/packages/flutter_tools/lib/src/drive/drive_service.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/drive/drive_service.dart", "repo_id": "flutter", "token_count": 3752 }
752
// Copyright 2014 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 '../base/file_system.dart'; import '../base/io.dart'; import '../base/platform.dart'; import '../convert.dart'; import '../features.dart' show featureFlags; import '../globals.dart' as globals; import 'fuchsia_ffx.dart'; import 'fuchsia_kernel_compiler.dart'; import 'fuchsia_pm.dart'; /// Returns [true] if the current platform supports Fuchsia targets. bool isFuchsiaSupportedPlatform(Platform platform) { return featureFlags.isFuchsiaEnabled && (platform.isLinux || platform.isMacOS); } /// The Fuchsia SDK shell commands. /// /// This workflow assumes development within the fuchsia source tree, /// including a working fx command-line tool in the user's PATH. class FuchsiaSdk { /// Interface to the 'pm' tool. late final FuchsiaPM fuchsiaPM = FuchsiaPM(); /// Interface to the 'kernel_compiler' tool. late final FuchsiaKernelCompiler fuchsiaKernelCompiler = FuchsiaKernelCompiler(); /// Interface to the 'ffx' tool. late final FuchsiaFfx fuchsiaFfx = FuchsiaFfx(); /// Returns any attached devices is a newline-denominated String. /// /// Example output: abcd::abcd:abc:abcd:abcd%qemu scare-cable-skip-joy Future<String?> listDevices({Duration? timeout}) async { final File? ffx = globals.fuchsiaArtifacts?.ffx; if (ffx == null || !ffx.existsSync()) { return null; } final List<String>? devices = await fuchsiaFfx.list(timeout: timeout); if (devices == null) { return null; } return devices.isNotEmpty ? devices.join('\n') : null; } /// Returns the fuchsia system logs for an attached device where /// [id] is the IP address of the device. Stream<String>? syslogs(String id) { Process? process; try { final StreamController<String> controller = StreamController<String>(onCancel: () { process?.kill(); }); final File? sshConfig = globals.fuchsiaArtifacts?.sshConfig; if (sshConfig == null || !sshConfig.existsSync()) { globals.printError('Cannot read device logs: No ssh config.'); globals.printError('Have you set FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR?'); return null; } const String remoteCommand = 'log_listener --clock Local'; final List<String> cmd = <String>[ 'ssh', '-F', sshConfig.absolute.path, id, // The device's IP. remoteCommand, ]; globals.processManager.start(cmd).then((Process newProcess) { if (controller.isClosed) { return; } process = newProcess; process?.exitCode.whenComplete(controller.close); controller.addStream(process!.stdout .transform(utf8.decoder) .transform(const LineSplitter())); }); return controller.stream; } on Exception catch (exception) { globals.printTrace('$exception'); } return const Stream<String>.empty(); } } /// Fuchsia-specific artifacts used to interact with a device. class FuchsiaArtifacts { /// Creates a new [FuchsiaArtifacts]. FuchsiaArtifacts({ this.sshConfig, this.ffx, this.pm, }); /// Creates a new [FuchsiaArtifacts] using the cached Fuchsia SDK. /// /// Finds tools under bin/cache/artifacts/fuchsia/tools. /// Queries environment variables (first FUCHSIA_BUILD_DIR, then /// FUCHSIA_SSH_CONFIG) to find the ssh configuration needed to talk to /// a device. factory FuchsiaArtifacts.find() { if (!isFuchsiaSupportedPlatform(globals.platform)) { // Don't try to find the artifacts on platforms that are not supported. return FuchsiaArtifacts(); } // If FUCHSIA_BUILD_DIR is defined, then look for the ssh_config dir // relative to it. Next, if FUCHSIA_SSH_CONFIG is defined, then use it. // TODO(zanderso): Consider passing the ssh config path in with a flag. File? sshConfig; if (globals.platform.environment.containsKey(_kFuchsiaBuildDir)) { sshConfig = globals.fs.file(globals.fs.path.join( globals.platform.environment[_kFuchsiaBuildDir]!, 'ssh-keys', 'ssh_config')); } else if (globals.platform.environment.containsKey(_kFuchsiaSshConfig)) { sshConfig = globals.fs.file(globals.platform.environment[_kFuchsiaSshConfig]); } final String fuchsia = globals.cache.getArtifactDirectory('fuchsia').path; final String tools = globals.fs.path.join(fuchsia, 'tools'); final File ffx = globals.fs.file(globals.fs.path.join(tools, 'x64/ffx')); final File pm = globals.fs.file(globals.fs.path.join(tools, 'pm')); return FuchsiaArtifacts( sshConfig: sshConfig, ffx: ffx.existsSync() ? ffx : null, pm: pm.existsSync() ? pm : null, ); } static const String _kFuchsiaSshConfig = 'FUCHSIA_SSH_CONFIG'; static const String _kFuchsiaBuildDir = 'FUCHSIA_BUILD_DIR'; /// The location of the SSH configuration file used to interact with a /// Fuchsia device. final File? sshConfig; /// The location of the ffx tool used to locate connected /// Fuchsia devices. final File? ffx; /// The pm tool. final File? pm; /// Returns true if the [sshConfig] file is not null and exists. bool get hasSshConfig => sshConfig != null && sshConfig!.existsSync(); }
flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_sdk.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_sdk.dart", "repo_id": "flutter", "token_count": 1980 }
753
// Copyright 2014 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 '../../base/file_system.dart'; import '../../base/project_migrator.dart'; import '../../xcode_project.dart'; const String _kDisableMinimumFrameDurationKey = 'CADisableMinimumFrameDurationOnPhone'; const String _kIndirectInputEventsKey = 'UIApplicationSupportsIndirectInputEvents'; /// Update Info.plist. class HostAppInfoPlistMigration extends ProjectMigrator { HostAppInfoPlistMigration( IosProject project, super.logger, ) : _infoPlist = project.defaultHostInfoPlist; final File _infoPlist; @override void migrate() { if (!_infoPlist.existsSync()) { logger.printTrace('Info.plist not found, skipping host app Info.plist migration.'); return; } processFileLines(_infoPlist); } @override String migrateFileContents(String fileContents) { String newContents = fileContents; if (!newContents.contains(_kDisableMinimumFrameDurationKey)) { logger.printTrace('Adding $_kDisableMinimumFrameDurationKey to Info.plist'); const String plistEnd = ''' </dict> </plist> '''; const String plistWithKey = ''' <key>$_kDisableMinimumFrameDurationKey</key> <true/> </dict> </plist> '''; newContents = newContents.replaceAll(plistEnd, plistWithKey); } if (!newContents.contains(_kIndirectInputEventsKey)) { logger.printTrace('Adding $_kIndirectInputEventsKey to Info.plist'); const String plistEnd = ''' </dict> </plist> '''; const String plistWithKey = ''' <key>$_kIndirectInputEventsKey</key> <true/> </dict> </plist> '''; newContents = newContents.replaceAll(plistEnd, plistWithKey); } return newContents; } }
flutter/packages/flutter_tools/lib/src/ios/migrations/host_app_info_plist_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/migrations/host_app_info_plist_migration.dart", "repo_id": "flutter", "token_count": 632 }
754
The directory structure in here mirrors the directory structure in lib/src/. The native assets feature lives in lib/src/isolated/ because this code is not used in other build systems.
flutter/packages/flutter_tools/lib/src/isolated/native_assets/README.md/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/README.md", "repo_id": "flutter", "token_count": 42 }
755
// Copyright 2014 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:meta/meta.dart'; import 'package:process/process.dart'; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../convert.dart'; import '../flutter_manifest.dart'; import 'gen_l10n_templates.dart'; import 'gen_l10n_types.dart'; import 'localizations_utils.dart'; import 'message_parser.dart'; /// Run the localizations generation script with the configuration [options]. Future<LocalizationsGenerator> generateLocalizations({ required Directory projectDir, Directory? dependenciesDir, required LocalizationOptions options, required Logger logger, required FileSystem fileSystem, required Artifacts artifacts, required ProcessManager processManager, }) async { // If generating a synthetic package, generate a warning if // flutter: generate is not set. final FlutterManifest? flutterManifest = FlutterManifest.createFromPath( projectDir.childFile('pubspec.yaml').path, fileSystem: projectDir.fileSystem, logger: logger, ); if (options.syntheticPackage && (flutterManifest == null || !flutterManifest.generateSyntheticPackage)) { throwToolExit( 'Attempted to generate localizations code without having ' 'the flutter: generate flag turned on.' '\n' 'Check pubspec.yaml and ensure that flutter: generate: true has ' 'been added and rebuild the project. Otherwise, the localizations ' 'source code will not be importable.' ); } precacheLanguageAndRegionTags(); // Use \r\n if project's pubspec file contains \r\n. final bool useCRLF = projectDir.childFile('pubspec.yaml').readAsStringSync().contains('\r\n'); LocalizationsGenerator generator; try { generator = LocalizationsGenerator( fileSystem: fileSystem, inputsAndOutputsListPath: dependenciesDir?.path, projectPathString: projectDir.path, inputPathString: options.arbDir, templateArbFileName: options.templateArbFile, outputFileString: options.outputLocalizationFile, outputPathString: options.outputDir, classNameString: options.outputClass, preferredSupportedLocales: options.preferredSupportedLocales, headerString: options.header, headerFile: options.headerFile, useDeferredLoading: options.useDeferredLoading, useSyntheticPackage: options.syntheticPackage, areResourceAttributesRequired: options.requiredResourceAttributes, untranslatedMessagesFile: options.untranslatedMessagesFile, usesNullableGetter: options.nullableGetter, useEscaping: options.useEscaping, logger: logger, suppressWarnings: options.suppressWarnings, useRelaxedSyntax: options.relaxSyntax, useNamedParameters: options.useNamedParameters, ) ..loadResources() ..writeOutputFiles(isFromYaml: true, useCRLF: useCRLF); } on L10nException catch (e) { throwToolExit(e.message); } if (options.format) { // Only format Dart files using `dart format`. final List<String> formatFileList = generator.outputFileList .where((String e) => e.endsWith('.dart')) .toList(growable: false); if (formatFileList.isEmpty) { return generator; } final String dartBinary = artifacts.getArtifactPath(Artifact.engineDartBinary); final List<String> command = <String>[dartBinary, 'format', ...formatFileList]; final ProcessResult result = await processManager.run(command); if (result.exitCode != 0) { throw ProcessException( dartBinary, command, ''' `dart format` failed with exit code ${result.exitCode} stdout:\n${result.stdout}\n stderr:\n${result.stderr}''', result.exitCode, ); } } return generator; } /// The path for the synthetic package. String _defaultSyntheticPackagePath(FileSystem fileSystem) => fileSystem.path.join('.dart_tool', 'flutter_gen'); /// The default path used when the `_useSyntheticPackage` setting is set to true /// in [LocalizationsGenerator]. /// /// See [LocalizationsGenerator.initialize] for where and how it is used by the /// localizations tool. String _syntheticL10nPackagePath(FileSystem fileSystem) => fileSystem.path.join(_defaultSyntheticPackagePath(fileSystem), 'gen_l10n'); // Generate method parameters and also infer the correct types from the usage of the placeholders // For example, if placeholders are used for plurals and no type was specified, then the type will // automatically set to 'num'. Similarly, if such placeholders are used for selects, then the type // will be set to 'String'. For such placeholders that are used for both, we should throw an error. List<String> generateMethodParameters(Message message, bool useNamedParameters) { return message.placeholders.values.map((Placeholder placeholder) { return '${useNamedParameters ? 'required ' : ''}${placeholder.type} ${placeholder.name}'; }).toList(); } // Similar to above, but is used for passing arguments into helper functions. List<String> generateMethodArguments(Message message) { return message.placeholders.values.map((Placeholder placeholder) => placeholder.name).toList(); } String generateDateFormattingLogic(Message message) { if (message.placeholders.isEmpty || !message.placeholdersRequireFormatting) { return '@(none)'; } final Iterable<String> formatStatements = message.placeholders.values .where((Placeholder placeholder) => placeholder.requiresDateFormatting) .map((Placeholder placeholder) { final String? placeholderFormat = placeholder.format; if (placeholderFormat == null) { throw L10nException( 'The placeholder, ${placeholder.name}, has its "type" resource attribute set to ' 'the "${placeholder.type}" type. To properly resolve for the right ' '${placeholder.type} format, the "format" attribute needs to be set ' 'to determine which DateFormat to use. \n' "Check the intl library's DateFormat class constructors for allowed " 'date formats.' ); } final bool? isCustomDateFormat = placeholder.isCustomDateFormat; if (!placeholder.hasValidDateFormat && (isCustomDateFormat == null || !isCustomDateFormat)) { throw L10nException( 'Date format "$placeholderFormat" for placeholder ' '${placeholder.name} does not have a corresponding DateFormat ' "constructor\n. Check the intl library's DateFormat class " 'constructors for allowed date formats, or set "isCustomDateFormat" attribute ' 'to "true".' ); } if (placeholder.hasValidDateFormat) { return dateFormatTemplate .replaceAll('@(placeholder)', placeholder.name) .replaceAll('@(format)', placeholderFormat); } return dateFormatCustomTemplate .replaceAll('@(placeholder)', placeholder.name) .replaceAll('@(format)', "'${generateString(placeholderFormat)}'"); }); return formatStatements.isEmpty ? '@(none)' : formatStatements.join(); } String generateNumberFormattingLogic(Message message) { if (message.placeholders.isEmpty || !message.placeholdersRequireFormatting) { return '@(none)'; } final Iterable<String> formatStatements = message.placeholders.values .where((Placeholder placeholder) => placeholder.requiresNumFormatting) .map((Placeholder placeholder) { final String? placeholderFormat = placeholder.format; if (!placeholder.hasValidNumberFormat || placeholderFormat == null) { throw L10nException( 'Number format $placeholderFormat for the ${placeholder.name} ' 'placeholder does not have a corresponding NumberFormat constructor.\n' "Check the intl library's NumberFormat class constructors for allowed " 'number formats.' ); } final Iterable<String> parameters = placeholder.optionalParameters.map<String>((OptionalParameter parameter) { if (parameter.value is num) { return '${parameter.name}: ${parameter.value}'; } else { return "${parameter.name}: '${generateString(parameter.value.toString())}'"; } }, ); if (placeholder.hasNumberFormatWithParameters) { return numberFormatNamedTemplate .replaceAll('@(placeholder)', placeholder.name) .replaceAll('@(format)', placeholderFormat) .replaceAll('@(parameters)', parameters.join(',\n ')); } else { return numberFormatPositionalTemplate .replaceAll('@(placeholder)', placeholder.name) .replaceAll('@(format)', placeholderFormat); } }); return formatStatements.isEmpty ? '@(none)' : formatStatements.join(); } /// List of possible cases for plurals defined the ICU messageFormat syntax. Map<String, String> pluralCases = <String, String>{ '0': 'zero', '1': 'one', '2': 'two', 'zero': 'zero', 'one': 'one', 'two': 'two', 'few': 'few', 'many': 'many', 'other': 'other', }; String generateBaseClassMethod(Message message, LocaleInfo? templateArbLocale, bool useNamedParameters) { final String comment = message .description ?.split('\n') .map((String line) => ' /// $line') .join('\n') ?? ' /// No description provided for @${message.resourceId}.'; final String templateLocaleTranslationComment = ''' /// In $templateArbLocale, this message translates to: /// **'${generateString(message.value)}'**'''; if (message.placeholders.isNotEmpty) { return (useNamedParameters ? baseClassMethodWithNamedParameterTemplate : baseClassMethodTemplate) .replaceAll('@(comment)', comment) .replaceAll('@(templateLocaleTranslationComment)', templateLocaleTranslationComment) .replaceAll('@(name)', message.resourceId) .replaceAll('@(parameters)', generateMethodParameters(message, useNamedParameters).join(', ')); } return baseClassGetterTemplate .replaceAll('@(comment)', comment) .replaceAll('@(templateLocaleTranslationComment)', templateLocaleTranslationComment) .replaceAll('@(name)', message.resourceId); } // Add spaces to pad the start of each line. Skips the first line // assuming that the padding is already present. String _addSpaces(String message, {int spaces = 0}) { bool isFirstLine = true; return message .split('\n') .map((String value) { if (isFirstLine) { isFirstLine = false; return value; } return value.padLeft(spaces); }) .join('\n'); } String _generateLookupByAllCodes( AppResourceBundleCollection allBundles, String Function(LocaleInfo) generateSwitchClauseTemplate, ) { final Iterable<LocaleInfo> localesWithAllCodes = allBundles.locales.where((LocaleInfo locale) { return locale.scriptCode != null && locale.countryCode != null; }); if (localesWithAllCodes.isEmpty) { return ''; } final Iterable<String> switchClauses = localesWithAllCodes.map<String>((LocaleInfo locale) { return generateSwitchClauseTemplate(locale) .replaceAll('@(case)', locale.toString()); }); return allCodesLookupTemplate.replaceAll( '@(allCodesSwitchClauses)', switchClauses.join('\n '), ); } String _generateLookupByScriptCode( AppResourceBundleCollection allBundles, String Function(LocaleInfo) generateSwitchClauseTemplate, ) { final Iterable<String> switchClauses = allBundles.languages.map((String language) { final Iterable<LocaleInfo> locales = allBundles.localesForLanguage(language); final Iterable<LocaleInfo> localesWithScriptCodes = locales.where((LocaleInfo locale) { return locale.scriptCode != null && locale.countryCode == null; }); if (localesWithScriptCodes.isEmpty) { return null; } return _addSpaces(nestedSwitchTemplate .replaceAll('@(languageCode)', language) .replaceAll('@(code)', 'scriptCode') .replaceAll('@(switchClauses)', _addSpaces( localesWithScriptCodes.map((LocaleInfo locale) { return generateSwitchClauseTemplate(locale) .replaceAll('@(case)', locale.scriptCode!); }).join('\n'), spaces: 8, ), ), spaces: 4, ); }).whereType<String>(); if (switchClauses.isEmpty) { return ''; } return languageCodeSwitchTemplate .replaceAll('@(comment)', '// Lookup logic when language+script codes are specified.') .replaceAll('@(switchClauses)', switchClauses.join('\n '), ); } String _generateLookupByCountryCode( AppResourceBundleCollection allBundles, String Function(LocaleInfo) generateSwitchClauseTemplate, ) { final Iterable<String> switchClauses = allBundles.languages.map((String language) { final Iterable<LocaleInfo> locales = allBundles.localesForLanguage(language); final Iterable<LocaleInfo> localesWithCountryCodes = locales.where((LocaleInfo locale) { return locale.countryCode != null && locale.scriptCode == null; }); if (localesWithCountryCodes.isEmpty) { return null; } return _addSpaces( nestedSwitchTemplate .replaceAll('@(languageCode)', language) .replaceAll('@(code)', 'countryCode') .replaceAll('@(switchClauses)', _addSpaces( localesWithCountryCodes.map((LocaleInfo locale) { return generateSwitchClauseTemplate(locale).replaceAll('@(case)', locale.countryCode!); }).join('\n'), spaces: 4, )), spaces: 4, ); }).whereType<String>(); if (switchClauses.isEmpty) { return ''; } return languageCodeSwitchTemplate .replaceAll('@(comment)', '// Lookup logic when language+country codes are specified.') .replaceAll('@(switchClauses)', switchClauses.join('\n ')); } String _generateLookupByLanguageCode( AppResourceBundleCollection allBundles, String Function(LocaleInfo) generateSwitchClauseTemplate, ) { final Iterable<String> switchClauses = allBundles.languages.map((String language) { final Iterable<LocaleInfo> locales = allBundles.localesForLanguage(language); final Iterable<LocaleInfo> localesWithLanguageCode = locales.where((LocaleInfo locale) { return locale.countryCode == null && locale.scriptCode == null; }); if (localesWithLanguageCode.isEmpty) { return null; } return localesWithLanguageCode.map((LocaleInfo locale) { return generateSwitchClauseTemplate(locale) .replaceAll('@(case)', locale.languageCode); }).join('\n '); }).whereType<String>(); if (switchClauses.isEmpty) { return ''; } return languageCodeSwitchTemplate .replaceAll('@(comment)', '// Lookup logic when only language code is specified.') .replaceAll('@(switchClauses)', switchClauses.join('\n ')); } String _generateLookupBody( AppResourceBundleCollection allBundles, String className, bool useDeferredLoading, String fileName, ) { String generateSwitchClauseTemplate(LocaleInfo locale) { return (useDeferredLoading ? switchClauseDeferredLoadingTemplate : switchClauseTemplate) .replaceAll('@(localeClass)', '$className${locale.camelCase()}') .replaceAll('@(appClass)', className) .replaceAll('@(library)', '${fileName}_${locale.languageCode}'); } return lookupBodyTemplate .replaceAll('@(lookupAllCodesSpecified)', _generateLookupByAllCodes( allBundles, generateSwitchClauseTemplate, )) .replaceAll('@(lookupScriptCodeSpecified)', _generateLookupByScriptCode( allBundles, generateSwitchClauseTemplate, )) .replaceAll('@(lookupCountryCodeSpecified)', _generateLookupByCountryCode( allBundles, generateSwitchClauseTemplate, )) .replaceAll('@(lookupLanguageCodeSpecified)', _generateLookupByLanguageCode( allBundles, generateSwitchClauseTemplate, )); } String _generateDelegateClass({ required AppResourceBundleCollection allBundles, required String className, required Set<String> supportedLanguageCodes, required bool useDeferredLoading, required String fileName, }) { final String lookupBody = _generateLookupBody( allBundles, className, useDeferredLoading, fileName, ); final String loadBody = ( useDeferredLoading ? loadBodyDeferredLoadingTemplate : loadBodyTemplate ) .replaceAll('@(class)', className) .replaceAll('@(lookupName)', 'lookup$className'); final String lookupFunction = (useDeferredLoading ? lookupFunctionDeferredLoadingTemplate : lookupFunctionTemplate) .replaceAll('@(class)', className) .replaceAll('@(lookupName)', 'lookup$className') .replaceAll('@(lookupBody)', lookupBody); return delegateClassTemplate .replaceAll('@(class)', className) .replaceAll('@(loadBody)', loadBody) .replaceAll('@(supportedLanguageCodes)', supportedLanguageCodes.join(', ')) .replaceAll('@(lookupFunction)', lookupFunction); } class LocalizationsGenerator { /// Initializes [inputDirectory], [outputDirectory], [templateArbFile], /// [outputFile] and [className]. /// /// Throws an [L10nException] when a provided configuration is not allowed /// by [LocalizationsGenerator]. /// /// Throws a [FileSystemException] when a file operation necessary for setting /// up the [LocalizationsGenerator] cannot be completed. factory LocalizationsGenerator({ required FileSystem fileSystem, required String inputPathString, String? outputPathString, required String templateArbFileName, required String outputFileString, required String classNameString, List<String>? preferredSupportedLocales, String? headerString, String? headerFile, bool useDeferredLoading = false, String? inputsAndOutputsListPath, bool useSyntheticPackage = true, String? projectPathString, bool areResourceAttributesRequired = false, String? untranslatedMessagesFile, bool usesNullableGetter = true, bool useEscaping = false, required Logger logger, bool suppressWarnings = false, bool useRelaxedSyntax = false, bool useNamedParameters = false, }) { final Directory? projectDirectory = projectDirFromPath(fileSystem, projectPathString); final Directory inputDirectory = inputDirectoryFromPath(fileSystem, inputPathString, projectDirectory); final Directory outputDirectory = outputDirectoryFromPath(fileSystem, outputPathString ?? inputPathString, useSyntheticPackage, projectDirectory); return LocalizationsGenerator._( fileSystem, useSyntheticPackage: useSyntheticPackage, usesNullableGetter: usesNullableGetter, className: classNameFromString(classNameString), projectDirectory: projectDirectory, inputDirectory: inputDirectory, outputDirectory: outputDirectory, templateArbFile: templateArbFileFromFileName(templateArbFileName, inputDirectory), baseOutputFile: outputDirectory.childFile(outputFileString), preferredSupportedLocales: preferredSupportedLocalesFromLocales(preferredSupportedLocales), header: headerFromFile(headerString, headerFile, inputDirectory), useDeferredLoading: useDeferredLoading, untranslatedMessagesFile: _untranslatedMessagesFileFromPath(fileSystem, untranslatedMessagesFile), inputsAndOutputsListFile: _inputsAndOutputsListFileFromPath(fileSystem, inputsAndOutputsListPath), areResourceAttributesRequired: areResourceAttributesRequired, useEscaping: useEscaping, logger: logger, suppressWarnings: suppressWarnings, useRelaxedSyntax: useRelaxedSyntax, useNamedParameters: useNamedParameters, ); } /// Creates an instance of the localizations generator class. /// /// It takes in a [FileSystem] representation that the class will act upon. LocalizationsGenerator._(this._fs, { required this.inputDirectory, required this.outputDirectory, required this.templateArbFile, required this.baseOutputFile, required this.className, this.preferredSupportedLocales = const <LocaleInfo>[], this.header = '', this.useDeferredLoading = false, required this.inputsAndOutputsListFile, this.useSyntheticPackage = true, this.projectDirectory, this.areResourceAttributesRequired = false, this.untranslatedMessagesFile, this.usesNullableGetter = true, required this.logger, this.useEscaping = false, this.suppressWarnings = false, this.useRelaxedSyntax = false, this.useNamedParameters = false, }); final FileSystem _fs; List<Message> _allMessages = <Message>[]; late final AppResourceBundleCollection _allBundles = AppResourceBundleCollection(inputDirectory); late final AppResourceBundle _templateBundle = AppResourceBundle(templateArbFile); late final Map<LocaleInfo, String> _inputFileNames = Map<LocaleInfo, String>.fromEntries( _allBundles.bundles.map((AppResourceBundle bundle) => MapEntry<LocaleInfo, String>(bundle.locale, bundle.file.basename)) ); late final LocaleInfo _templateArbLocale = _templateBundle.locale; @visibleForTesting final bool useSyntheticPackage; // Used to decide if the generated code is nullable or not // (whether AppLocalizations? or AppLocalizations is returned from // `static {name}Localizations{?} of (BuildContext context))` @visibleForTesting final bool usesNullableGetter; /// The directory that contains the project's arb files, as well as the /// header file, if specified. /// /// It is assumed that all input files (e.g. [templateArbFile], arb files /// for translated messages, header file templates) will reside here. final Directory inputDirectory; /// The Flutter project's root directory. final Directory? projectDirectory; /// The directory to generate the project's localizations files in. /// /// It is assumed that all output files (e.g. The localizations /// [outputFile], `messages_<locale>.dart` and `messages_all.dart`) /// will reside here. final Directory outputDirectory; /// The input arb file which defines all of the messages that will be /// exported by the generated class that's written to [outputFile]. final File templateArbFile; /// The file to write the generated abstract localizations and /// localizations delegate classes to. Separate localizations /// files will also be generated for each language using this /// filename as a prefix and the locale as the suffix. final File baseOutputFile; /// The class name to be used for the localizations class in [outputFile]. /// /// For example, if 'AppLocalizations' is passed in, a class named /// AppLocalizations will be used for localized message lookups. final String className; /// The list of preferred supported locales. /// /// By default, the list of supported locales in the localizations class /// will be sorted in alphabetical order. However, this option /// allows for a set of preferred locales to appear at the top of the /// list. /// /// The order of locales in this list will also be the order of locale /// priority. For example, if a device supports 'en' and 'es' and /// ['es', 'en'] is passed in, the 'es' locale will take priority over 'en'. final List<LocaleInfo> preferredSupportedLocales; // Whether we need to import intl or not. This flag is updated after parsing // all of the messages. bool requiresIntlImport = false; // Whether we want to use escaping for ICU messages. bool useEscaping = false; /// Whether any errors were caught. This is set after encountering any errors /// from calling [_generateMethod]. bool hadErrors = false; /// Whether to use relaxed syntax. bool useRelaxedSyntax = false; /// The list of all arb path strings in [inputDirectory]. List<String> get arbPathStrings { return _allBundles.bundles.map((AppResourceBundle bundle) => bundle.file.path).toList(); } List<String> get outputFileList { return _outputFileList; } /// The supported language codes as found in the arb files located in /// [inputDirectory]. final Set<String> supportedLanguageCodes = <String>{}; /// The supported locales as found in the arb files located in /// [inputDirectory]. final Set<LocaleInfo> supportedLocales = <LocaleInfo>{}; /// The header to be prepended to the generated Dart localization file. final String header; final Map<LocaleInfo, List<String>> _unimplementedMessages = <LocaleInfo, List<String>>{}; /// Whether to generate the Dart localization file with locales imported as /// deferred, allowing for lazy loading of each locale in Flutter web. /// /// This can reduce a web app’s initial startup time by decreasing the size of /// the JavaScript bundle. When [_useDeferredLoading] is set to true, the /// messages for a particular locale are only downloaded and loaded by the /// Flutter app as they are needed. For projects with a lot of different /// locales and many localization strings, it can be an performance /// improvement to have deferred loading. For projects with a small number of /// locales, the difference is negligible, and might slow down the start up /// compared to bundling the localizations with the rest of the application. /// /// This flag does not affect other platforms such as mobile or desktop. final bool useDeferredLoading; /// Contains a map of each output language file to its corresponding content in /// string format. final Map<File, String> _languageFileMap = <File, String>{}; /// A generated file that will contain the list of messages for each locale /// that do not have a translation yet. final File? untranslatedMessagesFile; /// The file that contains the list of inputs and outputs for generating /// localizations. @visibleForTesting final File? inputsAndOutputsListFile; final List<String> _inputFileList = <String>[]; final List<String> _outputFileList = <String>[]; /// Whether or not resource attributes are required for each corresponding /// resource id. /// /// Resource attributes provide metadata about the message. @visibleForTesting final bool areResourceAttributesRequired; /// Logger to be used during the execution of the script. Logger logger; /// Whether or not to suppress warnings or not. final bool suppressWarnings; /// Whether to generate the Dart localization methods with named parameters. /// /// If this sets to true, the generated Dart localization methods will be: /// ``` /// String helloWorld({required String name}); /// ``` final bool useNamedParameters; static bool _isNotReadable(FileStat fileStat) { final String rawStatString = fileStat.modeString(); // Removes potential prepended permission bits, such as '(suid)' and '(guid)'. final String statString = rawStatString.substring(rawStatString.length - 9); return !(statString[0] == 'r' || statString[3] == 'r' || statString[6] == 'r'); } static bool _isNotWritable(FileStat fileStat) { final String rawStatString = fileStat.modeString(); // Removes potential prepended permission bits, such as '(suid)' and '(guid)'. final String statString = rawStatString.substring(rawStatString.length - 9); return !(statString[1] == 'w' || statString[4] == 'w' || statString[7] == 'w'); } @visibleForTesting static Directory? projectDirFromPath(FileSystem fileSystem, String? projectPathString) { if (projectPathString == null) { return null; } final Directory directory = fileSystem.directory(projectPathString); if (!directory.existsSync()) { throw L10nException( 'Directory does not exist: $directory.\n' "Please select a directory that contains the project's localizations " 'resource files.' ); } return directory; } /// Sets the reference [Directory] for [inputDirectory]. @visibleForTesting static Directory inputDirectoryFromPath(FileSystem fileSystem, String inputPathString, Directory? projectDirectory) { final Directory inputDirectory = fileSystem.directory( projectDirectory != null ? _getAbsoluteProjectPath(inputPathString, projectDirectory) : inputPathString ); if (!inputDirectory.existsSync()) { throw L10nException( "The 'arb-dir' directory, '$inputDirectory', does not exist.\n" 'Make sure that the correct path was provided.' ); } final FileStat fileStat = inputDirectory.statSync(); if (_isNotReadable(fileStat) || _isNotWritable(fileStat)) { throw L10nException( "The 'arb-dir' directory, '$inputDirectory', doesn't allow reading and writing.\n" 'Please ensure that the user has read and write permissions.' ); } return inputDirectory; } /// Sets the reference [Directory] for [outputDirectory]. @visibleForTesting static Directory outputDirectoryFromPath(FileSystem fileSystem, String outputPathString, bool useSyntheticPackage, Directory? projectDirectory) { Directory outputDirectory; if (useSyntheticPackage) { outputDirectory = fileSystem.directory( projectDirectory != null ? _getAbsoluteProjectPath(_syntheticL10nPackagePath(fileSystem), projectDirectory) : _syntheticL10nPackagePath(fileSystem) ); } else { outputDirectory = fileSystem.directory( projectDirectory != null ? _getAbsoluteProjectPath(outputPathString, projectDirectory) : outputPathString ); } return outputDirectory; } /// Sets the reference [File] for [templateArbFile]. @visibleForTesting static File templateArbFileFromFileName(String templateArbFileName, Directory inputDirectory) { final File templateArbFile = inputDirectory.childFile(templateArbFileName); final FileStat templateArbFileStat = templateArbFile.statSync(); if (templateArbFileStat.type == FileSystemEntityType.notFound) { throw L10nException( "The 'template-arb-file', $templateArbFile, does not exist." ); } final String templateArbFileStatModeString = templateArbFileStat.modeString(); if (templateArbFileStatModeString[0] == '-' && templateArbFileStatModeString[3] == '-') { throw L10nException( "The 'template-arb-file', $templateArbFile, is not readable.\n" 'Please ensure that the user has read permissions.' ); } return templateArbFile; } static bool _isValidClassName(String className) { // Public Dart class name cannot begin with an underscore if (className[0] == '_') { return false; } // Dart class name cannot contain non-alphanumeric symbols if (className.contains(RegExp(r'[^a-zA-Z_\d]'))) { return false; } // Dart class name must start with upper case character if (className[0].contains(RegExp(r'[a-z]'))) { return false; } // Dart class name cannot start with a number if (className[0].contains(RegExp(r'\d'))) { return false; } return true; } /// Sets the [className] for the localizations and localizations delegate /// classes. @visibleForTesting static String classNameFromString(String classNameString) { if (classNameString.isEmpty) { throw L10nException('classNameString argument cannot be empty'); } if (!_isValidClassName(classNameString)) { throw L10nException( "The 'output-class', $classNameString, is not a valid public Dart class name.\n" ); } return classNameString; } /// Sets [preferredSupportedLocales] so that this particular list of locales /// will take priority over the other locales. @visibleForTesting static List<LocaleInfo> preferredSupportedLocalesFromLocales(List<String>? inputLocales) { if (inputLocales == null || inputLocales.isEmpty) { return const <LocaleInfo>[]; } return inputLocales.map((String localeString) { return LocaleInfo.fromString(localeString); }).toList(); } static String headerFromFile(String? headerString, String? headerFile, Directory inputDirectory) { if (headerString != null && headerFile != null) { throw L10nException( 'Cannot accept both header and header file arguments. \n' 'Please make sure to define only one or the other. ' ); } if (headerString != null) { return headerString; } else if (headerFile != null) { try { return inputDirectory.childFile(headerFile).readAsStringSync(); } on FileSystemException catch (error) { throw L10nException ( 'Failed to read header file: "$headerFile". \n' 'FileSystemException: ${error.message}' ); } } return ''; } static String _getAbsoluteProjectPath(String relativePath, Directory projectDirectory) => projectDirectory.fileSystem.path.join(projectDirectory.path, relativePath); static File? _untranslatedMessagesFileFromPath(FileSystem fileSystem, String? untranslatedMessagesFileString) { if (untranslatedMessagesFileString == null || untranslatedMessagesFileString.isEmpty) { return null; } untranslatedMessagesFileString = untranslatedMessagesFileString.replaceAll(r'\', fileSystem.path.separator); return fileSystem.file(untranslatedMessagesFileString); } static File? _inputsAndOutputsListFileFromPath(FileSystem fileSystem, String? inputsAndOutputsListPath) { if (inputsAndOutputsListPath == null) { return null; } return fileSystem.file( fileSystem.path.join(inputsAndOutputsListPath, 'gen_l10n_inputs_and_outputs.json'), ); } static bool _isValidGetterAndMethodName(String name) { if (name.isEmpty) { return false; } // Public Dart method name must not start with an underscore if (name[0] == '_') { return false; } // Dart identifiers can only use letters, numbers, underscores, and `$` if (name.contains(RegExp(r'[^a-zA-Z_$\d]'))) { return false; } // Dart getter and method name should start with lower case character if (name[0].contains(RegExp(r'[A-Z]'))) { return false; } // Dart getter and method name cannot start with a number if (name[0].contains(RegExp(r'\d'))) { return false; } return true; } // Load _allMessages from templateArbFile and _allBundles from all of the ARB // files in inputDirectory. Also initialized: supportedLocales. void loadResources() { for (final String resourceId in _templateBundle.resourceIds) { if (!_isValidGetterAndMethodName(resourceId)) { throw L10nException( 'Invalid ARB resource name "$resourceId" in $templateArbFile.\n' 'Resources names must be valid Dart method names: they have to be ' 'camel case, cannot start with a number or underscore, and cannot ' 'contain non-alphanumeric characters.' ); } } // The call to .toList() is absolutely necessary. Otherwise, it is an iterator and will call Message's constructor again. _allMessages = _templateBundle.resourceIds.map((String id) => Message( _templateBundle, _allBundles, id, areResourceAttributesRequired, useEscaping: useEscaping, logger: logger, useRelaxedSyntax: useRelaxedSyntax, )).toList(); hadErrors = _allMessages.any((Message message) => message.hadErrors); if (inputsAndOutputsListFile != null) { _inputFileList.addAll(_allBundles.bundles.map((AppResourceBundle bundle) { return bundle.file.absolute.path; })); } final List<LocaleInfo> allLocales = List<LocaleInfo>.from(_allBundles.locales); for (final LocaleInfo preferredLocale in preferredSupportedLocales) { final int index = allLocales.indexOf(preferredLocale); if (index == -1) { throw L10nException( "The preferred supported locale, '$preferredLocale', cannot be " 'added. Please make sure that there is a corresponding ARB file ' 'with translations for the locale, or remove the locale from the ' 'preferred supported locale list.' ); } allLocales.removeAt(index); allLocales.insertAll(0, preferredSupportedLocales); } supportedLocales.addAll(allLocales); } void _addUnimplementedMessage(LocaleInfo locale, String message) { if (_unimplementedMessages.containsKey(locale)) { _unimplementedMessages[locale]!.add(message); } else { _unimplementedMessages.putIfAbsent(locale, () => <String>[message]); } } String _generateBaseClassFile( String className, String fileName, String header, final LocaleInfo locale, ) { final Iterable<String> methods = _allMessages.map((Message message) { LocaleInfo localeWithFallback = locale; if (message.messages[locale] == null) { _addUnimplementedMessage(locale, message.resourceId); localeWithFallback = _templateArbLocale; } if (message.parsedMessages[localeWithFallback] == null) { // The message exists, but parsedMessages[locale] is null due to a syntax error. // This means that we have already set hadErrors = true while constructing the Message. return ''; } return _generateMethod( message, localeWithFallback, ); }); return classFileTemplate .replaceAll('@(header)', header.isEmpty ? '' : '$header\n\n') .replaceAll('@(language)', describeLocale(locale.toString())) .replaceAll('@(baseClass)', className) .replaceAll('@(fileName)', fileName) .replaceAll('@(class)', '$className${locale.camelCase()}') .replaceAll('@(localeName)', locale.toString()) .replaceAll('@(methods)', methods.join('\n\n')) .replaceAll('@(requiresIntlImport)', requiresIntlImport ? "import 'package:intl/intl.dart' as intl;\n\n" : ''); } String _generateSubclass( String className, AppResourceBundle bundle, ) { final LocaleInfo locale = bundle.locale; final String baseClassName = '$className${LocaleInfo.fromString(locale.languageCode).camelCase()}'; _allMessages .where((Message message) => message.messages[locale] == null) .forEach((Message message) { _addUnimplementedMessage(locale, message.resourceId); }); final Iterable<String> methods = _allMessages .where((Message message) => message.parsedMessages[locale] != null) .map((Message message) => _generateMethod(message, locale)); return subclassTemplate .replaceAll('@(language)', describeLocale(locale.toString())) .replaceAll('@(baseLanguageClassName)', baseClassName) .replaceAll('@(class)', '$className${locale.camelCase()}') .replaceAll('@(localeName)', locale.toString()) .replaceAll('@(methods)', methods.join('\n\n')); } // Generate the AppLocalizations class, its LocalizationsDelegate subclass, // and all AppLocalizations subclasses for every locale. This method by // itself does not generate the output files. String _generateCode() { bool isBaseClassLocale(LocaleInfo locale, String language) { return locale.languageCode == language && locale.countryCode == null && locale.scriptCode == null; } List<LocaleInfo> getLocalesForLanguage(String language) { return _allBundles.bundles // Return locales for the language specified, except for the base locale itself .where((AppResourceBundle bundle) { final LocaleInfo locale = bundle.locale; return !isBaseClassLocale(locale, language) && locale.languageCode == language; }) .map((AppResourceBundle bundle) => bundle.locale).toList(); } final String directory = _fs.path.basename(outputDirectory.path); final String outputFileName = _fs.path.basename(baseOutputFile.path); if (!outputFileName.endsWith('.dart')) { throw L10nException( "The 'output-localization-file', $outputFileName, is invalid.\n" 'The file name must have a .dart extension.' ); } final Iterable<String> supportedLocalesCode = supportedLocales.map((LocaleInfo locale) { final String languageCode = locale.languageCode; final String? countryCode = locale.countryCode; final String? scriptCode = locale.scriptCode; if (countryCode == null && scriptCode == null) { return "Locale('$languageCode')"; } else if (countryCode != null && scriptCode == null) { return "Locale('$languageCode', '$countryCode')"; } else if (countryCode != null && scriptCode != null) { return "Locale.fromSubtags(languageCode: '$languageCode', countryCode: '$countryCode', scriptCode: '$scriptCode')"; } else { return "Locale.fromSubtags(languageCode: '$languageCode', scriptCode: '$scriptCode')"; } }); final Set<String> supportedLanguageCodes = Set<String>.from( _allBundles.locales.map<String>((LocaleInfo locale) => "'${locale.languageCode}'") ); final List<LocaleInfo> allLocales = _allBundles.locales.toList()..sort(); final int extensionIndex = outputFileName.indexOf('.'); if (extensionIndex <= 0) { throw L10nException( "The 'output-localization-file', $outputFileName, is invalid.\n" 'The base name cannot be empty.' ); } final String fileName = outputFileName.substring(0, extensionIndex); final String fileExtension = outputFileName.substring(extensionIndex + 1); for (final LocaleInfo locale in allLocales) { if (isBaseClassLocale(locale, locale.languageCode)) { final File languageMessageFile = outputDirectory.childFile('${fileName}_$locale.$fileExtension'); // Generate the template for the base class file. Further string // interpolation will be done to determine if there are // subclasses that extend the base class. final String languageBaseClassFile = _generateBaseClassFile( className, outputFileName, header, locale, ); // Every locale for the language except the base class. final List<LocaleInfo> localesForLanguage = getLocalesForLanguage(locale.languageCode); // Generate every subclass that is needed for the particular language final Iterable<String> subclasses = localesForLanguage.map<String>((LocaleInfo locale) { return _generateSubclass( className, _allBundles.bundleFor(locale)!, ); }); _languageFileMap.putIfAbsent(languageMessageFile, () { return languageBaseClassFile.replaceAll('@(subclasses)', subclasses.join()); }); } } final List<String> sortedClassImports = supportedLocales .where((LocaleInfo locale) => isBaseClassLocale(locale, locale.languageCode)) .map((LocaleInfo locale) { final String library = '${fileName}_$locale'; if (useDeferredLoading) { return "import '$library.$fileExtension' deferred as $library;"; } else { return "import '$library.$fileExtension';"; } }) .toList() ..sort(); final String delegateClass = _generateDelegateClass( allBundles: _allBundles, className: className, supportedLanguageCodes: supportedLanguageCodes, useDeferredLoading: useDeferredLoading, fileName: fileName, ); return fileTemplate .replaceAll('@(header)', header.isEmpty ? '' : '$header\n') .replaceAll('@(class)', className) .replaceAll('@(methods)', _allMessages.map((Message message) => generateBaseClassMethod(message, _templateArbLocale, useNamedParameters)).join('\n')) .replaceAll('@(importFile)', '$directory/$outputFileName') .replaceAll('@(supportedLocales)', supportedLocalesCode.join(',\n ')) .replaceAll('@(supportedLanguageCodes)', supportedLanguageCodes.join(', ')) .replaceAll('@(messageClassImports)', sortedClassImports.join('\n')) .replaceAll('@(delegateClass)', delegateClass) .replaceAll('@(requiresFoundationImport)', useDeferredLoading ? '' : "import 'package:flutter/foundation.dart';") .replaceAll('@(requiresIntlImport)', requiresIntlImport ? "import 'package:intl/intl.dart' as intl;" : '') .replaceAll('@(canBeNullable)', usesNullableGetter ? '?' : '') .replaceAll('@(needsNullCheck)', usesNullableGetter ? '' : '!') // Removes all trailing whitespace from the generated file. .split('\n').map((String line) => line.trimRight()).join('\n') // Cleans out unnecessary newlines. .replaceAll('\n\n\n', '\n\n'); } String _generateMethod(Message message, LocaleInfo locale) { try { // Determine if we must import intl for date or number formatting. if (message.placeholdersRequireFormatting) { requiresIntlImport = true; } final String translationForMessage = message.messages[locale]!; final Node node = message.parsedMessages[locale]!; // If the placeholders list is empty, then return a getter method. if (message.placeholders.isEmpty) { // Use the parsed translation to handle escaping with the same behavior. return getterTemplate .replaceAll('@(name)', message.resourceId) .replaceAll('@(message)', "'${generateString(node.children.map((Node child) => child.value!).join())}'"); } final List<String> tempVariables = <String>[]; // Get a unique temporary variable name. int variableCount = 0; String getTempVariableName() { return '_temp${variableCount++}'; } // Do a DFS post order traversal through placeholderExpr, pluralExpr, and selectExpr nodes. // When traversing through a placeholderExpr node, return "$placeholderName". // When traversing through a pluralExpr node, return "$tempVarN" and add variable declaration in "tempVariables". // When traversing through a selectExpr node, return "$tempVarN" and add variable declaration in "tempVariables". // When traversing through an argumentExpr node, return "$tempVarN" and add variable declaration in "tempVariables". // When traversing through a message node, return concatenation of all of "generateVariables(child)" for each child. String generateVariables(Node node, { bool isRoot = false }) { switch (node.type) { case ST.message: final List<String> expressions = node.children.map<String>((Node node) { if (node.type == ST.string) { return generateString(node.value!); } return generateVariables(node); }).toList(); return generateReturnExpr(expressions); case ST.placeholderExpr: assert(node.children[1].type == ST.identifier); final String identifier = node.children[1].value!; final Placeholder placeholder = message.placeholders[identifier]!; if (placeholder.requiresFormatting) { return '\$${node.children[1].value}String'; } return '\$${node.children[1].value}'; case ST.pluralExpr: requiresIntlImport = true; final Map<String, String> pluralLogicArgs = <String, String>{}; // Recall that pluralExpr are of the form // pluralExpr := "{" ID "," "plural" "," pluralParts "}" assert(node.children[1].type == ST.identifier); assert(node.children[5].type == ST.pluralParts); final Node identifier = node.children[1]; final Node pluralParts = node.children[5]; for (final Node pluralPart in pluralParts.children.reversed) { String pluralCase; Node pluralMessage; if (pluralPart.children[0].value == '=') { assert(pluralPart.children[1].type == ST.number); assert(pluralPart.children[3].type == ST.message); pluralCase = pluralPart.children[1].value!; pluralMessage = pluralPart.children[3]; } else { assert(pluralPart.children[0].type == ST.identifier || pluralPart.children[0].type == ST.other); assert(pluralPart.children[2].type == ST.message); pluralCase = pluralPart.children[0].value!; pluralMessage = pluralPart.children[2]; } if (!pluralLogicArgs.containsKey(pluralCases[pluralCase])) { final String pluralPartExpression = generateVariables(pluralMessage); final String? transformedPluralCase = pluralCases[pluralCase]; // A valid plural case is one of "=0", "=1", "=2", "zero", "one", "two", "few", "many", or "other". if (transformedPluralCase == null) { throw L10nParserException( ''' The plural cases must be one of "=0", "=1", "=2", "zero", "one", "two", "few", "many", or "other. $pluralCase is not a valid plural case.''', _inputFileNames[locale]!, message.resourceId, translationForMessage, pluralPart.positionInMessage, ); } pluralLogicArgs[transformedPluralCase] = ' ${pluralCases[pluralCase]}: $pluralPartExpression,'; } else if (!suppressWarnings) { logger.printWarning(''' [${_inputFileNames[locale]}:${message.resourceId}] ICU Syntax Warning: The plural part specified below is overridden by a later plural part. $translationForMessage ${Parser.indentForError(pluralPart.positionInMessage)}'''); } } final String tempVarName = getTempVariableName(); tempVariables.add(pluralVariableTemplate .replaceAll('@(varName)', tempVarName) .replaceAll('@(count)', identifier.value!) .replaceAll('@(pluralLogicArgs)', pluralLogicArgs.values.join('\n')) ); return '\$$tempVarName'; case ST.selectExpr: requiresIntlImport = true; // Recall that pluralExpr are of the form // pluralExpr := "{" ID "," "plural" "," pluralParts "}" assert(node.children[1].type == ST.identifier); assert(node.children[5].type == ST.selectParts); final Node identifier = node.children[1]; final List<String> selectLogicArgs = <String>[]; final Node selectParts = node.children[5]; for (final Node selectPart in selectParts.children) { assert(selectPart.children[0].type == ST.identifier || selectPart.children[0].type == ST.other); assert(selectPart.children[2].type == ST.message); final String selectCase = selectPart.children[0].value!; final Node selectMessage = selectPart.children[2]; final String selectPartExpression = generateVariables(selectMessage); selectLogicArgs.add(" '$selectCase': $selectPartExpression,"); } final String tempVarName = getTempVariableName(); tempVariables.add(selectVariableTemplate .replaceAll('@(varName)', tempVarName) .replaceAll('@(choice)', identifier.value!) .replaceAll('@(selectCases)', selectLogicArgs.join('\n')) ); return '\$$tempVarName'; case ST.argumentExpr: requiresIntlImport = true; assert(node.children[1].type == ST.identifier); assert(node.children[3].type == ST.argType); assert(node.children[7].type == ST.identifier); final String identifierName = node.children[1].value!; final Node formatType = node.children[7]; // Check that formatType is a valid intl.DateFormat. if (!validDateFormats.contains(formatType.value)) { throw L10nParserException( 'Date format "${formatType.value!}" for placeholder ' '$identifierName does not have a corresponding DateFormat ' "constructor\n. Check the intl library's DateFormat class " 'constructors for allowed date formats, or set "isCustomDateFormat" attribute ' 'to "true".', _inputFileNames[locale]!, message.resourceId, translationForMessage, formatType.positionInMessage, ); } final String tempVarName = getTempVariableName(); tempVariables.add(dateVariableTemplate .replaceAll('@(varName)', tempVarName) .replaceAll('@(formatType)', formatType.value!) .replaceAll('@(argument)', identifierName) ); return '\$$tempVarName'; // ignore: no_default_cases default: throw Exception('Cannot call "generateHelperMethod" on node type ${node.type}'); } } final String messageString = generateVariables(node, isRoot: true); final String tempVarLines = tempVariables.isEmpty ? '' : '${tempVariables.join('\n')}\n'; return (useNamedParameters ? methodWithNamedParameterTemplate : methodTemplate) .replaceAll('@(name)', message.resourceId) .replaceAll('@(parameters)', generateMethodParameters(message, useNamedParameters).join(', ')) .replaceAll('@(dateFormatting)', generateDateFormattingLogic(message)) .replaceAll('@(numberFormatting)', generateNumberFormattingLogic(message)) .replaceAll('@(tempVars)', tempVarLines) .replaceAll('@(message)', messageString) .replaceAll('@(none)\n', ''); } on L10nParserException catch (error) { logger.printError(error.toString()); hadErrors = true; return ''; } } List<String> writeOutputFiles({ bool isFromYaml = false, bool useCRLF = false }) { // First, generate the string contents of all necessary files. final String generatedLocalizationsFile = _generateCode(); // If there were any syntax errors, don't write to files. if (hadErrors) { throw L10nException('Found syntax errors.'); } // A pubspec.yaml file is required when using a synthetic package. If it does not // exist, create a blank one. if (useSyntheticPackage) { final Directory syntheticPackageDirectory = projectDirectory != null ? projectDirectory!.childDirectory(_defaultSyntheticPackagePath(_fs)) : _fs.directory(_defaultSyntheticPackagePath(_fs)); syntheticPackageDirectory.createSync(recursive: true); final File flutterGenPubspec = syntheticPackageDirectory.childFile('pubspec.yaml'); if (!flutterGenPubspec.existsSync()) { flutterGenPubspec.writeAsStringSync( useCRLF ? emptyPubspecTemplate.replaceAll('\n', '\r\n') : emptyPubspecTemplate ); } } // Since all validity checks have passed up to this point, // write the contents into the directory. outputDirectory.createSync(recursive: true); // Ensure that the created directory has read/write permissions. final FileStat fileStat = outputDirectory.statSync(); if (_isNotReadable(fileStat) || _isNotWritable(fileStat)) { throw L10nException( "The 'output-dir' directory, $outputDirectory, doesn't allow reading and writing.\n" 'Please ensure that the user has read and write permissions.' ); } // Generate the required files for localizations. _languageFileMap.forEach((File file, String contents) { file.writeAsStringSync(useCRLF ? contents.replaceAll('\n', '\r\n') : contents); _outputFileList.add(file.absolute.path); }); baseOutputFile.writeAsStringSync( useCRLF ? generatedLocalizationsFile.replaceAll('\n', '\r\n') : generatedLocalizationsFile ); final File? messagesFile = untranslatedMessagesFile; if (messagesFile != null) { _generateUntranslatedMessagesFile(logger, messagesFile); } else if (_unimplementedMessages.isNotEmpty) { _unimplementedMessages.forEach((LocaleInfo locale, List<String> messages) { logger.printStatus('"$locale": ${messages.length} untranslated message(s).'); }); if (isFromYaml) { logger.printStatus( 'To see a detailed report, use the untranslated-messages-file \n' 'option in the l10n.yaml file:\n' 'untranslated-messages-file: desiredFileName.txt\n' '<other option>: <other selection> \n\n' ); } else { logger.printStatus( 'To see a detailed report, use the --untranslated-messages-file \n' 'option in the flutter gen-l10n tool:\n' 'flutter gen-l10n --untranslated-messages-file=desiredFileName.txt\n' '<other options> \n\n' ); } logger.printStatus( 'This will generate a JSON format file containing all messages that \n' 'need to be translated.' ); } final File? inputsAndOutputsListFileLocal = inputsAndOutputsListFile; _outputFileList.add(baseOutputFile.absolute.path); if (inputsAndOutputsListFileLocal != null) { // Generate a JSON file containing the inputs and outputs of the gen_l10n script. if (!inputsAndOutputsListFileLocal.existsSync()) { inputsAndOutputsListFileLocal.createSync(recursive: true); } final String filesListContent = json.encode(<String, Object> { 'inputs': _inputFileList, 'outputs': _outputFileList, }); inputsAndOutputsListFileLocal.writeAsStringSync( useCRLF ? filesListContent.replaceAll('\n', '\r\n') : filesListContent, ); } return _outputFileList; } void _generateUntranslatedMessagesFile(Logger logger, File untranslatedMessagesFile) { if (_unimplementedMessages.isEmpty) { untranslatedMessagesFile.writeAsStringSync('{}'); _outputFileList.add(untranslatedMessagesFile.absolute.path); return; } String resultingFile = '{\n'; int count = 0; final int numberOfLocales = _unimplementedMessages.length; _unimplementedMessages.forEach((LocaleInfo locale, List<String> messages) { resultingFile += ' "$locale": [\n'; for (int i = 0; i < messages.length; i += 1) { resultingFile += ' "${messages[i]}"'; if (i != messages.length - 1) { resultingFile += ','; } resultingFile += '\n'; } resultingFile += ' ]'; count += 1; if (count < numberOfLocales) { resultingFile += ',\n'; } resultingFile += '\n'; }); resultingFile += '}\n'; untranslatedMessagesFile.writeAsStringSync(resultingFile); _outputFileList.add(untranslatedMessagesFile.absolute.path); } }
flutter/packages/flutter_tools/lib/src/localizations/gen_l10n.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/localizations/gen_l10n.dart", "repo_id": "flutter", "token_count": 21261 }
756
// Copyright 2014 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:unified_analytics/unified_analytics.dart'; import '../../base/common.dart'; import '../../base/file_system.dart'; import '../../base/project_migrator.dart'; import '../../reporting/reporting.dart'; import '../../xcode_project.dart'; // Remove the linking and embedding logic from the Xcode project to give the tool more control over these. class RemoveMacOSFrameworkLinkAndEmbeddingMigration extends ProjectMigrator { RemoveMacOSFrameworkLinkAndEmbeddingMigration( MacOSProject project, super.logger, Usage usage, Analytics analytics, ) : _xcodeProjectInfoFile = project.xcodeProjectInfoFile, _usage = usage, _analytics = analytics; final File _xcodeProjectInfoFile; final Usage _usage; final Analytics _analytics; @override void migrate() { if (!_xcodeProjectInfoFile.existsSync()) { logger.printTrace( 'Xcode project not found, skipping framework link and embedding migration'); return; } processFileLines(_xcodeProjectInfoFile); } @override String? migrateLine(String line) { // App.framework Frameworks reference. // isa = PBXFrameworksBuildPhase; // files = ( // D73912F022F37F9E000D13A0 /* App.framework in Frameworks */, if (line.contains('D73912F022F37F9E000D13A0')) { return null; } // App.framework Embed Framework reference (build phase to embed framework). // D73912F222F3801D000D13A0 /* App.framework in Bundle Framework */, if (line.contains('D73912F222F3801D000D13A0')) { return null; } // App.framework project file reference (seen in Xcode navigator pane). // isa = PBXGroup; // children = ( // D73912EF22F37F9E000D13A0 /* App.framework */, if (line.contains('D73912EF22F37F9E000D13A0')) { return null; } // FlutterMacOS.framework Frameworks reference. // isa = PBXFrameworksBuildPhase; // files = ( // 33D1A10422148B71006C7A3E /* FlutterMacOS.framework in Frameworks */, if (line.contains('33D1A10422148B71006C7A3E')) { return null; } // FlutterMacOS.framework Embed Framework reference (build phase to embed framework). // 33D1A10522148B93006C7A3E /* FlutterMacOS.framework in Bundle Framework */, if (line.contains('33D1A10522148B93006C7A3E')) { return null; } // FlutterMacOS.framework project file reference (seen in Xcode navigator pane). // isa = PBXGroup; // children = ( // 33D1A10322148B71006C7A3E /* FlutterMacOS.framework */, if (line.contains('33D1A10322148B71006C7A3E')) { return null; } // Embed frameworks in a script instead of using Xcode's link / embed build phases. const String thinBinaryScript = r'/Flutter/ephemeral/.app_filename'; if (line.contains(thinBinaryScript) && !line.contains(' embed')) { return line.replaceFirst( thinBinaryScript, r'/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed'); } if (line.contains('/* App.framework ') || line.contains('/* FlutterMacOS.framework ')) { UsageEvent('macos-migration', 'remove-frameworks', label: 'failure', flutterUsage: _usage) .send(); _analytics.send(Event.appleUsageEvent( workflow: 'macos-migration', parameter: 'remove-frameworks', result: 'failure', )); throwToolExit( 'Your Xcode project requires migration.'); } return line; } }
flutter/packages/flutter_tools/lib/src/macos/migrations/remove_macos_framework_link_and_embedding_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/macos/migrations/remove_macos_framework_link_and_embedding_migration.dart", "repo_id": "flutter", "token_count": 1422 }
757
// Copyright 2014 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 'base/common.dart'; import 'base/file_system.dart'; import 'cache.dart'; /// A validator that runs before the tool runs any command. abstract class PreRunValidator { factory PreRunValidator({required FileSystem fileSystem}) = _DefaultPreRunValidator; void validate(); } class _DefaultPreRunValidator implements PreRunValidator { _DefaultPreRunValidator({ required this.fileSystem, }); final FileSystem fileSystem; late final Directory _toolsDir = fileSystem.directory( fileSystem.path.join(Cache.flutterRoot!, 'packages', 'flutter_tools'), ); @override void validate() { // If a user downloads the Flutter SDK via a pre-built archive and there is // an error during extraction, the user could have a valid Dart snapshot of // the tool but not the source directory. We still need the source, so // validate the source directory exists and toolExit if not. if (!_toolsDir.existsSync()) { throwToolExit( 'Flutter SDK installation appears corrupted: expected to find the ' 'directory ${_toolsDir.path} but it does not exist! Please go to ' 'https://flutter.dev/setup for instructions on how to re-install ' 'Flutter.', ); } } } class NoOpPreRunValidator implements PreRunValidator { const NoOpPreRunValidator(); @override void validate() {} }
flutter/packages/flutter_tools/lib/src/pre_run_validator.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/pre_run_validator.dart", "repo_id": "flutter", "token_count": 470 }
758
// Copyright 2014 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:file/file.dart'; import 'package:intl/intl.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../build_system/exceptions.dart'; import '../convert.dart'; import '../devfs.dart'; import '../flutter_manifest.dart'; import '../flutter_project_metadata.dart'; import '../project.dart'; import '../version.dart'; /// Provide suggested GitHub issue templates to user when Flutter encounters an error. class GitHubTemplateCreator { GitHubTemplateCreator({ required FileSystem fileSystem, required Logger logger, required FlutterProjectFactory flutterProjectFactory, }) : _fileSystem = fileSystem, _logger = logger, _flutterProjectFactory = flutterProjectFactory; final FileSystem _fileSystem; final Logger _logger; final FlutterProjectFactory _flutterProjectFactory; static String toolCrashSimilarIssuesURL(String errorString) { return 'https://github.com/flutter/flutter/issues?q=is%3Aissue+${Uri.encodeQueryComponent(errorString)}'; } /// Restricts exception object strings to contain only information about tool internals. static String sanitizedCrashException(Object error) { if (error is ProcessException) { // Suppress args. return 'ProcessException: ${error.message} Command: ${error.executable}, OS error code: ${error.errorCode}'; } else if (error is FileSystemException) { // Suppress path. return 'FileSystemException: ${error.message}, ${error.osError}'; } else if (error is SocketException) { // Suppress address and port. return 'SocketException: ${error.message}, ${error.osError}'; } else if (error is DevFSException) { // Suppress underlying error. return 'DevFSException: ${error.message}'; } else if (error is NoSuchMethodError || error is ArgumentError || error is VersionCheckError || error is MissingDefineException || error is UnsupportedError || error is UnimplementedError || error is StateError || error is ProcessExit || error is OSError) { // These exception objects only reference tool internals, print the whole error. return '${error.runtimeType}: $error'; } else if (error is Error) { return '${error.runtimeType}: ${LineSplitter.split(error.stackTrace.toString()).take(1)}'; } else if (error is String) { // Force comma separator to standardize. return 'String: <${NumberFormat(null, 'en_US').format(error.length)} characters>'; } // Exception, other. return error.runtimeType.toString(); } /// GitHub URL to present to the user containing encoded suggested template. /// /// Shorten the URL, if possible. Future<String> toolCrashIssueTemplateGitHubURL( String command, Object error, StackTrace stackTrace, String doctorText ) async { final String errorString = sanitizedCrashException(error); final String title = '[tool_crash] $errorString'; final String body = ''' ## Command ``` $command ``` ## Steps to Reproduce 1. ... 2. ... 3. ... ## Logs $errorString ``` ${LineSplitter.split(stackTrace.toString()).take(25).join('\n')} ``` ``` $doctorText ``` ## Flutter Application Metadata ${_projectMetadataInformation()} '''; return 'https://github.com/flutter/flutter/issues' '/new' // We split this here to appease our lint that looks for bad "new bug" links. '?title=${Uri.encodeQueryComponent(title)}' '&body=${Uri.encodeQueryComponent(body)}' '&labels=${Uri.encodeQueryComponent('tool,severe: crash')}'; } /// Provide information about the Flutter project in the working directory, if present. String _projectMetadataInformation() { FlutterProject project; try { project = _flutterProjectFactory.fromDirectory(_fileSystem.currentDirectory); } on Exception catch (exception) { // pubspec may be malformed. return exception.toString(); } try { final FlutterManifest manifest = project.manifest; if (manifest.isEmpty) { return 'No pubspec in working directory.'; } final FlutterProjectMetadata metadata = FlutterProjectMetadata(project.metadataFile, _logger); final FlutterProjectType? projectType = metadata.projectType; final StringBuffer description = StringBuffer() ..writeln('**Type**: ${projectType == null ? 'malformed' : projectType.cliName}') ..writeln('**Version**: ${manifest.appVersion}') ..writeln('**Material**: ${manifest.usesMaterialDesign}') ..writeln('**Android X**: ${manifest.usesAndroidX}') ..writeln('**Module**: ${manifest.isModule}') ..writeln('**Plugin**: ${manifest.isPlugin}') ..writeln('**Android package**: ${manifest.androidPackage}') ..writeln('**iOS bundle identifier**: ${manifest.iosBundleIdentifier}') ..writeln('**Creation channel**: ${metadata.versionChannel}') ..writeln('**Creation framework version**: ${metadata.versionRevision}'); final File file = project.flutterPluginsFile; if (file.existsSync()) { description.writeln('### Plugins'); // Format is: // camera=/path/to/.pub-cache/hosted/pub.dartlang.org/camera-0.5.7+2/ for (final String plugin in project.flutterPluginsFile.readAsLinesSync()) { final List<String> pluginParts = plugin.split('='); if (pluginParts.length != 2) { continue; } // Write the last part of the path, which includes the plugin name and version. // Example: camera-0.5.7+2 final List<String> pathParts = _fileSystem.path.split(pluginParts[1]); description.writeln(pathParts.isEmpty ? pluginParts.first : pathParts.last); } } return description.toString(); } on Exception catch (exception) { return exception.toString(); } } }
flutter/packages/flutter_tools/lib/src/reporting/github_template.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/reporting/github_template.dart", "repo_id": "flutter", "token_count": 2157 }
759
// Copyright 2014 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:dds/dds.dart'; import 'package:meta/meta.dart'; import 'package:package_config/package_config.dart'; import 'package:stream_channel/stream_channel.dart'; import 'package:test_core/src/platform.dart'; // ignore: implementation_imports import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../cache.dart'; import '../compile.dart'; import '../convert.dart'; import '../dart/language_version.dart'; import '../device.dart'; import '../globals.dart' as globals; import '../native_assets.dart'; import '../project.dart'; import '../test/test_wrapper.dart'; import 'flutter_tester_device.dart'; import 'font_config_manager.dart'; import 'integration_test_device.dart'; import 'test_compiler.dart'; import 'test_config.dart'; import 'test_device.dart'; import 'test_time_recorder.dart'; import 'watcher.dart'; /// The address at which our WebSocket server resides and at which the sky_shell /// processes will host the VmService server. final Map<InternetAddressType, InternetAddress> _kHosts = <InternetAddressType, InternetAddress>{ InternetAddressType.IPv4: InternetAddress.loopbackIPv4, InternetAddressType.IPv6: InternetAddress.loopbackIPv6, }; typedef PlatformPluginRegistration = void Function(FlutterPlatform platform); /// Configure the `test` package to work with Flutter. /// /// On systems where each [FlutterPlatform] is only used to run one test suite /// (that is, one Dart file with a `*_test.dart` file name and a single `void /// main()`), you can set a VM Service port explicitly. FlutterPlatform installHook({ TestWrapper testWrapper = const TestWrapper(), required String shellPath, required DebuggingOptions debuggingOptions, TestWatcher? watcher, // TODO(bkonyi): remove after roll into google3. bool enableObservatory = false, bool enableVmService = false, bool machine = false, String? precompiledDillPath, Map<String, String>? precompiledDillFiles, bool updateGoldens = false, String? testAssetDirectory, InternetAddressType serverType = InternetAddressType.IPv4, Uri? projectRootDirectory, FlutterProject? flutterProject, String? icudtlPath, PlatformPluginRegistration? platformPluginRegistration, Device? integrationTestDevice, String? integrationTestUserIdentifier, TestTimeRecorder? testTimeRecorder, UriConverter? uriConverter, TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) { assert(enableVmService || enableObservatory || (!debuggingOptions.startPaused && debuggingOptions.hostVmServicePort == null)); // registerPlatformPlugin can be injected for testing since it's not very mock-friendly. platformPluginRegistration ??= (FlutterPlatform platform) { testWrapper.registerPlatformPlugin( <Runtime>[Runtime.vm], () { return platform; }, ); }; final FlutterPlatform platform = FlutterPlatform( shellPath: shellPath, debuggingOptions: debuggingOptions, watcher: watcher, machine: machine, enableVmService: enableVmService || enableObservatory, host: _kHosts[serverType], precompiledDillPath: precompiledDillPath, precompiledDillFiles: precompiledDillFiles, updateGoldens: updateGoldens, testAssetDirectory: testAssetDirectory, projectRootDirectory: projectRootDirectory, flutterProject: flutterProject, icudtlPath: icudtlPath, integrationTestDevice: integrationTestDevice, integrationTestUserIdentifier: integrationTestUserIdentifier, testTimeRecorder: testTimeRecorder, uriConverter: uriConverter, nativeAssetsBuilder: nativeAssetsBuilder, ); platformPluginRegistration(platform); return platform; } /// Generates the bootstrap entry point script that will be used to launch an /// individual test file. /// /// The [testUrl] argument specifies the path to the test file that is being /// launched. /// /// The [host] argument specifies the address at which the test harness is /// running. /// /// If [testConfigFile] is specified, it must follow the conventions of test /// configuration files as outlined in the [flutter_test] library. By default, /// the test file will be launched directly. /// /// The [updateGoldens] argument will set the [autoUpdateGoldens] global /// variable in the [flutter_test] package before invoking the test. /// /// The [integrationTest] argument can be specified to generate the bootstrap /// for integration tests. /// // This API is used by the Fuchsia source tree, do not add new // required or position parameters. String generateTestBootstrap({ required Uri testUrl, required InternetAddress host, File? testConfigFile, bool updateGoldens = false, String languageVersionHeader = '', bool nullSafety = false, bool flutterTestDep = true, bool integrationTest = false, }) { final String websocketUrl = host.type == InternetAddressType.IPv4 ? 'ws://${host.address}' : 'ws://[${host.address}]'; final StringBuffer buffer = StringBuffer(); buffer.write(''' $languageVersionHeader import 'dart:async'; import 'dart:convert'; // flutter_ignore: dart_convert_import import 'dart:io'; // flutter_ignore: dart_io_import import 'dart:isolate'; '''); if (flutterTestDep) { buffer.write(''' import 'package:flutter_test/flutter_test.dart'; '''); } if (integrationTest) { buffer.write(''' import 'package:integration_test/integration_test.dart'; import 'dart:developer' as developer; '''); } buffer.write(''' import 'package:test_api/backend.dart'; import 'package:stream_channel/stream_channel.dart'; import 'package:stack_trace/stack_trace.dart'; import '$testUrl' as test; '''); if (testConfigFile != null) { buffer.write(''' import '${Uri.file(testConfigFile.path)}' as test_config; '''); } buffer.write(''' /// Returns a serialized test suite. StreamChannel<dynamic> serializeSuite(Function getMain()) { return RemoteListener.start(getMain); } Future<void> _testMain() async { '''); if (integrationTest) { buffer.write(''' IntegrationTestWidgetsFlutterBinding.ensureInitialized(); '''); } // Don't propagate the return value of `test.main` here. If the `main` // function on users` test is annotated with `@doNotStore`, it will cause an // analyzer error otherwise. buffer.write(''' await Future(test.main); } /// Capture any top-level errors (mostly lazy syntax errors, since other are /// caught below) and report them to the parent isolate. void catchIsolateErrors() { final ReceivePort errorPort = ReceivePort(); // Treat errors non-fatal because otherwise they'll be double-printed. Isolate.current.setErrorsFatal(false); Isolate.current.addErrorListener(errorPort.sendPort); errorPort.listen((dynamic message) { // Masquerade as an IsolateSpawnException because that's what this would // be if the error had been detected statically. final IsolateSpawnException error = IsolateSpawnException( message[0] as String); final Trace stackTrace = message[1] == null ? Trace(const <Frame>[]) : Trace.parse(message[1] as String); Zone.current.handleUncaughtError(error, stackTrace); }); } void main() { final String serverPort = Platform.environment['SERVER_PORT'] ?? ''; final String server = '$websocketUrl:\$serverPort'; StreamChannel<dynamic> testChannel = serializeSuite(() { catchIsolateErrors(); '''); if (flutterTestDep) { buffer.write(''' goldenFileComparator = LocalFileComparator(Uri.parse('$testUrl')); autoUpdateGoldenFiles = $updateGoldens; '''); } if (testConfigFile != null) { buffer.write(''' return () => test_config.testExecutable(_testMain); '''); } else { buffer.write(''' return _testMain; '''); } buffer.write(''' }); '''); if (integrationTest) { buffer.write(''' final callback = (method, params) async { testChannel.sink.add(json.decode(params['$kIntegrationTestData'] as String)); // Result is ignored but null is not accepted here. return developer.ServiceExtensionResponse.result('{}'); }; developer.registerExtension('$kIntegrationTestMethod', callback); testChannel.stream.listen((x) { developer.postEvent( '$kIntegrationTestExtension', {'$kIntegrationTestData': json.encode(x)}, ); }); '''); } else { buffer.write(''' WebSocket.connect(server).then((WebSocket socket) { socket.map((dynamic message) { // We're only communicating with string encoded JSON. return json.decode(message as String); }).pipe(testChannel.sink); socket.addStream(testChannel.stream.map(json.encode)); }); '''); } buffer.write(''' } '''); return buffer.toString(); } typedef Finalizer = Future<void> Function(); /// The flutter test platform used to integrate with package:test. class FlutterPlatform extends PlatformPlugin { FlutterPlatform({ required this.shellPath, required this.debuggingOptions, this.watcher, this.enableVmService, this.machine, this.host, this.precompiledDillPath, this.precompiledDillFiles, this.updateGoldens, this.testAssetDirectory, this.projectRootDirectory, this.flutterProject, this.icudtlPath, this.integrationTestDevice, this.integrationTestUserIdentifier, this.testTimeRecorder, this.uriConverter, this.nativeAssetsBuilder, }); final String shellPath; final DebuggingOptions debuggingOptions; final TestWatcher? watcher; final bool? enableVmService; final bool? machine; final InternetAddress? host; final String? precompiledDillPath; final Map<String, String>? precompiledDillFiles; final bool? updateGoldens; final String? testAssetDirectory; final Uri? projectRootDirectory; final FlutterProject? flutterProject; final String? icudtlPath; final TestTimeRecorder? testTimeRecorder; final TestCompilerNativeAssetsBuilder? nativeAssetsBuilder; // This can be used by internal projects that require custom logic for converting package: URIs to local paths. final UriConverter? uriConverter; /// The device to run the test on for Integration Tests. /// /// If this is null, the test will run as a regular test with the Flutter /// Tester; otherwise it will run as a Integration Test on this device. final Device? integrationTestDevice; bool get _isIntegrationTest => integrationTestDevice != null; final String? integrationTestUserIdentifier; final FontConfigManager _fontConfigManager = FontConfigManager(); /// The test compiler produces dill files for each test main. /// /// To speed up compilation, each compile is initialized from an existing /// dill file from previous runs, if possible. TestCompiler? compiler; // Each time loadChannel() is called, we spin up a local WebSocket server, // then spin up the engine in a subprocess. We pass the engine a Dart file // that connects to our WebSocket server, then we proxy JSON messages from // the test harness to the engine and back again. If at any time the engine // crashes, we inject an error into that stream. When the process closes, // we clean everything up. int _testCount = 0; @override Future<RunnerSuite> load( String path, SuitePlatform platform, SuiteConfiguration suiteConfig, Object message, ) async { // loadChannel may throw an exception. That's fine; it will cause the // LoadSuite to emit an error, which will be presented to the user. // Except for the Declarer error, which is a specific test incompatibility // error we need to catch. final StreamChannel<dynamic> channel = loadChannel(path, platform); final RunnerSuiteController controller = deserializeSuite(path, platform, suiteConfig, const PluginEnvironment(), channel, message); return controller.suite; } StreamChannel<dynamic> loadChannel(String path, SuitePlatform platform) { if (_testCount > 0) { // Fail if there will be a port conflict. if (debuggingOptions.hostVmServicePort != null) { throwToolExit('installHook() was called with a VM Service port or debugger mode enabled, but then more than one test suite was run.'); } // Fail if we're passing in a precompiled entry-point. if (precompiledDillPath != null) { throwToolExit('installHook() was called with a precompiled test entry-point, but then more than one test suite was run.'); } } final int ourTestCount = _testCount; _testCount += 1; final StreamController<dynamic> localController = StreamController<dynamic>(); final StreamController<dynamic> remoteController = StreamController<dynamic>(); final Completer<_AsyncError?> testCompleteCompleter = Completer<_AsyncError?>(); final _FlutterPlatformStreamSinkWrapper<dynamic> remoteSink = _FlutterPlatformStreamSinkWrapper<dynamic>( remoteController.sink, testCompleteCompleter.future, ); final StreamChannel<dynamic> localChannel = StreamChannel<dynamic>.withGuarantees( remoteController.stream, localController.sink, ); final StreamChannel<dynamic> remoteChannel = StreamChannel<dynamic>.withGuarantees( localController.stream, remoteSink, ); testCompleteCompleter.complete(_startTest(path, localChannel, ourTestCount)); return remoteChannel; } Future<String> _compileExpressionService( String isolateId, String expression, List<String> definitions, List<String> definitionTypes, List<String> typeDefinitions, List<String> typeBounds, List<String> typeDefaults, String libraryUri, String? klass, String? method, bool isStatic, ) async { if (compiler == null || compiler!.compiler == null) { throw Exception('Compiler is not set up properly to compile $expression'); } final CompilerOutput? compilerOutput = await compiler!.compiler!.compileExpression(expression, definitions, definitionTypes, typeDefinitions, typeBounds, typeDefaults, libraryUri, klass, method, isStatic); if (compilerOutput != null && compilerOutput.expressionData != null) { return base64.encode(compilerOutput.expressionData!); } throw Exception('Failed to compile $expression'); } TestDevice _createTestDevice(int ourTestCount) { if (_isIntegrationTest) { return IntegrationTestTestDevice( id: ourTestCount, debuggingOptions: debuggingOptions, device: integrationTestDevice!, userIdentifier: integrationTestUserIdentifier, compileExpression: _compileExpressionService ); } return FlutterTesterTestDevice( id: ourTestCount, platform: globals.platform, fileSystem: globals.fs, processManager: globals.processManager, logger: globals.logger, shellPath: shellPath, enableVmService: enableVmService!, machine: machine, debuggingOptions: debuggingOptions, host: host, testAssetDirectory: testAssetDirectory, flutterProject: flutterProject, icudtlPath: icudtlPath, compileExpression: _compileExpressionService, fontConfigManager: _fontConfigManager, uriConverter: uriConverter, ); } Future<_AsyncError?> _startTest( String testPath, StreamChannel<dynamic> testHarnessChannel, int ourTestCount, ) async { globals.printTrace('test $ourTestCount: starting test $testPath'); _AsyncError? outOfBandError; // error that we couldn't send to the harness that we need to send via our future final List<Finalizer> finalizers = <Finalizer>[]; // Will be run in reverse order. bool controllerSinkClosed = false; try { // Callback can't throw since it's just setting a variable. unawaited(testHarnessChannel.sink.done.whenComplete(() { controllerSinkClosed = true; })); void initializeExpressionCompiler(String path) { // When start paused is specified, it means that the user is likely // running this with a debugger attached. Initialize the resident // compiler in this case. if (debuggingOptions.startPaused) { compiler ??= TestCompiler( debuggingOptions.buildInfo, flutterProject, precompiledDillPath: precompiledDillPath, testTimeRecorder: testTimeRecorder, nativeAssetsBuilder: nativeAssetsBuilder, ); final Uri uri = globals.fs.file(path).uri; // Trigger a compilation to initialize the resident compiler. unawaited(compiler!.compile(uri)); } } // If a kernel file is given, then use that to launch the test. // If mapping is provided, look kernel file from mapping. // If all fails, create a "listener" dart that invokes actual test. String? mainDart; if (precompiledDillPath != null) { mainDart = precompiledDillPath; initializeExpressionCompiler(testPath); } else if (precompiledDillFiles != null) { mainDart = precompiledDillFiles![testPath]; } else { mainDart = _createListenerDart(finalizers, ourTestCount, testPath); // Integration test device takes care of the compilation. if (integrationTestDevice == null) { // Lazily instantiate compiler so it is built only if it is actually used. compiler ??= TestCompiler( debuggingOptions.buildInfo, flutterProject, testTimeRecorder: testTimeRecorder, nativeAssetsBuilder: nativeAssetsBuilder, ); mainDart = await compiler!.compile(globals.fs.file(mainDart).uri); if (mainDart == null) { testHarnessChannel.sink.addError('Compilation failed for testPath=$testPath'); return null; } } else { // For integration tests, we may still need to set up expression compilation service. initializeExpressionCompiler(mainDart); } } globals.printTrace('test $ourTestCount: starting test device'); final TestDevice testDevice = _createTestDevice(ourTestCount); final Stopwatch? testTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.Run); final Future<StreamChannel<String>> remoteChannelFuture = testDevice.start(mainDart!); finalizers.add(() async { globals.printTrace('test $ourTestCount: ensuring test device is terminated.'); await testDevice.kill(); }); // At this point, these things can happen: // A. The test device could crash, in which case [testDevice.finished] // will complete. // B. The test device could connect to us, in which case // [remoteChannelFuture] will complete. globals.printTrace('test $ourTestCount: awaiting connection to test device'); await Future.any<void>(<Future<void>>[ testDevice.finished, () async { final Uri? processVmServiceUri = await testDevice.vmServiceUri; if (processVmServiceUri != null) { globals.printTrace('test $ourTestCount: VM Service uri is available at $processVmServiceUri'); } else { globals.printTrace('test $ourTestCount: VM Service uri is not available'); } watcher?.handleStartedDevice(processVmServiceUri); final StreamChannel<String> remoteChannel = await remoteChannelFuture; globals.printTrace('test $ourTestCount: connected to test device, now awaiting test result'); await _pipeHarnessToRemote( id: ourTestCount, harnessChannel: testHarnessChannel, remoteChannel: remoteChannel, ); globals.printTrace('test $ourTestCount: finished'); testTimeRecorder?.stop(TestTimePhases.Run, testTimeRecorderStopwatch!); final Stopwatch? watchTestTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.WatcherFinishedTest); await watcher?.handleFinishedTest(testDevice); testTimeRecorder?.stop(TestTimePhases.WatcherFinishedTest, watchTestTimeRecorderStopwatch!); }() ]); } on Exception catch (error, stackTrace) { Object reportedError = error; StackTrace reportedStackTrace = stackTrace; if (error is TestDeviceException) { reportedError = error.message; reportedStackTrace = error.stackTrace; } globals.printTrace('test $ourTestCount: error caught during test; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}'); if (!controllerSinkClosed) { testHarnessChannel.sink.addError(reportedError, reportedStackTrace); } else { globals.printError('unhandled error during test:\n$testPath\n$reportedError\n$reportedStackTrace'); outOfBandError ??= _AsyncError(reportedError, reportedStackTrace); } } finally { globals.printTrace('test $ourTestCount: cleaning up...'); // Finalizers are treated like a stack; run them in reverse order. for (final Finalizer finalizer in finalizers.reversed) { try { await finalizer(); } on Exception catch (error, stack) { globals.printTrace('test $ourTestCount: error while cleaning up; ${controllerSinkClosed ? "reporting to console" : "sending to test framework"}'); if (!controllerSinkClosed) { testHarnessChannel.sink.addError(error, stack); } else { globals.printError('unhandled error during finalization of test:\n$testPath\n$error\n$stack'); outOfBandError ??= _AsyncError(error, stack); } } } if (!controllerSinkClosed) { // Waiting below with await. unawaited(testHarnessChannel.sink.close()); globals.printTrace('test $ourTestCount: waiting for controller sink to close'); await testHarnessChannel.sink.done; } } assert(controllerSinkClosed); if (outOfBandError != null) { globals.printTrace('test $ourTestCount: finished with out-of-band failure'); } else { globals.printTrace('test $ourTestCount: finished'); } return outOfBandError; } String _createListenerDart( List<Finalizer> finalizers, int ourTestCount, String testPath, ) { // Prepare a temporary directory to store the Dart file that will talk to us. final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_test_listener.'); finalizers.add(() async { globals.printTrace('test $ourTestCount: deleting temporary directory'); tempDir.deleteSync(recursive: true); }); // Prepare the Dart file that will talk to us and start the test. final File listenerFile = globals.fs.file('${tempDir.path}/listener.dart'); listenerFile.createSync(); listenerFile.writeAsStringSync(_generateTestMain( testUrl: globals.fs.path.toUri(globals.fs.path.absolute(testPath)), )); return listenerFile.path; } String _generateTestMain({ required Uri testUrl, }) { assert(testUrl.scheme == 'file'); final File file = globals.fs.file(testUrl); final PackageConfig packageConfig = debuggingOptions.buildInfo.packageConfig; final LanguageVersion languageVersion = determineLanguageVersion( file, packageConfig[flutterProject!.manifest.appName], Cache.flutterRoot!, ); return generateTestBootstrap( testUrl: testUrl, testConfigFile: findTestConfigFile(globals.fs.file(testUrl), globals.logger), host: host!, updateGoldens: updateGoldens!, flutterTestDep: packageConfig['flutter_test'] != null, languageVersionHeader: '// @dart=${languageVersion.major}.${languageVersion.minor}', integrationTest: _isIntegrationTest, ); } @override Future<dynamic> close() async { if (compiler != null) { await compiler!.dispose(); compiler = null; } await _fontConfigManager.dispose(); } } // The [_shellProcessClosed] future can't have errors thrown on it because it // crosses zones (it's fed in a zone created by the test package, but listened // to by a parent zone, the same zone that calls [close] below). // // This is because Dart won't let errors that were fed into a Future in one zone // propagate to listeners in another zone. (Specifically, the zone in which the // future was completed with the error, and the zone in which the listener was // registered, are what matters.) // // Because of this, the [_shellProcessClosed] future takes an [_AsyncError] // object as a result. If it's null, it's as if it had completed correctly; if // it's non-null, it contains the error and stack trace of the actual error, as // if it had completed with that error. class _FlutterPlatformStreamSinkWrapper<S> implements StreamSink<S> { _FlutterPlatformStreamSinkWrapper(this._parent, this._shellProcessClosed); final StreamSink<S> _parent; final Future<_AsyncError?> _shellProcessClosed; @override Future<void> get done => _done.future; final Completer<void> _done = Completer<void>(); @override Future<dynamic> close() { Future.wait<dynamic>(<Future<dynamic>>[ _parent.close(), _shellProcessClosed, ]).then<void>( (List<dynamic> futureResults) { assert(futureResults.length == 2); assert(futureResults.first == null); final dynamic lastResult = futureResults.last; if (lastResult is _AsyncError) { _done.completeError(lastResult.error as Object, lastResult.stack); } else { assert(lastResult == null); _done.complete(); } }, onError: _done.completeError, ); return done; } @override void add(S event) => _parent.add(event); @override void addError(Object errorEvent, [ StackTrace? stackTrace ]) => _parent.addError(errorEvent, stackTrace); @override Future<dynamic> addStream(Stream<S> stream) => _parent.addStream(stream); } @immutable class _AsyncError { const _AsyncError(this.error, this.stack); final dynamic error; final StackTrace stack; } /// Bridges the package:test harness and the remote device. /// /// The returned future completes when either side is closed, which also /// indicates when the tests have finished. Future<void> _pipeHarnessToRemote({ required int id, required StreamChannel<dynamic> harnessChannel, required StreamChannel<String> remoteChannel, }) async { globals.printTrace('test $id: Waiting for test harness or tests to finish'); await Future.any<void>(<Future<void>>[ harnessChannel.stream .map<String>(json.encode) .pipe(remoteChannel.sink) .then<void>((void value) { globals.printTrace('test $id: Test process is no longer needed by test harness'); }), remoteChannel.stream .map<dynamic>(json.decode) .pipe(harnessChannel.sink) .then<void>((void value) { globals.printTrace('test $id: Test harness is no longer needed by test process'); }), ]); }
flutter/packages/flutter_tools/lib/src/test/flutter_platform.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/test/flutter_platform.dart", "repo_id": "flutter", "token_count": 9251 }
760
// Copyright 2014 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 constant is in its own library so that the test exemption bot knows // that changing a pin does not require a new test. These pins are already // tested as part of the analysis shard. /// Map from package name to package version, used to artificially pin a pub /// package version in cases when upgrading to the latest breaks Flutter. /// /// These version pins must be pins, not ranges! Allowing these to be ranges /// defeats the whole purpose of pinning all our dependencies, which is to /// prevent upstream changes from causing our CI to fail randomly in ways /// unrelated to the commits. It also, more importantly, risks breaking users /// in ways that prevent them from ever upgrading Flutter again! const Map<String, String> kManuallyPinnedDependencies = <String, String>{ // Add pinned packages here. Please leave a comment explaining why. 'flutter_gallery_assets': '1.0.2', // Tests depend on the exact version. 'flutter_template_images': '4.2.0', // Must always exactly match flutter_tools template. 'material_color_utilities': '0.8.0', // Keep pinned to latest until 1.0.0. 'archive': '3.3.2', // https://github.com/flutter/flutter/issues/115660 'leak_tracker': '10.0.4', // https://github.com/flutter/devtools/issues/3951 'leak_tracker_testing': '3.0.1', // https://github.com/flutter/devtools/issues/3951 'leak_tracker_flutter_testing': '3.0.3', // https://github.com/flutter/devtools/issues/3951 'path_provider_android': '2.2.1', // https://github.com/flutter/flutter/issues/140796 };
flutter/packages/flutter_tools/lib/src/update_packages_pins.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/update_packages_pins.dart", "repo_id": "flutter", "token_count": 497 }
761
// Copyright 2014 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:unified_analytics/unified_analytics.dart'; import '../base/context.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/net.dart'; import '../base/time.dart'; import '../device.dart'; import '../project.dart'; import '../reporting/reporting.dart'; import '../resident_runner.dart'; WebRunnerFactory? get webRunnerFactory => context.get<WebRunnerFactory>(); // Hack to hide web imports for google3. abstract class WebRunnerFactory { const WebRunnerFactory(); /// Create a [ResidentRunner] for the web. ResidentRunner createWebRunner( FlutterDevice device, { String? target, required bool stayResident, required FlutterProject flutterProject, required bool? ipv6, required DebuggingOptions debuggingOptions, UrlTunneller? urlTunneller, required Logger logger, required FileSystem fileSystem, required SystemClock systemClock, required Usage usage, required Analytics analytics, bool machine = false, }); }
flutter/packages/flutter_tools/lib/src/web/web_runner.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/web/web_runner.dart", "repo_id": "flutter", "token_count": 368 }
762
name: flutter_tools description: Tools for building Flutter applications homepage: https://flutter.dev environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: # To update these, use "flutter update-packages --force-upgrade". # # For detailed instructions, refer to: # https://github.com/flutter/flutter/wiki/Updating-dependencies-in-Flutter archive: 3.3.2 args: 2.4.2 browser_launcher: 1.1.1 dds: 3.3.1 dwds: 23.3.0 completion: 1.0.1 coverage: 1.7.2 crypto: 3.0.3 ffi: 2.1.2 file: 7.0.0 flutter_template_images: 4.2.0 html: 0.15.4 http: 0.13.6 intl: 0.19.0 meta: 1.12.0 multicast_dns: 0.3.2+6 mustache_template: 2.0.0 package_config: 2.1.0 process: 5.0.2 fake_async: 1.3.1 stack_trace: 1.11.1 usage: 4.1.1 webdriver: 3.0.3 webkit_inspection_protocol: 1.2.1 xml: 6.5.0 yaml: 3.1.2 native_stack_traces: 0.5.6 shelf: 1.4.1 vm_snapshot_analysis: 0.7.6 uuid: 3.0.7 web_socket_channel: 2.4.4 stream_channel: 2.1.2 shelf_web_socket: 1.0.4 shelf_static: 1.1.2 pub_semver: 2.1.4 pool: 1.5.1 path: 1.9.0 mime: 1.0.5 logging: 1.2.0 http_multi_server: 3.2.1 convert: 3.1.1 async: 2.11.0 unified_analytics: 5.8.8 cli_config: 0.1.2 graphs: 2.3.1 native_assets_builder: 0.5.0 native_assets_cli: 0.4.2 # We depend on very specific internal implementation details of the # 'test' package, which change between versions, so when upgrading # this, make sure the tests are still running correctly. test_api: 0.7.0 test_core: 0.6.0 vm_service: 14.2.0 standard_message_codec: 0.0.1+4 _fe_analyzer_shared: 67.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" analyzer: 6.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" built_collection: 5.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" built_value: 8.9.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" csslib: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dap: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dds_service_extensions: 1.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" devtools_shared: 8.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dtd: 1.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" extension_discovery: 2.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" fixnum: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" frontend_server_client: 3.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" http_parser: 4.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" io: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" json_rpc_2: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" petitparser: 6.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" platform: 3.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" shelf_proxy: 1.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_map_stack_trace: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_maps: 0.10.12 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" sse: 4.1.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" sync_http: 0.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vm_service_interface: 1.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" watcher: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" web: 0.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" yaml_edit: 2.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: collection: 1.18.0 file_testing: 3.0.0 pubspec_parse: 1.2.3 checked_yaml: 2.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" js: 0.7.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" json_annotation: 4.8.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" test: 1.25.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dartdoc: # Exclude this package from the hosted API docs. nodoc: true # PUBSPEC CHECKSUM: df1d
flutter/packages/flutter_tools/pubspec.yaml/0
{ "file_path": "flutter/packages/flutter_tools/pubspec.yaml", "repo_id": "flutter", "token_count": 2244 }
763
plugins { id "com.android.application" id "kotlin-android" // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. 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 = "{{androidIdentifier}}" compileSdk = flutter.compileSdkVersion ndkVersion = flutter.ndkVersion compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId = "{{androidIdentifier}}" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration. minSdk = flutter.minSdkVersion targetSdk = flutter.targetSdkVersion versionCode = flutterVersionCode.toInteger() versionName = flutterVersionName } buildTypes { release { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig = signingConfigs.debug } } } flutter { source = "../.." }
flutter/packages/flutter_tools/templates/app_shared/android-java.tmpl/app/build.gradle.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/app_shared/android-java.tmpl/app/build.gradle.tmpl", "repo_id": "flutter", "token_count": 679 }
764
// Generated file. Do not edit. def localProperties = new Properties() def localPropertiesFile = new File(buildscript.sourceFile.parentFile.parentFile, "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.library" apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" group = "{{androidIdentifier}}" version = "1.0" android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace = "{{androidIdentifier}}" } compileSdk = flutter.compileSdkVersion ndkVersion = flutter.ndkVersion compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } defaultConfig { minSdk = flutter.minSdkVersion targetSdk = flutter.targetSdkVersion versionCode = flutterVersionCode.toInteger() versionName = flutterVersionName } } flutter { source = "../.." }
flutter/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/android/library_new_embedding/Flutter.tmpl/build.gradle.tmpl", "repo_id": "flutter", "token_count": 560 }
765
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/{{projectName}}.iml" filepath="$PROJECT_DIR$/{{projectName}}.iml" /> </modules> </component> </project>
flutter/packages/flutter_tools/templates/package/.idea/modules.xml.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/package/.idea/modules.xml.tmpl", "repo_id": "flutter", "token_count": 103 }
766
package {{androidIdentifier}} import androidx.annotation.NonNull import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.flutter.plugin.common.MethodChannel.MethodCallHandler import io.flutter.plugin.common.MethodChannel.Result /** {{pluginClass}} */ class {{pluginClass}}: FlutterPlugin, MethodCallHandler { /// The MethodChannel that will the communication between Flutter and native Android /// /// This local reference serves to register the plugin with the Flutter Engine and unregister it /// when the Flutter Engine is detached from the Activity private lateinit var channel : MethodChannel override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) { channel = MethodChannel(flutterPluginBinding.binaryMessenger, "{{projectName}}") channel.setMethodCallHandler(this) } override fun onMethodCall(call: MethodCall, result: Result) { if (call.method == "getPlatformVersion") { result.success("Android ${android.os.Build.VERSION.RELEASE}") } else { result.notImplemented() } } override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { channel.setMethodCallHandler(null) } }
flutter/packages/flutter_tools/templates/plugin/android-kotlin.tmpl/src/main/kotlin/androidIdentifier/pluginClass.kt.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin/android-kotlin.tmpl/src/main/kotlin/androidIdentifier/pluginClass.kt.tmpl", "repo_id": "flutter", "token_count": 374 }
767
# The Flutter tooling requires that developers have CMake 3.10 or later # installed. You should not increase this version, as doing so will cause # the plugin to fail to compile for some customers of the plugin. cmake_minimum_required(VERSION 3.10) # Project-level configuration. set(PROJECT_NAME "{{projectName}}") project(${PROJECT_NAME} LANGUAGES CXX) # This value is used when generating builds using this plugin, so it must # not be changed. set(PLUGIN_NAME "{{projectName}}_plugin") # Any new source files that you add to the plugin should be added here. list(APPEND PLUGIN_SOURCES "{{pluginClassSnakeCase}}.cc" ) # Define the plugin library target. Its name must not be changed (see comment # on PLUGIN_NAME above). add_library(${PLUGIN_NAME} SHARED ${PLUGIN_SOURCES} ) # Apply a standard set of build settings that are configured in the # application-level CMakeLists.txt. This can be removed for plugins that want # full control over build settings. apply_standard_settings(${PLUGIN_NAME}) # Symbols are hidden by default to reduce the chance of accidental conflicts # between plugins. This should not be removed; any symbols that should be # exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. set_target_properties(${PLUGIN_NAME} PROPERTIES CXX_VISIBILITY_PRESET hidden) target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) # Source include directories and library dependencies. Add any plugin-specific # dependencies here. target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") target_link_libraries(${PLUGIN_NAME} PRIVATE flutter) target_link_libraries(${PLUGIN_NAME} PRIVATE PkgConfig::GTK) # List of absolute paths to libraries that should be bundled with the plugin. # This list could contain prebuilt libraries, or libraries created by an # external build triggered from this build file. set({{projectName}}_bundled_libraries "" PARENT_SCOPE ) # === Tests === # These unit tests can be run from a terminal after building the example. # Only enable test builds when building the example (which sets this variable) # so that plugin clients aren't building the tests. if (${include_${PROJECT_NAME}_tests}) if(${CMAKE_VERSION} VERSION_LESS "3.11.0") message("Unit tests require CMake 3.11.0 or later") else() set(TEST_RUNNER "${PROJECT_NAME}_test") enable_testing() # Add the Google Test dependency. include(FetchContent) FetchContent_Declare( googletest URL https://github.com/google/googletest/archive/release-1.11.0.zip ) # Prevent overriding the parent project's compiler/linker settings set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) # Disable install commands for gtest so it doesn't end up in the bundle. set(INSTALL_GTEST OFF CACHE BOOL "Disable installation of googletest" FORCE) FetchContent_MakeAvailable(googletest) # The plugin's exported API is not very useful for unit testing, so build the # sources directly into the test binary rather than using the shared library. add_executable(${TEST_RUNNER} test/{{pluginClassSnakeCase}}_test.cc ${PLUGIN_SOURCES} ) apply_standard_settings(${TEST_RUNNER}) target_include_directories(${TEST_RUNNER} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}") target_link_libraries(${TEST_RUNNER} PRIVATE flutter) target_link_libraries(${TEST_RUNNER} PRIVATE PkgConfig::GTK) target_link_libraries(${TEST_RUNNER} PRIVATE gtest_main gmock) # Enable automatic test discovery. include(GoogleTest) gtest_discover_tests(${TEST_RUNNER}) endif() # CMake version check endif() # include_${PROJECT_NAME}_tests
flutter/packages/flutter_tools/templates/plugin/linux.tmpl/CMakeLists.txt.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin/linux.tmpl/CMakeLists.txt.tmpl", "repo_id": "flutter", "token_count": 1116 }
768
/// A placeholder class that represents an entity or model. class SampleItem { const SampleItem(this.id); final int id; }
flutter/packages/flutter_tools/templates/skeleton/lib/src/sample_feature/sample_item.dart.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/skeleton/lib/src/sample_feature/sample_item.dart.tmpl", "repo_id": "flutter", "token_count": 35 }
769
// Copyright 2014 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/memory.dart'; import 'package:flutter_tools/src/android/android_sdk.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/common.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/process.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build.dart'; import 'package:flutter_tools/src/commands/build_ios.dart'; import 'package:flutter_tools/src/ios/code_signing.dart'; import 'package:flutter_tools/src/ios/mac.dart'; import 'package:flutter_tools/src/ios/plist_parser.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../../general.shard/ios/xcresult_test_data.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fakes.dart'; import '../../src/test_build_system.dart'; import '../../src/test_flutter_command_runner.dart'; class FakeXcodeProjectInterpreterWithBuildSettings extends FakeXcodeProjectInterpreter { FakeXcodeProjectInterpreterWithBuildSettings({this.productBundleIdentifier, this.developmentTeam = 'abc'}); @override Future<Map<String, String>> getBuildSettings( String projectPath, { XcodeProjectBuildContext? buildContext, Duration timeout = const Duration(minutes: 1), }) async { return <String, String>{ 'PRODUCT_BUNDLE_IDENTIFIER': productBundleIdentifier ?? 'io.flutter.someProject', 'TARGET_BUILD_DIR': 'build/ios/Release-iphoneos', 'WRAPPER_NAME': 'Runner.app', if (developmentTeam != null) 'DEVELOPMENT_TEAM': developmentTeam!, }; } /// The value of 'PRODUCT_BUNDLE_IDENTIFIER'. final String? productBundleIdentifier; final String? developmentTeam; } final Platform macosPlatform = FakePlatform( operatingSystem: 'macos', environment: <String, String>{ 'FLUTTER_ROOT': '/', 'HOME': '/', } ); final Platform notMacosPlatform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': '/', } ); void main() { late FileSystem fileSystem; late TestUsage usage; late FakeAnalytics fakeAnalytics; late BufferLogger logger; late FakeProcessManager processManager; late ProcessUtils processUtils; late Artifacts artifacts; setUpAll(() { Cache.disableLocking(); }); setUp(() { fileSystem = MemoryFileSystem.test(); artifacts = Artifacts.test(fileSystem: fileSystem); usage = TestUsage(); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); logger = BufferLogger.test(); processManager = FakeProcessManager.empty(); processUtils = ProcessUtils( logger: logger, processManager: processManager, ); }); // Sets up the minimal mock project files necessary to look like a Flutter project. void createCoreMockProjectFiles() { fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').createSync(); fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true); } // Sets up the minimal mock project files necessary for iOS builds to succeed. void createMinimalMockProjectFiles() { fileSystem.directory(fileSystem.path.join('ios', 'Runner.xcodeproj')).createSync(recursive: true); fileSystem.directory(fileSystem.path.join('ios', 'Runner.xcworkspace')).createSync(recursive: true); fileSystem.file(fileSystem.path.join('ios', 'Runner.xcodeproj', 'project.pbxproj')).createSync(); createCoreMockProjectFiles(); } const FakeCommand xattrCommand = FakeCommand(command: <String>[ 'xattr', '-r', '-d', 'com.apple.FinderInfo', '/', ]); FakeCommand setUpRsyncCommand({void Function(List<String> command)? onRun}) { return FakeCommand( command: const <String>[ 'rsync', '-8', '-av', '--delete', 'build/ios/Release-iphoneos/Runner.app', 'build/ios/iphoneos', ], onRun: onRun, ); } FakeCommand setUpXCResultCommand({String stdout = '', void Function(List<String> command)? onRun}) { return FakeCommand( command: const <String>[ 'xcrun', 'xcresulttool', 'get', '--path', _xcBundleDirectoryPath, '--format', 'json', ], stdout: stdout, onRun: onRun, ); } // Creates a FakeCommand for the xcodebuild call to build the app // in the given configuration. FakeCommand setUpFakeXcodeBuildHandler({ bool verbose = false, bool simulator = false, bool customNaming = false, bool disablePortPublication = false, String? deviceId, int exitCode = 0, String? stdout, void Function(List<String> command)? onRun, }) { return FakeCommand( command: <String>[ 'xcrun', 'xcodebuild', '-configuration', if (simulator) 'Debug' else 'Release', if (verbose) 'VERBOSE_SCRIPT_LOGGING=YES' else '-quiet', '-workspace', if (customNaming) 'RenamedWorkspace.xcworkspace' else 'Runner.xcworkspace', '-scheme', 'Runner', 'BUILD_DIR=/build/ios', '-sdk', if (simulator) ...<String>[ 'iphonesimulator', ] else ...<String>[ 'iphoneos', ], if (deviceId != null) ...<String>[ '-destination', 'id=$deviceId', ] else if (simulator) ...<String>[ '-destination', 'generic/platform=iOS Simulator', ] else ...<String>[ '-destination', 'generic/platform=iOS', ], '-resultBundlePath', _xcBundleDirectoryPath, '-resultBundleVersion', '3', if (disablePortPublication) 'DISABLE_PORT_PUBLICATION=YES', 'FLUTTER_SUPPRESS_ANALYTICS=true', 'COMPILER_INDEX_STORE_ENABLE=NO', ], stdout: ''' TARGET_BUILD_DIR=build/ios/Release-iphoneos WRAPPER_NAME=Runner.app $stdout ''', exitCode: exitCode, onRun: onRun, ); } testUsingContext('ios build fails when there is no ios project', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createCoreMockProjectFiles(); expect(createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub'] ), throwsToolExit(message: 'Application not configured for iOS')); }, overrides: <Type, Generator>{ Platform: () => macosPlatform, FileSystem: () => fileSystem, ProcessManager: () => processManager, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build fails in debug with code analysis', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createCoreMockProjectFiles(); expect(createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub', '--debug', '--analyze-size'] ), throwsToolExit(message: '--analyze-size" can only be used on release builds')); }, overrides: <Type, Generator>{ Platform: () => macosPlatform, FileSystem: () => fileSystem, ProcessManager: () => processManager, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build fails on non-macOS platform', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').createSync(); fileSystem.file(fileSystem.path.join('lib', 'main.dart')) .createSync(recursive: true); final bool supported = BuildIOSCommand(logger: BufferLogger.test(), verboseHelp: false).supported; expect(createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub'] ), supported ? throwsToolExit() : throwsA(isA<UsageException>())); }, overrides: <Type, Generator>{ Platform: () => notMacosPlatform, FileSystem: () => fileSystem, ProcessManager: () => processManager, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build invokes xcode build', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), setUpRsyncCommand(), ]); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub'] ); expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build invokes xcode build with disable port publication setting', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub', '--no-publish-port', '--ci'] ); expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( disablePortPublication: true, onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }, ), setUpRsyncCommand(), ]), Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build invokes xcode build without disable port publication setting when not in CI', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub', '--no-publish-port'] ); expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }, ), setUpRsyncCommand(), ]), Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build invokes xcode build with renamed xcodeproj and xcworkspace', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), osUtils: FakeOperatingSystemUtils(), fileSystem: fileSystem, logger: logger, processUtils: processUtils, ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(customNaming: true, onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), setUpRsyncCommand(), ]); fileSystem.directory(fileSystem.path.join('ios', 'RenamedProj.xcodeproj')).createSync(recursive: true); fileSystem.directory(fileSystem.path.join('ios', 'RenamedWorkspace.xcworkspace')).createSync(recursive: true); fileSystem.file(fileSystem.path.join('ios', 'RenamedProj.xcodeproj', 'project.pbxproj')).createSync(); createCoreMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub'] ); expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build invokes xcode build with device ID', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(deviceId: '1234', onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub', '--device-id', '1234'], ); expect(testLogger.statusText, contains('build/ios/iphoneos/Runner.app')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios simulator build invokes xcode build', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(simulator: true, onRun: (_) { fileSystem.directory('build/ios/Debug-iphonesimulator/Runner.app').createSync(recursive: true); }), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--simulator', '--no-pub'], ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('ios build invokes xcode build with verbosity', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(verbose: true, onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); }), setUpRsyncCommand(), ]); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub', '-v'], ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Performs code size analysis and sends analytics', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app').createSync(recursive: true); fileSystem.file('build/flutter_size_01/snapshot.arm64.json') ..createSync(recursive: true) ..writeAsStringSync(''' [ { "l": "dart:_internal", "c": "SubListIterable", "n": "[Optimized] skip", "s": 2400 } ]'''); fileSystem.file('build/flutter_size_01/trace.arm64.json') ..createSync(recursive: true) ..writeAsStringSync('{}'); }), setUpRsyncCommand(onRun: (_) => fileSystem.file('build/ios/iphoneos/Runner.app/Frameworks/App.framework/App') ..createSync(recursive: true) ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0))), ]); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub', '--analyze-size'] ); expect(logger.statusText, contains('A summary of your iOS bundle analysis can be found at')); expect(logger.statusText, contains('dart devtools --appSizeBase=')); expect(usage.events, contains( const TestUsageEvent('code-size-analysis', 'ios'), )); expect(fakeAnalytics.sentEvents, contains( Event.codeSizeAnalysis(platform: 'ios') )); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: macosPlatform), Usage: () => usage, Analytics: () => fakeAnalytics, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); group('Analytics for impeller plist setting', () { const String plistContents = ''' <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>FLTEnableImpeller</key> <false/> </dict> </plist> '''; const FakeCommand plutilCommand = FakeCommand( command: <String>[ '/usr/bin/plutil', '-convert', 'xml1', '-o', '-', '/ios/Runner/Info.plist', ], stdout: plistContents, ); testUsingContext('Sends an analytics event when Impeller is enabled', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: MemoryFileSystem.test(), logger: BufferLogger.test(), osUtils: FakeOperatingSystemUtils(), processUtils: processUtils, ); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub'] ); expect(usage.events, contains( const TestUsageEvent( 'build', 'ios', label:'plist-impeller-enabled', parameters:CustomDimensions(), ), )); expect(fakeAnalytics.sentEvents, contains( Event.flutterBuildInfo( label: 'plist-impeller-enabled', buildType: 'ios', ), )); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app') .createSync(recursive: true); }), setUpRsyncCommand(onRun: (_) => fileSystem.file('build/ios/iphoneos/Runner.app/Frameworks/App.framework/App') ..createSync(recursive: true) ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0))), ]), Platform: () => macosPlatform, FileSystemUtils: () => FileSystemUtils( fileSystem: fileSystem, platform: macosPlatform, ), Usage: () => usage, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), Analytics: () => fakeAnalytics, }); testUsingContext('Sends an analytics event when Impeller is disabled', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: BufferLogger.test(), osUtils: FakeOperatingSystemUtils(), processUtils: processUtils, ); createMinimalMockProjectFiles(); fileSystem.file( fileSystem.path.join('usr', 'bin', 'plutil'), ).createSync(recursive: true); final File infoPlist = fileSystem.file(fileSystem.path.join( 'ios', 'Runner', 'Info.plist', ))..createSync(recursive: true); infoPlist.writeAsStringSync(plistContents); await createTestCommandRunner(command).run( const <String>['build', 'ios', '--no-pub'] ); expect(usage.events, contains( const TestUsageEvent( 'build', 'ios', label:'plist-impeller-disabled', parameters:CustomDimensions(), ), )); expect(fakeAnalytics.sentEvents, contains( Event.flutterBuildInfo( label: 'plist-impeller-disabled', buildType: 'ios', ), )); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(onRun: (_) { fileSystem.directory('build/ios/Release-iphoneos/Runner.app') .createSync(recursive: true); }), setUpRsyncCommand(onRun: (_) => fileSystem.file('build/ios/iphoneos/Runner.app/Frameworks/App.framework/App') ..createSync(recursive: true) ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0))), ]), Platform: () => macosPlatform, FileSystemUtils: () => FileSystemUtils( fileSystem: fileSystem, platform: macosPlatform, ), Usage: () => usage, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), FlutterProjectFactory: () => FlutterProjectFactory( fileSystem: fileSystem, logger: BufferLogger.test(), ), PlistParser: () => PlistParser( fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.list(<FakeCommand>[ plutilCommand, plutilCommand, plutilCommand, ]), ), Analytics: () => fakeAnalytics, }); }); group('xcresults device', () { testUsingContext('Trace error if xcresult is empty.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), setUpXCResultCommand(), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.traceText, contains('xcresult parser: Unrecognized top level json format.')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Display xcresult issues on console if parsed, suppress Xcode output', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }, stdout: 'Lots of spew from Xcode', ), setUpXCResultCommand(stdout: kSampleResultJsonWithIssues), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains("Use of undeclared identifier 'asdas'")); expect(logger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56')); expect(logger.statusText, isNot(contains("Xcode's output"))); expect(logger.statusText, isNot(contains('Lots of spew from Xcode'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Do not display xcresult issues that needs to be discarded.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), setUpXCResultCommand(stdout: kSampleResultJsonWithIssuesToBeDiscarded), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains("Use of undeclared identifier 'asdas'")); expect(logger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56')); expect(logger.errorText, isNot(contains('Command PhaseScriptExecution failed with a nonzero exit code'))); expect(logger.warningText, isNot(contains('but the range of supported deployment target versions is'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Trace if xcresult bundle does not exist.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(exitCode: 1), setUpXCResultCommand(stdout: kSampleResultJsonWithIssues), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(testLogger.traceText, contains('The xcresult bundle are not generated. Displaying xcresult is disabled.')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Extra error message for provision profile issue in xcresult bundle.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), setUpXCResultCommand(stdout: kSampleResultJsonWithProvisionIssue), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains('Some Provisioning profile issue.')); expect(logger.errorText, contains('It appears that there was a problem signing your application prior to installation on the device.')); expect(logger.errorText, contains('Verify that the Bundle Identifier in your project is your signing id in Xcode')); expect(logger.errorText, contains('open ios/Runner.xcworkspace')); expect(logger.errorText, contains("Also try selecting 'Product > Build' to fix the problem.")); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Display xcresult issues with no provisioning profile.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); } ), setUpXCResultCommand(stdout: kSampleResultJsonWithNoProvisioningProfileIssue), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains('Runner requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor')); expect(logger.errorText, contains(noProvisioningProfileInstruction)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Extra error message for missing simulator platform in xcresult bundle.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler(exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }), setUpXCResultCommand(stdout: kSampleResultJsonWithActionIssues), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains(missingPlatformInstructions('iOS 17.0'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Delete xcresult bundle before each xcodebuild command.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, // Intentionally fail the first xcodebuild command with concurrent run failure message. setUpFakeXcodeBuildHandler( exitCode: 1, stdout: '$kConcurrentRunFailureMessage1 $kConcurrentRunFailureMessage2', onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).childFile('result.xcresult').createSync(recursive: true); } ), // The second xcodebuild is triggered due to above concurrent run failure message. setUpFakeXcodeBuildHandler( onRun: (_) { // If the file is not cleaned, throw an error, test failure. if (fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).existsSync()) { throwToolExit('xcresult bundle file existed.', exitCode: 2); } fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).childFile('result.xcresult').createSync(recursive: true); } ), setUpXCResultCommand(stdout: kSampleResultJsonNoIssues), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']); expect(logger.statusText, contains('Xcode build done.')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Failed to parse xcresult but display missing provisioning profile issue from stdout.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( exitCode: 1, stdout: ''' Runner requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor ''', onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); } ), setUpXCResultCommand(stdout: kSampleResultJsonInvalidIssuesMap), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains(noProvisioningProfileInstruction)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Failed to parse xcresult but detected no development team issue.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); } ), setUpXCResultCommand(stdout: kSampleResultJsonInvalidIssuesMap), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains(noDevelopmentTeamInstruction)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); testUsingContext('xcresult did not detect issue but detected by stdout.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(testLogger.errorText, contains(noProvisioningProfileInstruction)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.list(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( exitCode: 1, stdout: ''' Runner requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor ''', onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); } ), setUpXCResultCommand(stdout: kSampleResultJsonNoIssues), setUpRsyncCommand(), ]), EnvironmentType: () => EnvironmentType.physical, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('xcresult did not detect issue, no development team is detected from build setting.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); } ), setUpXCResultCommand(stdout: kSampleResultJsonInvalidIssuesMap), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(testLogger.errorText, contains(noDevelopmentTeamInstruction)); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); testUsingContext('No development team issue error message is not displayed if no provisioning profile issue is detected from xcresult first.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); } ), setUpXCResultCommand(stdout: kSampleResultJsonWithNoProvisioningProfileIssue), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains(noProvisioningProfileInstruction)); expect(logger.errorText, isNot(contains(noDevelopmentTeamInstruction))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); testUsingContext('General provisioning profile issue error message is not displayed if no development team issue is detected first.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); } ), setUpXCResultCommand(stdout: kSampleResultJsonWithProvisionIssue), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains(noDevelopmentTeamInstruction)); expect(logger.errorText, isNot(contains('It appears that there was a problem signing your application prior to installation on the device.'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(developmentTeam: null), }); }); group('xcresults simulator', () { testUsingContext('Trace error if xcresult is empty.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }, ), setUpXCResultCommand(), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator', '--no-pub']), throwsToolExit(), ); expect(logger.traceText, contains('xcresult parser: Unrecognized top level json format.')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Display xcresult issues on console if parsed.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }, ), setUpXCResultCommand(stdout: kSampleResultJsonWithIssues), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains("Use of undeclared identifier 'asdas'")); expect(logger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Do not display xcresult issues that needs to be discarded.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, onRun: (_) { fileSystem.systemTempDirectory.childDirectory(_xcBundleDirectoryPath).createSync(); }, ), setUpXCResultCommand(stdout: kSampleResultJsonWithIssuesToBeDiscarded), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator', '--no-pub']), throwsToolExit(), ); expect(logger.errorText, contains("Use of undeclared identifier 'asdas'")); expect(logger.errorText, contains('/Users/m/Projects/test_create/ios/Runner/AppDelegate.m:7:56')); expect(logger.errorText, isNot(contains('Command PhaseScriptExecution failed with a nonzero exit code'))); expect(logger.warningText, isNot(contains('but the range of supported deployment target versions is'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); testUsingContext('Trace if xcresult bundle does not exist.', () async { final BuildCommand command = BuildCommand( artifacts: artifacts, androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: fileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); processManager.addCommands(<FakeCommand>[ xattrCommand, setUpFakeXcodeBuildHandler( simulator: true, exitCode: 1, ), setUpXCResultCommand(stdout: kSampleResultJsonWithIssues), setUpRsyncCommand(), ]); createMinimalMockProjectFiles(); await expectLater( createTestCommandRunner(command).run(const <String>['build', 'ios', '--simulator', '--no-pub']), throwsToolExit(), ); expect(logger.traceText, contains('The xcresult bundle are not generated. Displaying xcresult is disabled.')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, Logger: () => logger, ProcessManager: () => processManager, Platform: () => macosPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreterWithBuildSettings(), }); }); } const String _xcBundleDirectoryPath = '/.tmp_rand0/flutter_ios_build_temp_dirrand0/temporary_xcresult_bundle'; class FakeAndroidSdk extends Fake implements AndroidSdk { @override late bool platformToolsAvailable; @override late bool licensesAvailable; @override AndroidSdkVersion? latestVersion; } class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils { FakeOperatingSystemUtils({this.hostPlatform = HostPlatform.linux_x64}); @override HostPlatform hostPlatform = HostPlatform.linux_x64; }
flutter/packages/flutter_tools/test/commands.shard/hermetic/build_ios_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/build_ios_test.dart", "repo_id": "flutter", "token_count": 20192 }
770
// Copyright 2014 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:file/memory.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/test/flutter_web_platform.dart'; import 'package:flutter_tools/src/web/chrome.dart'; import 'package:flutter_tools/src/web/compile.dart'; import 'package:flutter_tools/src/web/memory_fs.dart'; import 'package:shelf/shelf.dart' as shelf; import 'package:test/test.dart'; import '../../src/context.dart'; import '../../src/fakes.dart'; class MockServer implements shelf.Server { shelf.Handler? mountedHandler; @override Future<void> close() async {} @override void mount(shelf.Handler handler) { mountedHandler = handler; } @override Uri get url => Uri.parse(''); } void main() { late FileSystem fileSystem; late BufferLogger logger; late Platform platform; late Artifacts artifacts; late ProcessManager processManager; late FakeOperatingSystemUtils operatingSystemUtils; setUp(() { fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); platform = FakePlatform(); artifacts = Artifacts.test(fileSystem: fileSystem); processManager = FakeProcessManager.empty(); operatingSystemUtils = FakeOperatingSystemUtils(); for (final HostArtifact artifact in <HostArtifact>[ HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSoundSdk, HostArtifact.webPrecompiledAmdCanvaskitAndHtmlSdk, HostArtifact.webPrecompiledAmdCanvaskitSoundSdk, HostArtifact.webPrecompiledAmdCanvaskitSdk, HostArtifact.webPrecompiledAmdSoundSdk, HostArtifact.webPrecompiledAmdSdk, HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSoundSdk, HostArtifact.webPrecompiledDdcCanvaskitAndHtmlSdk, HostArtifact.webPrecompiledDdcCanvaskitSoundSdk, HostArtifact.webPrecompiledDdcCanvaskitSdk, HostArtifact.webPrecompiledDdcSoundSdk, HostArtifact.webPrecompiledDdcSdk, ]) { final File artifactFile = artifacts.getHostArtifact(artifact) as File; artifactFile.createSync(); artifactFile.writeAsStringSync(artifact.name); } }); testUsingContext( 'FlutterWebPlatform serves the correct dart_sdk.js (amd module system) for the passed web renderer', () async { final ChromiumLauncher chromiumLauncher = ChromiumLauncher( fileSystem: fileSystem, platform: platform, processManager: processManager, operatingSystemUtils: operatingSystemUtils, browserFinder: (Platform platform, FileSystem filesystem) => 'chrome', logger: logger, ); final MockServer server = MockServer(); fileSystem.directory('/test').createSync(); final FlutterWebPlatform webPlatform = await FlutterWebPlatform.start( 'ProjectRoot', buildInfo: const BuildInfo(BuildMode.debug, '', treeShakeIcons: false), webMemoryFS: WebMemoryFS(), fileSystem: fileSystem, logger: logger, chromiumLauncher: chromiumLauncher, artifacts: artifacts, processManager: processManager, webRenderer: WebRendererMode.canvaskit, serverFactory: () async => server, testPackageUri: Uri.parse('test'), ); final shelf.Handler? handler = server.mountedHandler; expect(handler, isNotNull); handler!; final shelf.Response response = await handler(shelf.Request( 'GET', Uri.parse('http://localhost/dart_sdk.js'), )); final String contents = await response.readAsString(); expect(contents, HostArtifact.webPrecompiledAmdCanvaskitSoundSdk.name); await webPlatform.close(); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Logger: () => logger, }); testUsingContext( 'FlutterWebPlatform serves the correct dart_sdk.js (ddc module system) for the passed web renderer', () async { final ChromiumLauncher chromiumLauncher = ChromiumLauncher( fileSystem: fileSystem, platform: platform, processManager: processManager, operatingSystemUtils: operatingSystemUtils, browserFinder: (Platform platform, FileSystem filesystem) => 'chrome', logger: logger, ); final MockServer server = MockServer(); fileSystem.directory('/test').createSync(); final FlutterWebPlatform webPlatform = await FlutterWebPlatform.start( 'ProjectRoot', buildInfo: const BuildInfo( BuildMode.debug, '', treeShakeIcons: false, extraFrontEndOptions: <String>['--dartdevc-module-format=ddc'], ), webMemoryFS: WebMemoryFS(), fileSystem: fileSystem, logger: logger, chromiumLauncher: chromiumLauncher, artifacts: artifacts, processManager: processManager, webRenderer: WebRendererMode.canvaskit, serverFactory: () async => server, testPackageUri: Uri.parse('test'), ); final shelf.Handler? handler = server.mountedHandler; expect(handler, isNotNull); handler!; final shelf.Response response = await handler(shelf.Request( 'GET', Uri.parse('http://localhost/dart_sdk.js'), )); final String contents = await response.readAsString(); expect(contents, HostArtifact.webPrecompiledDdcCanvaskitSoundSdk.name); await webPlatform.close(); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Logger: () => logger, }); }
flutter/packages/flutter_tools/test/commands.shard/hermetic/flutter_web_platform_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/flutter_web_platform_test.dart", "repo_id": "flutter", "token_count": 2061 }
771
// Copyright 2014 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:file/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/update_packages.dart'; import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:test/fake.dart'; import 'package:yaml/yaml.dart'; import '../../src/context.dart'; import '../../src/test_flutter_command_runner.dart'; // An example pubspec.yaml from flutter, not necessary for it to be up to date. const String kFlutterPubspecYaml = r''' name: flutter description: A framework for writing Flutter applications homepage: http://flutter.dev environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: # To update these, use "flutter update-packages --force-upgrade". collection: 1.14.11 meta: 1.1.8 typed_data: 1.1.6 vector_math: 2.0.8 sky_engine: sdk: flutter gallery: git: url: https://github.com/flutter/gallery.git ref: d00362e6bdd0f9b30bba337c358b9e4a6e4ca950 dev_dependencies: flutter_test: sdk: flutter flutter_goldens: sdk: flutter archive: 2.0.11 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" # PUBSPEC CHECKSUM: 1234 '''; // An example pubspec.yaml, not necessary for it to be up to date. const String kExamplesPubspecYaml = r''' name: examples description: Examples for flutter homepage: http://flutter.dev version: 1.0.0 environment: sdk: '>=3.2.0-0 <4.0.0' flutter: ">=2.5.0-6.0.pre.30 <3.0.0" dependencies: cupertino_icons: 1.0.4 flutter: sdk: flutter archive: 2.0.11 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" # PUBSPEC CHECKSUM: 6543 '''; const String kVersionJson = ''' { "frameworkVersion": "1.2.3", "channel": "[user-branch]", "repositoryUrl": "[email protected]:flutter/flutter.git", "frameworkRevision": "1234567812345678123456781234567812345678", "frameworkCommitDate": "2024-02-06 22:26:52 +0100", "engineRevision": "abcdef01abcdef01abcdef01abcdef01abcdef01", "dartSdkVersion": "1.2.3", "devToolsVersion": "1.2.3", "flutterVersion": "1.2.3" } '''; void main() { group('update-packages', () { late FileSystem fileSystem; late Directory flutterSdk; late Directory flutter; late FakePub pub; late FakeProcessManager processManager; late BufferLogger logger; setUpAll(() { Cache.disableLocking(); logger = BufferLogger.test(); }); setUp(() { fileSystem = MemoryFileSystem.test(); flutterSdk = fileSystem.directory('flutter')..createSync(); flutterSdk.childFile('version').writeAsStringSync('1.2.3'); flutterSdk.childDirectory('bin').childDirectory('cache').childFile('flutter.version.json') ..createSync(recursive: true) ..writeAsStringSync(kVersionJson); flutter = flutterSdk.childDirectory('packages').childDirectory('flutter') ..createSync(recursive: true); flutterSdk.childDirectory('dev').createSync(recursive: true); flutterSdk.childDirectory('examples').childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(kExamplesPubspecYaml); flutter.childFile('pubspec.yaml').writeAsStringSync(kFlutterPubspecYaml); Cache.flutterRoot = flutterSdk.absolute.path; pub = FakePub(fileSystem); processManager = FakeProcessManager.empty(); }); testUsingContext('updates packages', () async { final UpdatePackagesCommand command = UpdatePackagesCommand(); await createTestCommandRunner(command).run(<String>['update-packages']); expect(pub.pubGetDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', '/flutter/examples', '/flutter/packages/flutter', ])); expect(pub.pubBatchDirectories, isEmpty); }, overrides: <Type, Generator>{ Pub: () => pub, FileSystem: () => fileSystem, ProcessManager: () => processManager, Cache: () => Cache.test( processManager: processManager, ), }); testUsingContext('force updates packages', () async { final UpdatePackagesCommand command = UpdatePackagesCommand(); await createTestCommandRunner(command).run(<String>[ 'update-packages', '--force-upgrade', ]); expect(pub.pubGetDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', '/flutter/examples', '/flutter/packages/flutter', ])); expect(pub.pubBatchDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', ])); }, overrides: <Type, Generator>{ Pub: () => pub, FileSystem: () => fileSystem, ProcessManager: () => processManager, Cache: () => Cache.test( processManager: processManager, ), }); testUsingContext('force updates packages --jobs=1', () async { final UpdatePackagesCommand command = UpdatePackagesCommand(); await createTestCommandRunner(command).run(<String>[ 'update-packages', '--force-upgrade', '--jobs=1', ]); expect(pub.pubGetDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', '/flutter/examples', '/flutter/packages/flutter', ])); expect(pub.pubBatchDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', ])); }, overrides: <Type, Generator>{ Pub: () => pub, FileSystem: () => fileSystem, ProcessManager: () => processManager, Cache: () => Cache.test( processManager: processManager, ), }); testUsingContext('--transitive-closure --consumer-only', () async { final UpdatePackagesCommand command = UpdatePackagesCommand(); await createTestCommandRunner(command).run(<String>[ 'update-packages', '--transitive-closure', '--consumer-only', ]); expect(pub.pubGetDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', ])); expect(pub.pubBatchDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', ])); // Expecting a line like: // 'flutter -> {collection, meta, typed_data, vector_math}' expect( logger.statusText, contains(RegExp(r'flutter -> {([a-z_]+, )*([a-z_]+)+}')), ); }, overrides: <Type, Generator>{ Pub: () => pub, FileSystem: () => fileSystem, ProcessManager: () => processManager, Cache: () => Cache.test( processManager: processManager, ), Logger: () => logger, }); testUsingContext('--cherry-pick-package', () async { final UpdatePackagesCommand command = UpdatePackagesCommand(); await createTestCommandRunner(command).run(<String>[ 'update-packages', '--cherry-pick-package=vector_math', '--cherry-pick-version=2.0.9', ]); expect(pub.pubGetDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', '/flutter/examples', '/flutter/packages/flutter', ])); expect(pub.pubBatchDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', ])); expect(pub.pubspecYamls, hasLength(3)); final String output = pub.pubspecYamls.first; expect(output, isNotNull); expect(output, contains('collection: 1.14.11\n')); expect(output, contains('meta: 1.1.8\n')); expect(output, contains('typed_data: 1.1.6\n')); expect(output, contains('vector_math: 2.0.9\n')); expect(output, isNot(contains('vector_math: 2.0.8'))); expect(output, isNot(contains('vector_math: ">= 2.0.8"'))); expect(output, isNot(contains("vector_math: '>= 2.0.8'"))); }, overrides: <Type, Generator>{ Pub: () => pub, FileSystem: () => fileSystem, ProcessManager: () => processManager, Cache: () => Cache.test( processManager: processManager, ), Logger: () => logger, }); testUsingContext('--force-upgrade', () async { final UpdatePackagesCommand command = UpdatePackagesCommand(); await createTestCommandRunner(command).run(<String>[ 'update-packages', '--force-upgrade', ]); expect(pub.pubGetDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', '/flutter/examples', '/flutter/packages/flutter', ])); expect(pub.pubBatchDirectories, equals(<String>[ '/.tmp_rand0/flutter_update_packages.rand0/synthetic_package', ])); expect(pub.pubspecYamls, hasLength(3)); final String output = pub.pubspecYamls.first; expect(output, isNotNull); expect(output, contains("collection: '>= 1.14.11'\n")); expect(output, contains("meta: '>= 1.1.8'\n")); expect(output, contains("typed_data: '>= 1.1.6'\n")); expect(output, contains("vector_math: '>= 2.0.8'\n")); expect(output, isNot(contains('vector_math: 2.0.8'))); }, overrides: <Type, Generator>{ Pub: () => pub, FileSystem: () => fileSystem, ProcessManager: () => processManager, Cache: () => Cache.test( processManager: processManager, ), Logger: () => logger, }); testUsingContext('force updates packages --synthetic-package-path', () async { final UpdatePackagesCommand command = UpdatePackagesCommand(); const String dir = '/path/to/synthetic/package'; await createTestCommandRunner(command).run(<String>[ 'update-packages', '--force-upgrade', '--synthetic-package-path=$dir', ]); expect(pub.pubGetDirectories, equals(<String>[ '$dir/synthetic_package', '/flutter/examples', '/flutter/packages/flutter', ])); expect(pub.pubBatchDirectories, equals(<String>[ '$dir/synthetic_package', ])); }, overrides: <Type, Generator>{ Pub: () => pub, FileSystem: () => fileSystem, ProcessManager: () => processManager, Cache: () => Cache.test( processManager: processManager, ), }); }); group('generateFakePubspec', () { const String prevVersion = '1.2.0'; testUsingContext('constrains package versions to >= previous version if doUpgrade: true', () { final String pubspecSource = generateFakePubspec( <PubspecDependency>[ PubspecDependency( ' foo: $prevVersion', 'foo', '', version: prevVersion, sourcePath: '/path/to/pubspec.yaml', kind: DependencyKind.normal, isTransitive: false, isDevDependency: false, ), ], doUpgrade: true, ); final YamlMap pubspec = loadYaml(pubspecSource) as YamlMap; expect((pubspec['dependencies'] as YamlMap)['foo'], '>= $prevVersion'); }); testUsingContext('uses previous package versions doUpgrade: false', () { final String pubspecSource = generateFakePubspec( <PubspecDependency>[ PubspecDependency( ' foo: $prevVersion', 'foo', '', version: prevVersion, sourcePath: '/path/to/pubspec.yaml', kind: DependencyKind.normal, isTransitive: false, isDevDependency: false, ), ], ); final YamlMap pubspec = loadYaml(pubspecSource) as YamlMap; expect((pubspec['dependencies'] as YamlMap)['foo'], prevVersion); }); }); } class FakePub extends Fake implements Pub { FakePub(this.fileSystem); final FileSystem fileSystem; final List<String> pubGetDirectories = <String>[]; final List<String> pubBatchDirectories = <String>[]; final List<String> pubspecYamls = <String>[]; @override Future<void> get({ required PubContext context, required FlutterProject project, bool upgrade = false, bool offline = false, bool generateSyntheticPackage = false, bool generateSyntheticPackageForExample = false, String? flutterRootOverride, bool checkUpToDate = false, bool shouldSkipThirdPartyGenerator = true, PubOutputMode outputMode = PubOutputMode.all, }) async { pubGetDirectories.add(project.directory.path); pubspecYamls.add(project.directory.childFile('pubspec.yaml').readAsStringSync()); project.directory.childFile('pubspec.lock') ..createSync(recursive: true) ..writeAsStringSync(''' # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: async: dependency: "direct dev" description: name: async url: "https://pub.dartlang.org" source: hosted version: "2.8.2" sdks: dart: ">=2.14.0 <3.0.0" '''); fileSystem.currentDirectory .childDirectory('.dart_tool') .childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync('{"configVersion":2,"packages":[]}'); } @override Future<void> batch( List<String> arguments, { required PubContext context, String? directory, MessageFilter? filter, String failureMessage = 'pub failed', }) async { if (directory != null) { pubBatchDirectories.add(directory); } ''' Dart SDK 2.16.0-144.0.dev Flutter SDK 2.9.0-1.0.pre.263 flutter_api_samples 1.0.0 dependencies: - cupertino_icons 1.0.4 - collection 1.15.0 - meta 1.7.0 - typed_data 1.3.0 [collection] - vector_math 2.1.1 dev dependencies: transitive dependencies: - platform 3.1.0 - process 4.2.4 [file path platform] '''.split('\n').forEach(filter!); } }
flutter/packages/flutter_tools/test/commands.shard/hermetic/update_packages_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/update_packages_test.dart", "repo_id": "flutter", "token_count": 5780 }
772
// Copyright 2014 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/memory.dart'; import 'package:flutter_tools/src/android/android_studio.dart'; import 'package:flutter_tools/src/android/android_workflow.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/config.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/process.dart'; import 'package:flutter_tools/src/base/time.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/build.dart'; import 'package:flutter_tools/src/commands/config.dart'; import 'package:flutter_tools/src/commands/doctor.dart'; import 'package:flutter_tools/src/doctor.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/runner/flutter_command.dart'; import 'package:flutter_tools/src/version.dart'; import 'package:test/fake.dart'; import 'package:usage/usage_io.dart'; import '../src/common.dart'; import '../src/context.dart'; import '../src/fakes.dart'; import '../src/test_build_system.dart'; import '../src/test_flutter_command_runner.dart'; void main() { setUpAll(() { Cache.disableLocking(); }); group('analytics', () { late Directory tempDir; late Config testConfig; late FileSystem fs; const String flutterRoot = '/path/to/flutter'; setUp(() { Cache.flutterRoot = flutterRoot; tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_analytics_test.'); testConfig = Config.test(); fs = MemoryFileSystem.test(); }); tearDown(() { tryToDelete(tempDir); }); // Ensure we don't send anything when analytics is disabled. testUsingContext("doesn't send when disabled", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++); final FlutterCommand command = FakeFlutterCommand(); final CommandRunner<void>runner = createTestCommandRunner(command); globals.flutterUsage.enabled = false; await runner.run(<String>['fake']); expect(count, 0); globals.flutterUsage.enabled = true; await runner.run(<String>['fake']); // LogToFileAnalytics isFirstRun is hardcoded to false // so this usage will never act like the first run // (which would not send usage). expect(count, 4); count = 0; globals.flutterUsage.enabled = false; await runner.run(<String>['fake']); expect(count, 0); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Usage: () => Usage( configDirOverride: tempDir.path, logFile: tempDir.childFile('analytics.log').path, runningOnBot: true, ), }); // Ensure we don't send for the 'flutter config' command. testUsingContext("config doesn't send", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++); globals.flutterUsage.enabled = false; final ConfigCommand command = ConfigCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['config']); expect(count, 0); globals.flutterUsage.enabled = true; await runner.run(<String>['config']); expect(count, 0); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Usage: () => Usage( configDirOverride: tempDir.path, logFile: tempDir.childFile('analytics.log').path, runningOnBot: true, ), }); testUsingContext('Usage records one feature in experiment setting', () async { testConfig.setValue(flutterWebFeature.configSetting!, true); final Usage usage = Usage(runningOnBot: true); usage.sendCommand('test'); final String featuresKey = CustomDimensionsEnum.enabledFlutterFeatures.cdKey; expect(globals.fs.file('test').readAsStringSync(), contains('$featuresKey: enable-web')); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Config: () => testConfig, Platform: () => FakePlatform(environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'test', }), FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), }); testUsingContext('Usage records multiple features in experiment setting', () async { testConfig.setValue(flutterWebFeature.configSetting!, true); testConfig.setValue(flutterLinuxDesktopFeature.configSetting!, true); testConfig.setValue(flutterMacOSDesktopFeature.configSetting!, true); final Usage usage = Usage(runningOnBot: true); usage.sendCommand('test'); final String featuresKey = CustomDimensionsEnum.enabledFlutterFeatures.cdKey; expect( globals.fs.file('test').readAsStringSync(), contains('$featuresKey: enable-web,enable-linux-desktop,enable-macos-desktop'), ); }, overrides: <Type, Generator>{ FlutterVersion: () => FakeFlutterVersion(), Config: () => testConfig, Platform: () => FakePlatform(environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'test', }), FileSystem: () => fs, ProcessManager: () => FakeProcessManager.any(), }); }); group('analytics with fakes', () { late MemoryFileSystem memoryFileSystem; late FakeStdio fakeStdio; late TestUsage testUsage; late FakeClock fakeClock; late FakeDoctor doctor; late FakeAndroidStudio androidStudio; late ProcessManager processManager; late BufferLogger logger; late ProcessUtils processUtils; setUp(() { memoryFileSystem = MemoryFileSystem.test(); fakeStdio = FakeStdio(); testUsage = TestUsage(); fakeClock = FakeClock(); doctor = FakeDoctor(); androidStudio = FakeAndroidStudio(); processManager = FakeProcessManager.empty(); logger = BufferLogger.test(); processUtils = ProcessUtils(logger: logger, processManager: processManager); }); testUsingContext('flutter commands send timing events', () async { fakeClock.times = <int>[1000, 2000]; doctor.diagnoseSucceeds = true; final DoctorCommand command = DoctorCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['doctor']); expect(testUsage.timings, contains( const TestTimingEvent( 'flutter', 'doctor', Duration(milliseconds: 1000), label: 'success', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => androidStudio, SystemClock: () => fakeClock, Doctor: () => doctor, Usage: () => testUsage, }); testUsingContext('doctor fail sends warning', () async { fakeClock.times = <int>[1000, 2000]; doctor.diagnoseSucceeds = false; final DoctorCommand command = DoctorCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['doctor']); expect(testUsage.timings, contains( const TestTimingEvent( 'flutter', 'doctor', Duration(milliseconds: 1000), label: 'warning', ), )); }, overrides: <Type, Generator>{ AndroidStudio: () => androidStudio, SystemClock: () => fakeClock, Doctor: () => doctor, Usage: () => testUsage, }); testUsingContext('single command usage path', () async { final FlutterCommand doctorCommand = DoctorCommand(); expect(await doctorCommand.usagePath, 'doctor'); }, overrides: <Type, Generator>{ Usage: () => testUsage, }); testUsingContext('compound command usage path', () async { final BuildCommand buildCommand = BuildCommand( artifacts: Artifacts.test(fileSystem: memoryFileSystem), androidSdk: FakeAndroidSdk(), buildSystem: TestBuildSystem.all(BuildResult(success: true)), fileSystem: memoryFileSystem, logger: logger, processUtils: processUtils, osUtils: FakeOperatingSystemUtils(), ); final FlutterCommand buildApkCommand = buildCommand.subcommands['apk']! as FlutterCommand; expect(await buildApkCommand.usagePath, 'build/apk'); }); testUsingContext('command sends localtime', () async { const int kMillis = 1000; fakeClock.times = <int>[kMillis]; // Since FLUTTER_ANALYTICS_LOG_FILE is set in the environment, analytics // will be written to a file. final Usage usage = Usage( versionOverride: 'test', runningOnBot: true, ); usage.suppressAnalytics = false; usage.enabled = true; usage.sendCommand('test'); final String log = globals.fs.file('analytics.log').readAsStringSync(); final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(kMillis); expect(log.contains(formatDateTime(dateTime)), isTrue); }, overrides: <Type, Generator>{ FileSystem: () => memoryFileSystem, ProcessManager: () => processManager, SystemClock: () => fakeClock, Platform: () => FakePlatform( environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'analytics.log', }, ), Stdio: () => fakeStdio, }); testUsingContext('event sends localtime', () async { const int kMillis = 1000; fakeClock.times = <int>[kMillis]; // Since FLUTTER_ANALYTICS_LOG_FILE is set in the environment, analytics // will be written to a file. final Usage usage = Usage( versionOverride: 'test', runningOnBot: true, ); usage.suppressAnalytics = false; usage.enabled = true; usage.sendEvent('test', 'test'); final String log = globals.fs.file('analytics.log').readAsStringSync(); final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(kMillis); expect(log.contains(formatDateTime(dateTime)), isTrue); }, overrides: <Type, Generator>{ FileSystem: () => memoryFileSystem, ProcessManager: () => processManager, SystemClock: () => fakeClock, Platform: () => FakePlatform( environment: <String, String>{ 'FLUTTER_ANALYTICS_LOG_FILE': 'analytics.log', }, ), Stdio: () => fakeStdio, }); }); group('analytics bots', () { late Directory tempDir; setUp(() { tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_analytics_bots_test.'); }); tearDown(() { tryToDelete(tempDir); }); testUsingContext("don't send on bots with unknown version", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++); await createTestCommandRunner().run(<String>['--version']); expect(count, 0); }, overrides: <Type, Generator>{ Usage: () => Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/unknown', configDirOverride: tempDir.path, runningOnBot: false, ), }); testUsingContext("don't send on bots even when opted in", () async { int count = 0; globals.flutterUsage.onSend.listen((Map<String, dynamic> data) => count++); globals.flutterUsage.enabled = true; await createTestCommandRunner().run(<String>['--version']); expect(count, 0); }, overrides: <Type, Generator>{ Usage: () => Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/unknown', configDirOverride: tempDir.path, runningOnBot: false, ), }); testUsingContext('Uses AnalyticsMock when .flutter cannot be created', () async { final Usage usage = Usage( settingsName: 'flutter_bot_test', versionOverride: 'dev/known', configDirOverride: tempDir.path, analyticsIOFactory: throwingAnalyticsIOFactory, runningOnBot: false, ); final AnalyticsMock analyticsMock = AnalyticsMock(); expect(usage.clientId, analyticsMock.clientId); expect(usage.suppressAnalytics, isTrue); }); }); } Analytics throwingAnalyticsIOFactory( String trackingId, String applicationName, String applicationVersion, { String? analyticsUrl, Directory? documentDirectory, }) { throw const FileSystemException('Could not create file'); } class FakeFlutterCommand extends FlutterCommand { @override String get description => 'A fake command'; @override String get name => 'fake'; @override Future<FlutterCommandResult> runCommand() async { return FlutterCommandResult.success(); } } class FakeDoctor extends Fake implements Doctor { bool diagnoseSucceeds = false; @override Future<bool> diagnose({ bool androidLicenses = false, bool verbose = true, bool showColor = true, AndroidLicenseValidator? androidLicenseValidator, bool showPii = true, List<ValidatorTask>? startedValidatorTasks, bool sendEvent = true, FlutterVersion? version, }) async { return diagnoseSucceeds; } } class FakeClock extends Fake implements SystemClock { List<int> times = <int>[]; @override DateTime now() { return DateTime.fromMillisecondsSinceEpoch(times.removeAt(0)); } }
flutter/packages/flutter_tools/test/general.shard/analytics_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/analytics_test.dart", "repo_id": "flutter", "token_count": 5101 }
773
// Copyright 2014 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/memory.dart'; import 'package:flutter_tools/src/android/deferred_components_prebuild_validator.dart'; import 'package:flutter_tools/src/android/deferred_components_validator.dart'; import 'package:flutter_tools/src/base/deferred_component.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import '../../src/common.dart'; import '../../src/context.dart'; void main() { late FileSystem fileSystem; late BufferLogger logger; late Directory projectDir; late Platform platform; late Directory flutterRootDir; setUp(() { fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); projectDir = fileSystem.directory('/project'); flutterRootDir = fileSystem.directory('/flutter_root'); platform = FakePlatform(); }); testWithoutContext('No checks passes', () async { final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( projectDir, logger, platform, exitOnFail: false, title: 'test check', ); validator.displayResults(); validator.attemptToolExit(); expect(logger.statusText, 'test check passed.\n'); }); testWithoutContext('clearTempDir passes', () async { final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( projectDir, logger, platform, exitOnFail: false, title: 'test check', ); validator.displayResults(); validator.attemptToolExit(); expect(logger.statusText, 'test check passed.\n'); }); testUsingContext('androidComponentSetup build.gradle does not exist', () async { final Directory templatesDir = flutterRootDir.childDirectory('templates'); final Directory deferredComponentDir = templatesDir.childDirectory('module').childDirectory('android').childDirectory('deferred_component'); final File buildGradleTemplate = deferredComponentDir.childFile('build.gradle.tmpl'); final File androidManifestTemplate = deferredComponentDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml.tmpl'); deferredComponentDir.createSync(recursive: true); buildGradleTemplate.createSync(recursive: true); androidManifestTemplate.createSync(recursive: true); buildGradleTemplate.writeAsStringSync('fake build.gradle template {{componentName}}', flush: true, mode: FileMode.append); androidManifestTemplate.writeAsStringSync('fake AndroidManifest.xml template {{componentName}}', flush: true, mode: FileMode.append); final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( projectDir, logger, platform, exitOnFail: false, title: 'test check', templatesDir: templatesDir, ); final Directory componentDir = projectDir.childDirectory('android').childDirectory('component1'); final File file = componentDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml'); if (file.existsSync()) { file.deleteSync(); } file.createSync(recursive: true); await validator.checkAndroidDynamicFeature( <DeferredComponent>[ DeferredComponent(name: 'component1'), ], ); validator.displayResults(); validator.attemptToolExit(); file.deleteSync(); expect(logger.statusText.contains('Newly generated android files:\n'), true); expect(logger.statusText.contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/component1/build.gradle\n'), true); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), }); testUsingContext('androidComponentSetup AndroidManifest.xml does not exist', () async { final Directory templatesDir = flutterRootDir.childDirectory('templates'); final Directory deferredComponentDir = templatesDir.childDirectory('module').childDirectory('android').childDirectory('deferred_component'); final File buildGradleTemplate = deferredComponentDir.childFile('build.gradle.tmpl'); final File androidManifestTemplate = deferredComponentDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml.tmpl'); deferredComponentDir.createSync(recursive: true); buildGradleTemplate.createSync(recursive: true); androidManifestTemplate.createSync(recursive: true); buildGradleTemplate.writeAsStringSync('fake build.gradle template {{componentName}}', flush: true, mode: FileMode.append); androidManifestTemplate.writeAsStringSync('fake AndroidManifest.xml template {{componentName}}', flush: true, mode: FileMode.append); final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( projectDir, logger, platform, exitOnFail: false, title: 'test check', templatesDir: templatesDir, ); final Directory componentDir = projectDir.childDirectory('android').childDirectory('component1'); final File file = componentDir.childFile('build.gradle'); if (file.existsSync()) { file.deleteSync(); } file.createSync(recursive: true); await validator.checkAndroidDynamicFeature( <DeferredComponent>[ DeferredComponent(name: 'component1'), ], ); validator.displayResults(); validator.attemptToolExit(); file.deleteSync(); expect(logger.statusText.contains('Newly generated android files:\n'), true); expect(logger.statusText.contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/component1/src/main/AndroidManifest.xml\n'), true); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), }); testWithoutContext('androidComponentSetup all files exist passes', () async { final Directory templatesDir = flutterRootDir.childDirectory('templates').childDirectory('deferred_component'); final File buildGradleTemplate = templatesDir.childFile('build.gradle.tmpl'); final File androidManifestTemplate = templatesDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml.tmpl'); if (templatesDir.existsSync()) { templatesDir.deleteSync(recursive: true); } buildGradleTemplate.createSync(recursive: true); androidManifestTemplate.createSync(recursive: true); buildGradleTemplate.writeAsStringSync('fake build.gradle template {{componentName}}', flush: true, mode: FileMode.append); androidManifestTemplate.writeAsStringSync('fake AndroidManifest.xml template {{componentName}}', flush: true, mode: FileMode.append); final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( projectDir, logger, platform, exitOnFail: false, title: 'test check', templatesDir: templatesDir, ); final Directory componentDir = projectDir.childDirectory('android').childDirectory('component1'); final File buildGradle = componentDir.childFile('build.gradle'); if (buildGradle.existsSync()) { buildGradle.deleteSync(); } buildGradle.createSync(recursive: true); final File manifest = componentDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml'); if (manifest.existsSync()) { manifest.deleteSync(); } manifest.createSync(recursive: true); await validator.checkAndroidDynamicFeature( <DeferredComponent>[ DeferredComponent(name: 'component1'), ], ); validator.displayResults(); validator.attemptToolExit(); manifest.deleteSync(); buildGradle.deleteSync(); expect(logger.statusText, 'test check passed.\n'); }); testWithoutContext('androidStringMapping creates new file', () async { final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( projectDir, logger, platform, exitOnFail: false, title: 'test check', ); final Directory baseModuleDir = projectDir.childDirectory('android').childDirectory('app'); final File stringRes = baseModuleDir.childDirectory('src').childDirectory('main').childDirectory('res').childDirectory('values').childFile('strings.xml'); if (stringRes.existsSync()) { stringRes.deleteSync(); } final File manifest = baseModuleDir.childDirectory('src').childDirectory('main').childFile('AndroidManifest.xml'); if (manifest.existsSync()) { manifest.deleteSync(); } manifest.createSync(recursive: true); manifest.writeAsStringSync(''' <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.splitaot"> <application android:name="io.flutter.app.FlutterPlayStoreSplitApplication" android:label="splitaot" android:extractNativeLibs="false"> <activity android:name=".MainActivity" android:launchMode="singleTop" android:windowSoftInputMode="adjustResize"> </activity> <!-- Don't delete the meta-data below. This is used by the Flutter tool to generate GeneratedPluginRegistrant.java --> <meta-data android:name="flutterEmbedding" android:value="2" /> <meta-data android:name="io.flutter.embedding.engine.deferredcomponents.DeferredComponentManager.loadingUnitMapping" android:value="invalidmapping" /> </application> </manifest> ''', flush: true, mode: FileMode.append); validator.checkAndroidResourcesStrings( <DeferredComponent>[ DeferredComponent(name: 'component1', libraries: <String>['lib2']), DeferredComponent(name: 'component2', libraries: <String>['lib1', 'lib4']), ], ); validator.displayResults(); validator.attemptToolExit(); expect(logger.statusText.contains('Modified android files:\n'), false); expect(logger.statusText.contains('Newly generated android files:\n'), true); expect(logger.statusText.contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/res/values/strings.xml\n'), true); final File stringsOutput = projectDir .childDirectory('build') .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) .childDirectory('app') .childDirectory('src') .childDirectory('main') .childDirectory('res') .childDirectory('values') .childFile('strings.xml'); expect(stringsOutput.existsSync(), true); expect(stringsOutput.readAsStringSync().contains('<string name="component1Name">component1</string>'), true); expect(stringsOutput.readAsStringSync().contains('<string name="component2Name">component2</string>'), true); }); testWithoutContext('androidStringMapping modifies strings file', () async { final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( projectDir, logger, platform, exitOnFail: false, title: 'test check', ); final Directory baseModuleDir = projectDir.childDirectory('android').childDirectory('app'); final File stringRes = baseModuleDir.childDirectory('src').childDirectory('main').childDirectory('res').childDirectory('values').childFile('strings.xml'); if (stringRes.existsSync()) { stringRes.deleteSync(); } stringRes.createSync(recursive: true); stringRes.writeAsStringSync(''' <?xml version="1.0" encoding="utf-8"?> <resources> <string name="component1Name">component1</string> </resources> ''', flush: true, mode: FileMode.append); validator.checkAndroidResourcesStrings( <DeferredComponent>[ DeferredComponent(name: 'component1', libraries: <String>['lib2']), DeferredComponent(name: 'component2', libraries: <String>['lib1', 'lib4']), ], ); validator.displayResults(); validator.attemptToolExit(); expect(logger.statusText.contains('Newly generated android files:\n'), false); expect(logger.statusText.contains('Modified android files:\n'), true); expect(logger.statusText.contains('build/${DeferredComponentsValidator.kDeferredComponentsTempDirectory}/app/src/main/res/values/strings.xml\n'), true); final File stringsOutput = projectDir .childDirectory('build') .childDirectory(DeferredComponentsValidator.kDeferredComponentsTempDirectory) .childDirectory('app') .childDirectory('src') .childDirectory('main') .childDirectory('res') .childDirectory('values') .childFile('strings.xml'); expect(stringsOutput.existsSync(), true); expect(stringsOutput.readAsStringSync().contains('<string name="component1Name">component1</string>'), true); expect(stringsOutput.readAsStringSync().contains('<string name="component2Name">component2</string>'), true); }); }
flutter/packages/flutter_tools/test/general.shard/android/deferred_components_prebuild_validator_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/android/deferred_components_prebuild_validator_test.dart", "repo_id": "flutter", "token_count": 4320 }
774
// Copyright 2014 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:typed_data'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/asset.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/user_messages.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:standard_message_codec/standard_message_codec.dart'; import '../src/common.dart'; void main() { Future<Map<String, List<String>>> extractAssetManifestJsonFromBundle(ManifestAssetBundle bundle) async { final String manifestJson = utf8.decode(await bundle.entries['AssetManifest.json']!.contentsAsBytes()); final Map<String, dynamic> parsedJson = json.decode(manifestJson) as Map<String, dynamic>; final Iterable<String> keys = parsedJson.keys; final Map<String, List<String>> parsedManifest = <String, List<String>> { for (final String key in keys) key: List<String>.from(parsedJson[key] as List<dynamic>), }; return parsedManifest; } Future<Map<Object?, Object?>> extractAssetManifestSmcBinFromBundle(ManifestAssetBundle bundle) async { final List<int> manifest = await bundle.entries['AssetManifest.bin']!.contentsAsBytes(); final ByteData asByteData = ByteData.view(Uint8List.fromList(manifest).buffer); final Map<Object?, Object?> decoded = const StandardMessageCodec().decodeMessage(asByteData)! as Map<Object?, Object?>; return decoded; } group('AssetBundle asset variants (with Unix-style paths)', () { late Platform platform; late FileSystem fs; late String flutterRoot; setUp(() { platform = FakePlatform(); fs = MemoryFileSystem.test(); flutterRoot = Cache.defaultFlutterRoot( platform: platform, fileSystem: fs, userMessages: UserMessages(), ); fs.file('.packages').createSync(); }); void createPubspec({ required List<String> assets, }) { fs.file('pubspec.yaml').writeAsStringSync( ''' name: test dependencies: flutter: sdk: flutter flutter: assets: ${assets.map((String entry) => ' - $entry').join('\n')} ''' ); } testWithoutContext('Only images in folders named with device pixel ratios (e.g. 2x, 3.0x) should be considered as variants of other images', () async { createPubspec(assets: <String>['assets/', 'assets/notAVariant/']); const String image = 'assets/image.jpg'; const String image2xVariant = 'assets/2x/image.jpg'; const String imageNonVariant = 'assets/notAVariant/image.jpg'; final List<String> assets = <String>[ image, image2xVariant, imageNonVariant ]; for (final String asset in assets) { final File assetFile = fs.file(asset); assetFile.createSync(recursive: true); assetFile.writeAsStringSync(asset); } final ManifestAssetBundle bundle = ManifestAssetBundle( logger: BufferLogger.test(), fileSystem: fs, platform: platform, flutterRoot: flutterRoot, ); await bundle.build( packagesPath: '.packages', flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory), ); final Map<String, List<String>> jsonManifest = await extractAssetManifestJsonFromBundle(bundle); final Map<Object?, Object?> smcBinManifest = await extractAssetManifestSmcBinFromBundle(bundle); final Map<String, List<Map<String, Object>>> expectedAssetManifest = <String, List<Map<String, Object>>>{ image: <Map<String, Object>>[ <String, String>{ 'asset': image, }, <String, Object>{ 'asset': image2xVariant, 'dpr': 2.0, } ], imageNonVariant: <Map<String, String>>[ <String, String>{ 'asset': imageNonVariant, } ], }; expect(smcBinManifest, equals(expectedAssetManifest)); expect(jsonManifest, equals(_assetManifestBinToJson(expectedAssetManifest))); }); testWithoutContext('Asset directories have their subdirectories searched for asset variants', () async { createPubspec(assets: <String>['assets/', 'assets/folder/']); const String topLevelImage = 'assets/image.jpg'; const String secondLevelImage = 'assets/folder/secondLevel.jpg'; const String secondLevel2xVariant = 'assets/folder/2x/secondLevel.jpg'; final List<String> assets = <String>[ topLevelImage, secondLevelImage, secondLevel2xVariant ]; for (final String asset in assets) { final File assetFile = fs.file(asset); assetFile.createSync(recursive: true); assetFile.writeAsStringSync(asset); } final ManifestAssetBundle bundle = ManifestAssetBundle( logger: BufferLogger.test(), fileSystem: fs, flutterRoot: flutterRoot, platform: platform, ); await bundle.build( packagesPath: '.packages', flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory), ); final Map<String, List<String>> jsonManifest = await extractAssetManifestJsonFromBundle(bundle); expect(jsonManifest, hasLength(2)); expect(jsonManifest[topLevelImage], equals(<String>[topLevelImage])); expect(jsonManifest[secondLevelImage], equals(<String>[secondLevelImage, secondLevel2xVariant])); final Map<Object?, Object?> smcBinManifest = await extractAssetManifestSmcBinFromBundle(bundle); final Map<String, List<Map<String, Object>>> expectedAssetManifest = <String, List<Map<String, Object>>>{ topLevelImage: <Map<String, Object>>[ <String, String>{ 'asset': topLevelImage, }, ], secondLevelImage: <Map<String, Object>>[ <String, String>{ 'asset': secondLevelImage, }, <String, Object>{ 'asset': secondLevel2xVariant, 'dpr': 2.0, }, ], }; expect(jsonManifest, equals(_assetManifestBinToJson(expectedAssetManifest))); expect(smcBinManifest, equals(expectedAssetManifest)); }); testWithoutContext('Asset paths should never be URI-encoded', () async { createPubspec(assets: <String>['assets/normalFolder/']); const String image = 'assets/normalFolder/i have URI-reserved_characters.jpg'; const String imageVariant = 'assets/normalFolder/3x/i have URI-reserved_characters.jpg'; final List<String> assets = <String>[ image, imageVariant ]; for (final String asset in assets) { final File assetFile = fs.file(asset); assetFile.createSync(recursive: true); assetFile.writeAsStringSync(asset); } final ManifestAssetBundle bundle = ManifestAssetBundle( logger: BufferLogger.test(), fileSystem: fs, platform: platform, flutterRoot: flutterRoot, ); await bundle.build( packagesPath: '.packages', flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory), ); final Map<String, List<String>> jsonManifest = await extractAssetManifestJsonFromBundle(bundle); final Map<Object?, Object?> smcBinManifest = await extractAssetManifestSmcBinFromBundle(bundle); final Map<String, List<Map<String, Object>>> expectedAssetManifest = <String, List<Map<String, Object>>>{ image: <Map<String, Object>>[ <String, Object>{ 'asset': image, }, <String, Object>{ 'asset': imageVariant, 'dpr': 3.0 }, ], }; expect(jsonManifest, equals(_assetManifestBinToJson(expectedAssetManifest))); expect(smcBinManifest, equals(expectedAssetManifest)); }); testWithoutContext('Main assets are not included if the file does not exist', () async { createPubspec(assets: <String>['assets/image.png']); // We intentionally do not add a 'assets/image.png'. const String imageVariant = 'assets/2x/image.png'; final List<String> assets = <String>[ imageVariant, ]; for (final String asset in assets) { final File assetFile = fs.file(asset); assetFile.createSync(recursive: true); assetFile.writeAsStringSync(asset); } final ManifestAssetBundle bundle = ManifestAssetBundle( logger: BufferLogger.test(), fileSystem: fs, platform: platform, flutterRoot: flutterRoot, ); await bundle.build( packagesPath: '.packages', flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory), ); final Map<String, List<Map<String, Object>>> expectedManifest = <String, List<Map<String, Object>>>{ 'assets/image.png': <Map<String, Object>>[ <String, Object>{ 'asset': imageVariant, 'dpr': 2.0 }, ], }; final Map<String, List<String>> jsonManifest = await extractAssetManifestJsonFromBundle(bundle); final Map<Object?, Object?> smcBinManifest = await extractAssetManifestSmcBinFromBundle(bundle); expect(jsonManifest, equals(_assetManifestBinToJson(expectedManifest))); expect(smcBinManifest, equals(expectedManifest)); }); }); group('AssetBundle asset variants (with Windows-style filepaths)', () { late final Platform platform; late final FileSystem fs; late final String flutterRoot; setUp(() { platform = FakePlatform(operatingSystem: 'windows'); fs = MemoryFileSystem.test(style: FileSystemStyle.windows); flutterRoot = Cache.defaultFlutterRoot( platform: platform, fileSystem: fs, userMessages: UserMessages() ); fs.file('.packages').createSync(); fs.file('pubspec.yaml').writeAsStringSync( ''' name: test dependencies: flutter: sdk: flutter flutter: assets: - assets/ - assets/somewhereElse/ ''' ); }); testWithoutContext('Variant detection works with windows-style filepaths', () async { const List<String> assets = <String>[ r'assets\foo.jpg', r'assets\2x\foo.jpg', r'assets\somewhereElse\bar.jpg', r'assets\somewhereElse\2x\bar.jpg', ]; for (final String asset in assets) { final File assetFile = fs.file(asset); assetFile.createSync(recursive: true); assetFile.writeAsStringSync(asset); } final ManifestAssetBundle bundle = ManifestAssetBundle( logger: BufferLogger.test(), fileSystem: fs, platform: platform, flutterRoot: flutterRoot, ); await bundle.build( packagesPath: '.packages', flutterProject: FlutterProject.fromDirectoryTest(fs.currentDirectory), ); final Map<String, List<Map<String, Object>>> expectedAssetManifest = <String, List<Map<String, Object>>>{ 'assets/foo.jpg': <Map<String, Object>>[ <String, Object>{ 'asset': 'assets/foo.jpg', }, <String, Object>{ 'asset': 'assets/2x/foo.jpg', 'dpr': 2.0, }, ], 'assets/somewhereElse/bar.jpg': <Map<String, Object>>[ <String, Object>{ 'asset': 'assets/somewhereElse/bar.jpg', }, <String, Object>{ 'asset': 'assets/somewhereElse/2x/bar.jpg', 'dpr': 2.0, }, ], }; final Map<String, List<String>> jsonManifest = await extractAssetManifestJsonFromBundle(bundle); final Map<Object?, Object?> smcBinManifest = await extractAssetManifestSmcBinFromBundle(bundle); expect(jsonManifest, equals(_assetManifestBinToJson(expectedAssetManifest))); expect(smcBinManifest, equals(expectedAssetManifest)); }); }); } Map<Object, Object> _assetManifestBinToJson(Map<Object, Object> manifest) { List<Object> convertList(List<Object> variants) => variants .map((Object variant) => (variant as Map<Object?, Object?>)['asset']!) .toList(); return manifest.map((Object key, Object value) => MapEntry<Object, Object>(key, convertList(value as List<Object>))); }
flutter/packages/flutter_tools/test/general.shard/asset_bundle_variant_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/asset_bundle_variant_test.dart", "repo_id": "flutter", "token_count": 5077 }
775
// Copyright 2014 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 'package:fake_async/fake_async.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart' as io; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/net.dart'; import 'package:flutter_tools/src/base/platform.dart'; import '../../src/common.dart'; import '../../src/fake_http_client.dart'; void main() { late BufferLogger testLogger; setUp(() { testLogger = BufferLogger.test(); }); Net createNet(io.HttpClient client) { return Net( httpClientFactory: () => client, logger: testLogger, platform: FakePlatform(), ); } group('successful fetch', () { const String responseString = 'response string'; late List<int> responseData; setUp(() { responseData = utf8.encode(responseString); }); testWithoutContext('fetchUrl() gets the data', () async { final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(Uri.parse('http://example.invalid/'), response: FakeResponse( body: utf8.encode(responseString), )), ]) ); final List<int>? data = await net.fetchUrl(Uri.parse('http://example.invalid/')); expect(data, equals(responseData)); }); testWithoutContext('fetchUrl(destFile) writes the data to a file', () async { final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(Uri.parse('http://example.invalid/'), response: FakeResponse( body: utf8.encode(responseString), )), ]) ); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final File destFile = fileSystem.file('dest_file')..createSync(); final List<int>? data = await net.fetchUrl( Uri.parse('http://example.invalid/'), destFile: destFile, ); expect(data, equals(<int>[])); expect(destFile.readAsStringSync(), responseString); }); }); testWithoutContext('retry from 500', () async { final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(Uri.parse('http://example.invalid/'), response: const FakeResponse(statusCode: io.HttpStatus.internalServerError)), FakeRequest(Uri.parse('http://example.invalid/'), response: const FakeResponse(statusCode: io.HttpStatus.internalServerError)), FakeRequest(Uri.parse('http://example.invalid/'), response: const FakeResponse(statusCode: io.HttpStatus.internalServerError)), FakeRequest(Uri.parse('http://example.invalid/'), response: const FakeResponse(statusCode: io.HttpStatus.internalServerError)), ]) ); await net.fetchUrl(Uri.parse('http://example.invalid/'), maxAttempts: 4, durationOverride: Duration.zero); expect(testLogger.statusText, 'Download failed -- attempting retry 1 in 1 second...\n' 'Download failed -- attempting retry 2 in 2 seconds...\n' 'Download failed -- attempting retry 3 in 4 seconds...\n' 'Download failed -- retry 4\n', ); expect(testLogger.errorText, isEmpty); }); testWithoutContext('retry from network error', () async { final Uri invalid = Uri.parse('http://example.invalid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, responseError: const io.SocketException('test')), FakeRequest(invalid, responseError: const io.SocketException('test')), FakeRequest(invalid, responseError: const io.SocketException('test')), FakeRequest(invalid, responseError: const io.SocketException('test')), ]) ); await net.fetchUrl(Uri.parse('http://example.invalid/'), maxAttempts: 4, durationOverride: Duration.zero); expect(testLogger.statusText, 'Download failed -- attempting retry 1 in 1 second...\n' 'Download failed -- attempting retry 2 in 2 seconds...\n' 'Download failed -- attempting retry 3 in 4 seconds...\n' 'Download failed -- retry 4\n', ); expect(testLogger.errorText, isEmpty); }); testWithoutContext('retry from SocketException', () async { final Uri invalid = Uri.parse('http://example.invalid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, responseError: const io.SocketException('')), FakeRequest(invalid, responseError: const io.SocketException('')), FakeRequest(invalid, responseError: const io.SocketException('')), FakeRequest(invalid, responseError: const io.SocketException('')), ]) ); String? error; FakeAsync().run((FakeAsync time) { net.fetchUrl(invalid).then((List<int>? value) async { error = 'test completed unexpectedly'; }, onError: (dynamic exception) { error = 'test failed unexpectedly: $exception'; }); expect(testLogger.statusText, ''); time.elapse(const Duration(milliseconds: 10000)); expect(testLogger.statusText, 'Download failed -- attempting retry 1 in 1 second...\n' 'Download failed -- attempting retry 2 in 2 seconds...\n' 'Download failed -- attempting retry 3 in 4 seconds...\n' 'Download failed -- attempting retry 4 in 8 seconds...\n', ); }); expect(testLogger.errorText, isEmpty); expect(error, isNull); expect(testLogger.traceText, contains('Download error: SocketException')); }); testWithoutContext('no retry from HandshakeException', () async { final Uri invalid = Uri.parse('http://example.invalid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, responseError: const io.HandshakeException()), FakeRequest(invalid, responseError: const io.HandshakeException()), FakeRequest(invalid, responseError: const io.HandshakeException()), FakeRequest(invalid, responseError: const io.HandshakeException()), ]) ); String? error; FakeAsync().run((FakeAsync time) { net.fetchUrl(invalid).then((List<int>? value) async { error = 'test completed unexpectedly'; }, onError: (dynamic exception) { error = 'test failed: $exception'; }); expect(testLogger.statusText, ''); time.elapse(const Duration(milliseconds: 10000)); expect(testLogger.statusText, ''); }); expect(error, startsWith('test failed')); expect(testLogger.traceText, contains('HandshakeException')); }); testWithoutContext('check for bad override on ArgumentError', () async { final Uri invalid = Uri.parse('example.invalid/'); final Net net = Net( httpClientFactory: () { return FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, responseError: ArgumentError()), ]); }, logger: testLogger, platform: FakePlatform( environment: <String, String>{ 'FLUTTER_STORAGE_BASE_URL': 'example.invalid', }, ), ); String? error; FakeAsync().run((FakeAsync time) { net.fetchUrl(Uri.parse('example.invalid/')).then((List<int>? value) async { error = 'test completed unexpectedly'; }, onError: (dynamic exception) { error = 'test failed: $exception'; }); expect(testLogger.statusText, ''); time.elapse(const Duration(milliseconds: 10000)); expect(testLogger.statusText, ''); }); expect(error, startsWith('test failed')); expect(testLogger.errorText, contains('Invalid argument')); expect(error, contains('FLUTTER_STORAGE_BASE_URL')); }); testWithoutContext('retry from HttpException', () async { final Uri invalid = Uri.parse('http://example.invalid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, responseError: const io.HttpException('')), FakeRequest(invalid, responseError: const io.HttpException('')), FakeRequest(invalid, responseError: const io.HttpException('')), FakeRequest(invalid, responseError: const io.HttpException('')), ]) ); String? error; FakeAsync().run((FakeAsync time) { net.fetchUrl(invalid).then((List<int>? value) async { error = 'test completed unexpectedly'; }, onError: (dynamic exception) { error = 'test failed unexpectedly: $exception'; }); expect(testLogger.statusText, ''); time.elapse(const Duration(milliseconds: 10000)); expect(testLogger.statusText, 'Download failed -- attempting retry 1 in 1 second...\n' 'Download failed -- attempting retry 2 in 2 seconds...\n' 'Download failed -- attempting retry 3 in 4 seconds...\n' 'Download failed -- attempting retry 4 in 8 seconds...\n', ); }); expect(testLogger.errorText, isEmpty); expect(error, isNull); expect(testLogger.traceText, contains('Download error: HttpException')); }); testWithoutContext('retry from HttpException when request throws', () async { final Uri invalid = Uri.parse('http://example.invalid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, responseError: const io.HttpException('')), FakeRequest(invalid, responseError: const io.HttpException('')), FakeRequest(invalid, responseError: const io.HttpException('')), FakeRequest(invalid, responseError: const io.HttpException('')), ]) ); String? error; FakeAsync().run((FakeAsync time) { net.fetchUrl(invalid).then((List<int>? value) async { error = 'test completed unexpectedly'; }, onError: (dynamic exception) { error = 'test failed unexpectedly: $exception'; }); expect(testLogger.statusText, ''); time.elapse(const Duration(milliseconds: 10000)); expect(testLogger.statusText, 'Download failed -- attempting retry 1 in 1 second...\n' 'Download failed -- attempting retry 2 in 2 seconds...\n' 'Download failed -- attempting retry 3 in 4 seconds...\n' 'Download failed -- attempting retry 4 in 8 seconds...\n', ); }); expect(testLogger.errorText, isEmpty); expect(error, isNull); expect(testLogger.traceText, contains('Download error: HttpException')); }); testWithoutContext('max attempts', () async { final Uri invalid = Uri.parse('http://example.invalid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, response: const FakeResponse( statusCode: HttpStatus.internalServerError, )), FakeRequest(invalid, response: const FakeResponse( statusCode: HttpStatus.internalServerError, )), FakeRequest(invalid, response: const FakeResponse( statusCode: HttpStatus.internalServerError, )), ]) ); String? error; List<int>? actualResult; FakeAsync().run((FakeAsync time) { net.fetchUrl(invalid, maxAttempts: 3).then((List<int>? value) async { actualResult = value; }, onError: (dynamic exception) { error = 'test failed unexpectedly: $exception'; }); expect(testLogger.statusText, ''); time.elapse(const Duration(milliseconds: 10000)); expect(testLogger.statusText, 'Download failed -- attempting retry 1 in 1 second...\n' 'Download failed -- attempting retry 2 in 2 seconds...\n' 'Download failed -- retry 3\n', ); }); expect(testLogger.errorText, isEmpty); expect(error, isNull); expect(actualResult, isNull); }); testWithoutContext('remote file non-existent', () async { final Uri invalid = Uri.parse('http://example.invalid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(invalid, method: HttpMethod.head, response: const FakeResponse( statusCode: HttpStatus.notFound, )), ]) ); final bool result = await net.doesRemoteFileExist(invalid); expect(result, false); }); testWithoutContext('remote file server error', () async { final Uri valid = Uri.parse('http://example.valid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(valid, method: HttpMethod.head, response: const FakeResponse( statusCode: HttpStatus.internalServerError, )), ]) ); final bool result = await net.doesRemoteFileExist(valid); expect(result, false); }); testWithoutContext('remote file exists', () async { final Uri valid = Uri.parse('http://example.valid/'); final Net net = createNet( FakeHttpClient.list(<FakeRequest>[ FakeRequest(valid, method: HttpMethod.head), ]) ); final bool result = await net.doesRemoteFileExist(valid); expect(result, true); }); }
flutter/packages/flutter_tools/test/general.shard/base/net_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/base/net_test.dart", "repo_id": "flutter", "token_count": 4845 }
776
// Copyright 2014 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_tools/src/build_system/build_system.dart'; import '../../src/common.dart'; void main() { testWithoutContext('InvalidatedReason formats message per invalidation kind', () { final InvalidatedReason inputChanged = InvalidatedReason(InvalidatedReasonKind.inputChanged) ..data.add('a.dart'); final InvalidatedReason outputChanged = InvalidatedReason(InvalidatedReasonKind.outputChanged) ..data.add('b.dart'); final InvalidatedReason inputMissing = InvalidatedReason(InvalidatedReasonKind.inputMissing) ..data.add('c.dart'); final InvalidatedReason outputMissing = InvalidatedReason(InvalidatedReasonKind.outputMissing) ..data.add('d.dart'); final InvalidatedReason outputSetChanged = InvalidatedReason(InvalidatedReasonKind.outputSetChanged) ..data.add('e.dart'); expect(inputChanged.toString(), 'The following inputs have updated contents: a.dart'); expect(outputChanged.toString(), 'The following outputs have updated contents: b.dart'); expect(inputMissing.toString(), 'The following inputs were missing: c.dart'); expect(outputMissing.toString(), 'The following outputs were missing: d.dart'); expect(outputSetChanged.toString(), 'The following outputs were removed from the output set: e.dart'); }); }
flutter/packages/flutter_tools/test/general.shard/build_system/invalidated_reason_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/build_system/invalidated_reason_test.dart", "repo_id": "flutter", "token_count": 431 }
777
// Copyright 2014 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_testing/file_testing.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/template.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/depfile.dart'; import 'package:flutter_tools/src/build_system/targets/web.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/mustache_template.dart'; import 'package:flutter_tools/src/web/compile.dart'; import 'package:flutter_tools/src/web/file_generators/flutter_service_worker_js.dart'; import 'package:flutter_tools/src/web_template.dart'; import '../../../src/common.dart'; import '../../../src/fake_process_manager.dart'; import '../../../src/testbed.dart'; const List<String> _kDart2jsLinuxArgs = <String>[ 'Artifact.engineDartBinary.TargetPlatform.web_javascript', '--disable-dart-dev', 'Artifact.dart2jsSnapshot.TargetPlatform.web_javascript', '--platform-binaries=HostArtifact.webPlatformKernelFolder', '--invoker=flutter_tool', ]; const List<String> _kDart2WasmLinuxArgs = <String> [ 'Artifact.engineDartBinary.TargetPlatform.web_javascript', 'compile', 'wasm', '--packages=.dart_tool/package_config.json', '--extra-compiler-option=--dart-sdk=Artifact.engineDartSdkPath.TargetPlatform.web_javascript', '--extra-compiler-option=--platform=HostArtifact.webPlatformKernelFolder/dart2wasm_platform.dill', '--extra-compiler-option=--delete-tostring-package-uri=dart:ui', '--extra-compiler-option=--delete-tostring-package-uri=package:flutter', ]; void main() { late Testbed testbed; late Environment environment; late FakeProcessManager processManager; final Platform linux = FakePlatform( environment: <String, String>{}, ); final Platform windows = FakePlatform( operatingSystem: 'windows', environment: <String, String>{}, ); setUp(() { testbed = Testbed(setup: () { globals.fs.file('.packages') ..createSync(recursive: true) ..writeAsStringSync('foo:foo/lib/\n'); globals.fs.currentDirectory.childDirectory('bar').createSync(); processManager = FakeProcessManager.empty(); globals.fs.file('bin/cache/flutter_web_sdk/flutter_js/flutter.js') .createSync(recursive: true); environment = Environment.test( globals.fs.currentDirectory, projectDir: globals.fs.currentDirectory.childDirectory('foo'), outputDir: globals.fs.currentDirectory.childDirectory('bar'), defines: <String, String>{ kTargetFile: globals.fs.path.join('foo', 'lib', 'main.dart'), }, artifacts: Artifacts.test(), processManager: processManager, logger: globals.logger, fileSystem: globals.fs, ); environment.buildDir.createSync(recursive: true); }, overrides: <Type, Generator>{ Platform: () => linux, }); }); test('WebEntrypointTarget generates an entrypoint with plugins and init platform', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('foo', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('void main() {}'); environment.defines[kTargetFile] = mainFile.path; environment.defines[kHasWebPlugins] = 'true'; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Plugins expect(generated, contains("import 'web_plugin_registrant.dart' as pluginRegistrant;")); expect(generated, contains('pluginRegistrant.registerPlugins();')); // Import. expect(generated, contains("import 'package:foo/main.dart' as entrypoint;")); // Main expect(generated, contains('ui_web.bootstrapEngine(')); expect(generated, contains('entrypoint.main as _')); }, overrides: <Type, Generator>{ TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('version.json is created after release build', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; final Directory webResources = environment.projectDir.childDirectory('web'); webResources.childFile('index.html') .createSync(recursive: true); environment.buildDir.childFile('main.dart.js').createSync(); await WebReleaseBundle(<WebCompilerConfig>[ const JsCompilerConfig() ]).build(environment); expect(environment.outputDir.childFile('version.json'), exists); })); test('override version values', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; environment.defines[kBuildName] = '2.0.0'; environment.defines[kBuildNumber] = '22'; final Directory webResources = environment.projectDir.childDirectory('web'); webResources.childFile('index.html').createSync(recursive: true); environment.buildDir.childFile('main.dart.js').createSync(); await WebReleaseBundle(<WebCompilerConfig>[ const JsCompilerConfig() ]).build(environment); final String versionFile = environment.outputDir .childFile('version.json') .readAsStringSync(); expect(versionFile, contains('"version":"2.0.0"')); expect(versionFile, contains('"build_number":"22"')); })); test('Base href is created in index.html with given base-href after release build', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; environment.defines[kBaseHref] = '/basehreftest/'; final Directory webResources = environment.projectDir.childDirectory('web'); webResources.childFile('index.html').createSync(recursive: true); webResources.childFile('index.html').writeAsStringSync(''' <!DOCTYPE html><html><base href="$kBaseHrefPlaceholder"><head></head></html> '''); environment.buildDir.childFile('main.dart.js').createSync(); await WebTemplatedFiles('buildConfig').build(environment); expect(environment.outputDir.childFile('index.html').readAsStringSync(), contains('/basehreftest/')); })); test('null base href does not override existing base href in index.html', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; final Directory webResources = environment.projectDir.childDirectory('web'); webResources.childFile('index.html').createSync(recursive: true); webResources.childFile('index.html').writeAsStringSync(''' <!DOCTYPE html><html><head><base href='/basehreftest/'></head></html> '''); environment.buildDir.childFile('main.dart.js').createSync(); await WebTemplatedFiles('build config').build(environment); expect(environment.outputDir.childFile('index.html').readAsStringSync(), contains('/basehreftest/')); })); test('WebReleaseBundle copies dart2js output and resource files to output directory', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; final Directory webResources = environment.projectDir.childDirectory('web'); webResources.childFile('foo.txt') ..createSync(recursive: true) ..writeAsStringSync('A'); environment.buildDir.childFile('main.dart.js').createSync(); environment.buildDir.childFile('main.dart.js.map').createSync(); await WebReleaseBundle(<WebCompilerConfig>[ const JsCompilerConfig() ]).build(environment); expect(environment.outputDir.childFile('foo.txt') .readAsStringSync(), 'A'); expect(environment.outputDir.childFile('main.dart.js') .existsSync(), true); expect(environment.outputDir.childFile('main.dart.js.map') .existsSync(), true); expect(environment.outputDir.childDirectory('assets') .childFile('AssetManifest.bin.json').existsSync(), true); // Update to arbitrary resource file triggers rebuild. webResources.childFile('foo.txt').writeAsStringSync('B'); await WebReleaseBundle(<WebCompilerConfig>[ const JsCompilerConfig() ]).build(environment); expect(environment.outputDir.childFile('foo.txt') .readAsStringSync(), 'B'); })); test('WebReleaseBundle copies over output files when they change', () => testbed.run(() async { final Directory webResources = environment.projectDir.childDirectory('web'); webResources.childFile('foo.txt') ..createSync(recursive: true) ..writeAsStringSync('A'); environment.buildDir.childFile('main.dart.wasm')..createSync()..writeAsStringSync('old wasm'); environment.buildDir.childFile('main.dart.mjs')..createSync()..writeAsStringSync('old mjs'); await WebReleaseBundle(<WebCompilerConfig>[ const WasmCompilerConfig() ]).build(environment); expect(environment.outputDir.childFile('main.dart.wasm') .readAsStringSync(), 'old wasm'); expect(environment.outputDir.childFile('main.dart.mjs') .readAsStringSync(), 'old mjs'); environment.buildDir.childFile('main.dart.wasm')..createSync()..writeAsStringSync('new wasm'); environment.buildDir.childFile('main.dart.mjs')..createSync()..writeAsStringSync('new mjs'); await WebReleaseBundle(<WebCompilerConfig>[ const WasmCompilerConfig() ]).build(environment); expect(environment.outputDir.childFile('main.dart.wasm') .readAsStringSync(), 'new wasm'); expect(environment.outputDir.childFile('main.dart.mjs') .readAsStringSync(), 'new mjs'); })); test('WebEntrypointTarget generates an entrypoint for a file outside of main', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('other', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('void main() {}'); environment.defines[kTargetFile] = mainFile.path; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Import. expect(generated, contains("import 'file:///other/lib/main.dart' as entrypoint;")); }, overrides: <Type, Generator>{ TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('WebEntrypointTarget generates a plugin registrant for a file outside of main', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('other', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('void main() {}'); environment.defines[kTargetFile] = mainFile.path; environment.defines[kHasWebPlugins] = 'true'; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Import. expect(generated, contains("import 'file:///other/lib/main.dart' as entrypoint;")); expect(generated, contains("import 'web_plugin_registrant.dart' as pluginRegistrant;")); }, overrides: <Type, Generator>{ TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('WebEntrypointTarget generates an entrypoint with plugins and init platform on windows', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('foo', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('void main() {}'); environment.defines[kTargetFile] = mainFile.path; environment.defines[kHasWebPlugins] = 'true'; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Plugins expect(generated, contains("import 'web_plugin_registrant.dart' as pluginRegistrant;")); expect(generated, contains('pluginRegistrant.registerPlugins();')); // Import. expect(generated, contains("import 'package:foo/main.dart' as entrypoint;")); // Main expect(generated, contains('ui_web.bootstrapEngine(')); expect(generated, contains('entrypoint.main as _')); }, overrides: <Type, Generator>{ Platform: () => windows, TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('WebEntrypointTarget generates an entrypoint without plugins and init platform', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('foo', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('void main() {}'); environment.defines[kTargetFile] = mainFile.path; environment.defines[kHasWebPlugins] = 'false'; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Plugins (the generated file is a noop) expect(generated, contains("import 'web_plugin_registrant.dart' as pluginRegistrant;")); expect(generated, contains('pluginRegistrant.registerPlugins();')); // Import. expect(generated, contains("import 'package:foo/main.dart' as entrypoint;")); // Main expect(generated, contains('ui_web.bootstrapEngine(')); expect(generated, contains('entrypoint.main as _')); }, overrides: <Type, Generator>{ TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('WebEntrypointTarget generates an entrypoint with a language version', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('foo', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('// @dart=2.8\nvoid main() {}'); environment.defines[kTargetFile] = mainFile.path; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Language version expect(generated, contains('// @dart=2.8')); }, overrides: <Type, Generator>{ TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('WebEntrypointTarget generates an entrypoint with a language version from a package config', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('foo', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('void main() {}'); globals.fs.file(globals.fs.path.join('pubspec.yaml')) .writeAsStringSync('name: foo\n'); environment.defines[kTargetFile] = mainFile.path; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Language version expect(generated, contains('// @dart=2.7')); }, overrides: <Type, Generator>{ TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('WebEntrypointTarget generates an entrypoint without plugins and without init platform', () => testbed.run(() async { final File mainFile = globals.fs.file(globals.fs.path.join('foo', 'lib', 'main.dart')) ..createSync(recursive: true) ..writeAsStringSync('void main() {}'); environment.defines[kTargetFile] = mainFile.path; environment.defines[kHasWebPlugins] = 'false'; await const WebEntrypointTarget().build(environment); final String generated = environment.buildDir.childFile('main.dart').readAsStringSync(); // Plugins expect(generated, contains("import 'web_plugin_registrant.dart' as pluginRegistrant;")); expect(generated, contains('pluginRegistrant.registerPlugins();')); // Import. expect(generated, contains("import 'package:foo/main.dart' as entrypoint;")); // Main expect(generated, contains('ui_web.bootstrapEngine(')); expect(generated, contains('entrypoint.main as _')); }, overrides: <Type, Generator>{ TemplateRenderer: () => const MustacheTemplateRenderer(), })); test('Dart2JSTarget calls dart2js with expected args with csp', () => testbed.run(() async { environment.defines[kBuildMode] = 'profile'; environment.defines[JsCompilerConfig.kCspMode] = 'true'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-minify', '--no-source-maps', '-O4', '--csp', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( csp: true, sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget ignores frontend server starter path option when calling dart2js', () => testbed.run(() async { environment.defines[kBuildMode] = 'profile'; environment.defines[kFrontendServerStarterPath] = 'path/to/frontend_server_starter.dart'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-minify', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with expected args with enabled experiment', () => testbed.run(() async { environment.defines[kBuildMode] = 'profile'; environment.defines[kExtraFrontEndOptions] = '--enable-experiment=non-nullable'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '--enable-experiment=non-nullable', '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '--enable-experiment=non-nullable', '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-minify', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with expected args in profile mode', () => testbed.run(() async { environment.defines[kBuildMode] = 'profile'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-minify', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with expected args in release mode', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with expected args in release mode with native null assertions', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; environment.defines[JsCompilerConfig.kNativeNullAssertions] = 'true'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--native-null-assertions', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--native-null-assertions', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( nativeNullAssertions: true, sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with expected args in release with dart2js optimization override', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-O3', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( optimizationLevel: 3, sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget produces expected depfile', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ], onRun: (_) { environment.buildDir.childFile('app.dill.deps') .writeAsStringSync('file:///a.dart'); }, )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( sourceMaps: false, ) ).build(environment); expect(environment.buildDir.childFile('dart2js.d'), exists); final Depfile depfile = environment.depFileService.parse(environment.buildDir.childFile('dart2js.d')); expect(depfile.inputs.single.path, globals.fs.path.absolute('a.dart')); expect(depfile.outputs.single.path, environment.buildDir.childFile('main.dart.js').absolute.path); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with Dart defines in release mode', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; environment.defines[kDartDefines] = encodeDartDefines(<String>['FOO=bar', 'BAZ=qux']); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFOO=bar', '-DBAZ=qux', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFOO=bar', '-DBAZ=qux', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget can enable source maps', () => testbed.run(() async { environment.defines[kBuildMode] = 'release'; environment.defines[JsCompilerConfig.kSourceMapsEnabled] = 'true'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.product=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig() ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with Dart defines in profile mode', () => testbed.run(() async { environment.defines[kBuildMode] = 'profile'; environment.defines[kDartDefines] = encodeDartDefines(<String>['FOO=bar', 'BAZ=qux']); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFOO=bar', '-DBAZ=qux', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFOO=bar', '-DBAZ=qux', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-minify', '--no-source-maps', '-O4', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with expected args with dump-info', () => testbed.run(() async { environment.defines[kBuildMode] = 'profile'; environment.defines[JsCompilerConfig.kDart2jsDumpInfo] = 'true'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-minify', '--no-source-maps', '-O4', '--dump-info', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( dumpInfo: true, sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); test('Dart2JSTarget calls dart2js with expected args with no-frequency-based-minification', () => testbed.run(() async { environment.defines[kBuildMode] = 'profile'; environment.defines[JsCompilerConfig.kDart2jsNoFrequencyBasedMinification] = 'true'; processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-source-maps', '-o', environment.buildDir.childFile('app.dill').absolute.path, '--packages=.dart_tool/package_config.json', '--cfe-only', environment.buildDir.childFile('main.dart').absolute.path, ] )); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2jsLinuxArgs, '-Ddart.vm.profile=true', '-DFLUTTER_WEB_AUTO_DETECT=true', '--no-minify', '--no-source-maps', '-O4', '--no-frequency-based-minification', '-o', environment.buildDir.childFile('main.dart.js').absolute.path, environment.buildDir.childFile('app.dill').absolute.path, ] )); await Dart2JSTarget( const JsCompilerConfig( noFrequencyBasedMinification: true, sourceMaps: false, ) ).build(environment); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); for (final WebRendererMode renderer in <WebRendererMode>[WebRendererMode.canvaskit, WebRendererMode.skwasm]) { for (int level = 1; level <= 4; level++) { for (final bool strip in <bool>[true, false]) { for (final List<String> defines in const <List<String>>[<String>[], <String>['FOO=bar', 'BAZ=qux']]) { for (final String buildMode in const <String>['profile', 'release']) { test('Dart2WasmTarget invokes dart2wasm with renderer=$renderer, -O$level, stripping=$strip, defines=$defines, modeMode=$buildMode', () => testbed.run(() async { environment.defines[kBuildMode] = buildMode; environment.defines[kDartDefines] = encodeDartDefines(defines); final File depFile = environment.buildDir.childFile('dart2wasm.d'); final File outputJsFile = environment.buildDir.childFile('main.dart.mjs'); processManager.addCommand(FakeCommand( command: <String>[ ..._kDart2WasmLinuxArgs, if (renderer == WebRendererMode.skwasm) ...<String>[ '--extra-compiler-option=--import-shared-memory', '--extra-compiler-option=--shared-memory-max-pages=32768', ], '-Ddart.vm.${buildMode == 'release' ? 'product' : 'profile' }=true', ...defines.map((String define) => '-D$define'), if (renderer == WebRendererMode.skwasm) ...<String>[ '-DFLUTTER_WEB_AUTO_DETECT=false', '-DFLUTTER_WEB_USE_SKIA=false', '-DFLUTTER_WEB_USE_SKWASM=true', ], if (renderer == WebRendererMode.canvaskit) ...<String>[ '-DFLUTTER_WEB_AUTO_DETECT=false', '-DFLUTTER_WEB_USE_SKIA=true', ], '--extra-compiler-option=--depfile=${depFile.absolute.path}', '-O$level', if (strip && buildMode == 'release') '--no-name-section' else '--name-section', '-o', environment.buildDir.childFile('main.dart.wasm').absolute.path, environment.buildDir.childFile('main.dart').absolute.path, ], onRun: (_) => outputJsFile..createSync()..writeAsStringSync('foo')) ); await Dart2WasmTarget( WasmCompilerConfig( optimizationLevel: level, stripWasm: strip, renderer: renderer, ) ).build(environment); expect(outputJsFile.existsSync(), isTrue); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, })); } } } } } test('Generated service worker is empty with none-strategy', () => testbed.run(() { final String fileGeneratorsPath = environment.artifacts.getArtifactPath(Artifact.flutterToolsFileGenerators); final String result = generateServiceWorker( fileGeneratorsPath, <String, String>{'/foo': 'abcd'}, <String>[], serviceWorkerStrategy: ServiceWorkerStrategy.none, ); expect(result, ''); })); test('Generated service worker correctly inlines file hashes', () => testbed.run(() { final String fileGeneratorsPath = environment.artifacts.getArtifactPath(Artifact.flutterToolsFileGenerators); final String result = generateServiceWorker( fileGeneratorsPath, <String, String>{'/foo': 'abcd'}, <String>[], serviceWorkerStrategy: ServiceWorkerStrategy.offlineFirst, ); expect(result, contains('{"/foo": "abcd"};')); })); test('Generated service worker includes core files', () => testbed.run(() { final String fileGeneratorsPath = environment.artifacts.getArtifactPath(Artifact.flutterToolsFileGenerators); final String result = generateServiceWorker( fileGeneratorsPath, <String, String>{'/foo': 'abcd'}, <String>['foo', 'bar'], serviceWorkerStrategy: ServiceWorkerStrategy.offlineFirst, ); expect(result, contains('"foo",\n"bar"')); })); test('WebServiceWorker generates a service_worker for a web resource folder', () => testbed.run(() async { environment.outputDir.childDirectory('a').childFile('a.txt') ..createSync(recursive: true) ..writeAsStringSync('A'); await WebServiceWorker(globals.fs, <WebCompilerConfig>[ const JsCompilerConfig() ]).build(environment); expect(environment.outputDir.childFile('flutter_service_worker.js'), exists); // Contains file hash. expect(environment.outputDir.childFile('flutter_service_worker.js').readAsStringSync(), contains('"a/a.txt": "7fc56270e7a70fa81a5935b72eacbe29"')); expect(environment.buildDir.childFile('service_worker.d'), exists); // Depends on resource file. expect(environment.buildDir.childFile('service_worker.d').readAsStringSync(), contains('a/a.txt')); // Does NOT contain NOTICES expect(environment.outputDir.childFile('flutter_service_worker.js').readAsStringSync(), isNot(contains('NOTICES'))); })); test('WebServiceWorker contains baseUrl cache', () => testbed.run(() async { environment.outputDir .childFile('index.html') .createSync(recursive: true); environment.outputDir .childFile('assets/index.html') ..createSync(recursive: true) ..writeAsStringSync('A'); await WebServiceWorker(globals.fs, <WebCompilerConfig>[ const JsCompilerConfig() ]).build(environment); expect(environment.outputDir.childFile('flutter_service_worker.js'), exists); // Contains the same file hash for both `/` and the root index.html file. const String rootIndexHash = 'd41d8cd98f00b204e9800998ecf8427e'; expect(environment.outputDir.childFile('flutter_service_worker.js').readAsStringSync(), contains('"/": "$rootIndexHash"')); expect(environment.outputDir.childFile('flutter_service_worker.js').readAsStringSync(), contains('"index.html": "$rootIndexHash"')); // Make sure `assets/index.html` has a different hash than `index.html`. expect(environment.outputDir.childFile('flutter_service_worker.js').readAsStringSync(), contains('"assets/index.html": "7fc56270e7a70fa81a5935b72eacbe29"')); expect(environment.buildDir.childFile('service_worker.d'), exists); })); test('WebServiceWorker does not cache source maps', () => testbed.run(() async { environment.outputDir .childFile('main.dart.js') .createSync(recursive: true); environment.outputDir .childFile('main.dart.js.map') .createSync(recursive: true); await WebServiceWorker(globals.fs, <WebCompilerConfig>[ const JsCompilerConfig() ]).build(environment); // No caching of source maps. expect(environment.outputDir.childFile('flutter_service_worker.js').readAsStringSync(), isNot(contains('"main.dart.js.map"'))); // Expected twice, once for RESOURCES and once for CORE. expect(environment.outputDir.childFile('flutter_service_worker.js').readAsStringSync(), contains('"main.dart.js"')); })); test('WebBuiltInAssets copies over canvaskit again if the web sdk changes', () => testbed.run(() async { final File canvasKitInput = globals.fs.file('bin/cache/flutter_web_sdk/canvaskit/canvaskit.wasm') ..createSync(recursive: true); canvasKitInput.writeAsStringSync('foo', flush: true); await WebBuiltInAssets(globals.fs).build(environment); final File canvasKitOutputBefore = environment.outputDir.childDirectory('canvaskit') .childFile('canvaskit.wasm'); expect(canvasKitOutputBefore.existsSync(), true); expect(canvasKitOutputBefore.readAsStringSync(), 'foo'); canvasKitInput.writeAsStringSync('bar', flush: true); await WebBuiltInAssets(globals.fs).build(environment); final File canvasKitOutputAfter = environment.outputDir.childDirectory('canvaskit') .childFile('canvaskit.wasm'); expect(canvasKitOutputAfter.existsSync(), true); expect(canvasKitOutputAfter.readAsStringSync(), 'bar'); })); }
flutter/packages/flutter_tools/test/general.shard/build_system/targets/web_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/build_system/targets/web_test.dart", "repo_id": "flutter", "token_count": 16749 }
778
// Copyright 2014 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/memory.dart'; import 'package:flutter_tools/src/base/config.dart'; import 'package:flutter_tools/src/base/error_handling_io.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/convert.dart'; import 'package:test/fake.dart'; import '../src/common.dart'; void main() { late Config config; late MemoryFileSystem memoryFileSystem; late FakePlatform fakePlatform; setUp(() { memoryFileSystem = MemoryFileSystem.test(); fakePlatform = FakePlatform( environment: <String, String>{ 'HOME': '/', }, ); config = Config( 'example', fileSystem: memoryFileSystem, logger: BufferLogger.test(), platform: fakePlatform, ); }); testWithoutContext('Config get set value', () async { expect(config.getValue('foo'), null); config.setValue('foo', 'bar'); expect(config.getValue('foo'), 'bar'); expect(config.keys, contains('foo')); }); testWithoutContext('Config get set bool value', () async { expect(config.getValue('foo'), null); config.setValue('foo', true); expect(config.getValue('foo'), true); expect(config.keys, contains('foo')); }); testWithoutContext('Config containsKey', () async { expect(config.containsKey('foo'), false); config.setValue('foo', 'bar'); expect(config.containsKey('foo'), true); }); testWithoutContext('Config removeValue', () async { expect(config.getValue('foo'), null); config.setValue('foo', 'bar'); expect(config.getValue('foo'), 'bar'); expect(config.keys, contains('foo')); config.removeValue('foo'); expect(config.getValue('foo'), null); expect(config.keys, isNot(contains('foo'))); }); testWithoutContext('Config does not error on a file with a deprecated field', () { final BufferLogger bufferLogger = BufferLogger.test(); final File file = memoryFileSystem.file('.flutter_example') ..writeAsStringSync(''' { "is-bot": false, "license-hash": "3e8c85e63b26ce223cda96a9a8fbb410", "redisplay-welcome-message": true, "last-devtools-activation-time": "2021-10-04 16:03:19.832823", "last-active-stable-version": "b22742018b3edf16c6cadd7b76d9db5e7f9064b5" } '''); config = Config( 'example', fileSystem: memoryFileSystem, logger: bufferLogger, platform: fakePlatform, ); expect(file.existsSync(), isTrue); expect(bufferLogger.errorText, isEmpty); }); testWithoutContext('Config parse error', () { final BufferLogger bufferLogger = BufferLogger.test(); final File file = memoryFileSystem.file('.flutter_example') ..writeAsStringSync('{"hello":"bar'); config = Config( 'example', fileSystem: memoryFileSystem, logger: bufferLogger, platform: fakePlatform, ); expect(file.existsSync(), false); expect(bufferLogger.errorText, contains('Failed to decode preferences')); }); testWithoutContext('Config does not error on missing file', () { final BufferLogger bufferLogger = BufferLogger.test(); final File file = memoryFileSystem.file('example'); config = Config( 'example', fileSystem: memoryFileSystem, logger: bufferLogger, platform: fakePlatform, ); expect(file.existsSync(), false); expect(bufferLogger.errorText, isEmpty); }); testWithoutContext('Config does not error on a normally fatal file system exception', () { final BufferLogger bufferLogger = BufferLogger.test(); final Platform platform = FakePlatform(); final File file = ErrorHandlingFile( platform: platform, fileSystem: ErrorHandlingFileSystem(delegate: MemoryFileSystem.test(), platform: platform), delegate: FakeFile('testfile'), ); config = Config.createForTesting(file, bufferLogger); expect(bufferLogger.errorText, contains('Could not read preferences in testfile')); expect(bufferLogger.errorText, contains(r'sudo chown -R $(whoami) /testfile')); }); testWithoutContext('Config.createForTesting does not error when failing to delete a file', () { final BufferLogger bufferLogger = BufferLogger.test(); final FileExceptionHandler handler = FileExceptionHandler(); final MemoryFileSystem fs = MemoryFileSystem.test(opHandle: handler.opHandle); final File file = fs.file('testfile') // We write invalid JSON so that we test catching a `FormatException` ..writeAsStringSync('{"This is not valid JSON"'); handler.addError( file, FileSystemOp.delete, const FileSystemException( "Cannot delete file, path = 'testfile' (OS Error: No such file or directory, errno = 2)", ), ); // Should not throw a FileSystemException Config.createForTesting(file, bufferLogger); }); testWithoutContext('Config in home dir is used if it exists', () { memoryFileSystem.file('.flutter_example').writeAsStringSync('{"hello":"bar"}'); config = Config( 'example', fileSystem: memoryFileSystem, logger: BufferLogger.test(), platform: fakePlatform, ); expect(config.getValue('hello'), 'bar'); expect(memoryFileSystem.file('.config/flutter/example').existsSync(), false); }); testWithoutContext('Config is created in config dir if it does not already exist in home dir', () { config = Config( 'example', fileSystem: memoryFileSystem, logger: BufferLogger.test(), platform: fakePlatform, ); config.setValue('foo', 'bar'); expect(memoryFileSystem.file('.config/flutter/example').existsSync(), true); }); } class FakeFile extends Fake implements File { FakeFile(this.path); @override final String path; @override bool existsSync() { return true; } @override String readAsStringSync({Encoding encoding = utf8ForTesting}) { throw const FileSystemException('', '', OSError('', 13)); // EACCES error on linux } }
flutter/packages/flutter_tools/test/general.shard/config_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/config_test.dart", "repo_id": "flutter", "token_count": 2137 }
779
// Copyright 2014 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:file/memory.dart'; import 'package:flutter_tools/src/application_package.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/desktop_device.dart'; import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/device_port_forwarder.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:test/fake.dart'; import '../src/common.dart'; import '../src/fake_process_manager.dart'; void main() { group('Basic info', () { testWithoutContext('Category is desktop', () async { final FakeDesktopDevice device = setUpDesktopDevice(); expect(device.category, Category.desktop); }); testWithoutContext('Not an emulator', () async { final FakeDesktopDevice device = setUpDesktopDevice(); expect(await device.isLocalEmulator, false); expect(await device.emulatorId, null); }); testWithoutContext('Uses OS name as SDK name', () async { final FakeDesktopDevice device = setUpDesktopDevice(); expect(await device.sdkNameAndVersion, 'Example'); }); }); group('Install', () { testWithoutContext('Install checks always return true', () async { final FakeDesktopDevice device = setUpDesktopDevice(); expect(await device.isAppInstalled(FakeApplicationPackage()), true); expect(await device.isLatestBuildInstalled(FakeApplicationPackage()), true); expect(device.category, Category.desktop); }); testWithoutContext('Install and uninstall are no-ops that report success', () async { final FakeDesktopDevice device = setUpDesktopDevice(); final FakeApplicationPackage package = FakeApplicationPackage(); expect(await device.uninstallApp(package), true); expect(await device.isAppInstalled(package), true); expect(await device.isLatestBuildInstalled(package), true); expect(await device.installApp(package), true); expect(await device.isAppInstalled(package), true); expect(await device.isLatestBuildInstalled(package), true); expect(device.category, Category.desktop); }); }); group('Starting and stopping application', () { testWithoutContext('Stop without start is a successful no-op', () async { final FakeDesktopDevice device = setUpDesktopDevice(); final FakeApplicationPackage package = FakeApplicationPackage(); expect(await device.stopApp(package), true); }); testWithoutContext('Can run from prebuilt application', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Completer<void> completer = Completer<void>(); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['debug'], stdout: 'The Dart VM service is listening on http://127.0.0.1/0\n', completer: completer, ), ]); final FakeDesktopDevice device = setUpDesktopDevice(processManager: processManager, fileSystem: fileSystem); final String? executableName = device.executablePathForDevice(FakeApplicationPackage(), BuildInfo.debug); fileSystem.file(executableName).writeAsStringSync('\n'); final FakeApplicationPackage package = FakeApplicationPackage(); final LaunchResult result = await device.startApp( package, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), ); expect(result.started, true); expect(result.vmServiceUri, Uri.parse('http://127.0.0.1/0')); }); testWithoutContext('Null executable path fails gracefully', () async { final BufferLogger logger = BufferLogger.test(); final DesktopDevice device = setUpDesktopDevice(nullExecutablePathForDevice: true, logger: logger); final FakeApplicationPackage package = FakeApplicationPackage(); final LaunchResult result = await device.startApp( package, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), ); expect(result.started, false); expect(logger.errorText, contains('Unable to find executable to run')); }); testWithoutContext('stopApp kills process started by startApp', () async { final Completer<void> completer = Completer<void>(); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['debug'], stdout: 'The Dart VM service is listening on http://127.0.0.1/0\n', completer: completer, ), ]); final FakeDesktopDevice device = setUpDesktopDevice(processManager: processManager); final FakeApplicationPackage package = FakeApplicationPackage(); final LaunchResult result = await device.startApp( package, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), ); expect(result.started, true); expect(await device.stopApp(package), true); }); }); testWithoutContext('startApp supports DebuggingOptions through FLUTTER_ENGINE_SWITCH environment variables', () async { final Completer<void> completer = Completer<void>(); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['debug'], stdout: 'The Dart VM service is listening on http://127.0.0.1/0\n', completer: completer, environment: const <String, String>{ 'FLUTTER_ENGINE_SWITCH_1': 'enable-dart-profiling=true', 'FLUTTER_ENGINE_SWITCH_2': 'trace-startup=true', 'FLUTTER_ENGINE_SWITCH_3': 'enable-software-rendering=true', 'FLUTTER_ENGINE_SWITCH_4': 'skia-deterministic-rendering=true', 'FLUTTER_ENGINE_SWITCH_5': 'trace-skia=true', 'FLUTTER_ENGINE_SWITCH_6': 'trace-allowlist=foo,bar', 'FLUTTER_ENGINE_SWITCH_7': 'trace-skia-allowlist=skia.a,skia.b', 'FLUTTER_ENGINE_SWITCH_8': 'trace-systrace=true', 'FLUTTER_ENGINE_SWITCH_9': 'trace-to-file=path/to/trace.binpb', 'FLUTTER_ENGINE_SWITCH_10': 'endless-trace-buffer=true', 'FLUTTER_ENGINE_SWITCH_11': 'dump-skp-on-shader-compilation=true', 'FLUTTER_ENGINE_SWITCH_12': 'cache-sksl=true', 'FLUTTER_ENGINE_SWITCH_13': 'purge-persistent-cache=true', 'FLUTTER_ENGINE_SWITCH_14': 'enable-impeller=false', 'FLUTTER_ENGINE_SWITCH_15': 'enable-checked-mode=true', 'FLUTTER_ENGINE_SWITCH_16': 'verify-entry-points=true', 'FLUTTER_ENGINE_SWITCH_17': 'start-paused=true', 'FLUTTER_ENGINE_SWITCH_18': 'disable-service-auth-codes=true', 'FLUTTER_ENGINE_SWITCH_19': 'dart-flags=--null_assertions', 'FLUTTER_ENGINE_SWITCH_20': 'use-test-fonts=true', 'FLUTTER_ENGINE_SWITCH_21': 'verbose-logging=true', 'FLUTTER_ENGINE_SWITCHES': '21', } ), ]); final FakeDesktopDevice device = setUpDesktopDevice(processManager: processManager); final FakeApplicationPackage package = FakeApplicationPackage(); final LaunchResult result = await device.startApp( package, prebuiltApplication: true, platformArgs: <String, Object>{ 'trace-startup': true, }, debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, startPaused: true, disableServiceAuthCodes: true, enableSoftwareRendering: true, skiaDeterministicRendering: true, traceSkia: true, traceAllowlist: 'foo,bar', traceSkiaAllowlist: 'skia.a,skia.b', traceSystrace: true, traceToFile: 'path/to/trace.binpb', endlessTraceBuffer: true, dumpSkpOnShaderCompilation: true, cacheSkSL: true, purgePersistentCache: true, useTestFonts: true, verboseSystemLogs: true, nullAssertions: true, ), ); expect(result.started, true); }); testWithoutContext('startApp supports DebuggingOptions through FLUTTER_ENGINE_SWITCH environment variables when debugging is disabled', () async { final Completer<void> completer = Completer<void>(); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['debug'], stdout: 'The Dart VM service is listening on http://127.0.0.1/0\n', completer: completer, environment: const <String, String>{ 'FLUTTER_ENGINE_SWITCH_1': 'enable-dart-profiling=true', 'FLUTTER_ENGINE_SWITCH_2': 'trace-startup=true', 'FLUTTER_ENGINE_SWITCH_3': 'trace-allowlist=foo,bar', 'FLUTTER_ENGINE_SWITCH_4': 'cache-sksl=true', 'FLUTTER_ENGINE_SWITCH_5': 'enable-impeller=false', 'FLUTTER_ENGINE_SWITCHES': '5', } ), ]); final FakeDesktopDevice device = setUpDesktopDevice(processManager: processManager); final FakeApplicationPackage package = FakeApplicationPackage(); final LaunchResult result = await device.startApp( package, prebuiltApplication: true, platformArgs: <String, Object>{ 'trace-startup': true, }, debuggingOptions: DebuggingOptions.disabled( BuildInfo.debug, traceAllowlist: 'foo,bar', cacheSkSL: true, ), ); expect(result.started, true); }); testWithoutContext('Port forwarder is a no-op', () async { final FakeDesktopDevice device = setUpDesktopDevice(); final DevicePortForwarder portForwarder = device.portForwarder; final int result = await portForwarder.forward(2); expect(result, 2); expect(portForwarder.forwardedPorts.isEmpty, true); }); testWithoutContext('createDevFSWriter returns a LocalDevFSWriter', () { final FakeDesktopDevice device = setUpDesktopDevice(); expect(device.createDevFSWriter(FakeApplicationPackage(), ''), isA<LocalDevFSWriter>()); }); testWithoutContext('startApp supports dartEntrypointArgs', () async { final Completer<void> completer = Completer<void>(); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['debug', 'arg1', 'arg2'], stdout: 'The Dart VM service is listening on http://127.0.0.1/0\n', completer: completer, ), ]); final FakeDesktopDevice device = setUpDesktopDevice(processManager: processManager); final FakeApplicationPackage package = FakeApplicationPackage(); final LaunchResult result = await device.startApp( package, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, dartEntrypointArgs: <String>['arg1', 'arg2'], ), ); expect(result.started, true); }); testWithoutContext('Device logger captures all output', () async { final Completer<void> exitCompleter = Completer<void>(); final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: const <String>['debug', 'arg1', 'arg2'], exitCode: -1, stderr: 'Oops\n', completer: exitCompleter, outputFollowsExit: true, ), ]); final FakeDesktopDevice device = setUpDesktopDevice( processManager: processManager, ); unawaited(Future<void>(() { exitCompleter.complete(); })); // Start looking for 'Oops' in the stream before starting the app. expect(device.getLogReader().logLines, emits('Oops')); final FakeApplicationPackage package = FakeApplicationPackage(); await device.startApp( package, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, dartEntrypointArgs: <String>['arg1', 'arg2'], ), ); }); testWithoutContext('Desktop devices pass through the enable-impeller flag', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['debug'], exitCode: -1, environment: <String, String>{ 'FLUTTER_ENGINE_SWITCH_1': 'enable-dart-profiling=true', 'FLUTTER_ENGINE_SWITCH_2': 'enable-impeller=true', 'FLUTTER_ENGINE_SWITCH_3': 'enable-checked-mode=true', 'FLUTTER_ENGINE_SWITCH_4': 'verify-entry-points=true', 'FLUTTER_ENGINE_SWITCHES': '4' } ), ]); final FakeDesktopDevice device = setUpDesktopDevice( processManager: processManager, ); final FakeApplicationPackage package = FakeApplicationPackage(); await device.startApp( package, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, enableImpeller: ImpellerStatus.enabled, dartEntrypointArgs: <String>[], ), ); }); testWithoutContext('Desktop devices pass through the --no-enable-impeller flag', () async { final FakeProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['debug'], exitCode: -1, environment: <String, String>{ 'FLUTTER_ENGINE_SWITCH_1': 'enable-dart-profiling=true', 'FLUTTER_ENGINE_SWITCH_2': 'enable-impeller=false', 'FLUTTER_ENGINE_SWITCH_3': 'enable-checked-mode=true', 'FLUTTER_ENGINE_SWITCH_4': 'verify-entry-points=true', 'FLUTTER_ENGINE_SWITCHES': '4' } ), ]); final FakeDesktopDevice device = setUpDesktopDevice( processManager: processManager, ); final FakeApplicationPackage package = FakeApplicationPackage(); await device.startApp( package, prebuiltApplication: true, debuggingOptions: DebuggingOptions.enabled( BuildInfo.debug, enableImpeller: ImpellerStatus.disabled, dartEntrypointArgs: <String>[], ), ); }); } FakeDesktopDevice setUpDesktopDevice({ FileSystem? fileSystem, Logger? logger, ProcessManager? processManager, OperatingSystemUtils? operatingSystemUtils, bool nullExecutablePathForDevice = false, }) { return FakeDesktopDevice( fileSystem: fileSystem ?? MemoryFileSystem.test(), logger: logger ?? BufferLogger.test(), processManager: processManager ?? FakeProcessManager.any(), operatingSystemUtils: operatingSystemUtils ?? FakeOperatingSystemUtils(), nullExecutablePathForDevice: nullExecutablePathForDevice, ); } /// A trivial subclass of DesktopDevice for testing the shared functionality. class FakeDesktopDevice extends DesktopDevice { FakeDesktopDevice({ required ProcessManager processManager, required Logger logger, required FileSystem fileSystem, required OperatingSystemUtils operatingSystemUtils, this.nullExecutablePathForDevice = false, }) : super( 'dummy', platformType: PlatformType.linux, ephemeral: false, processManager: processManager, logger: logger, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ); /// The [mainPath] last passed to [buildForDevice]. String? lastBuiltMainPath; /// The [buildInfo] last passed to [buildForDevice]. BuildInfo? lastBuildInfo; final bool nullExecutablePathForDevice; @override String get name => 'dummy'; @override Future<TargetPlatform> get targetPlatform async => TargetPlatform.tester; @override bool isSupported() => true; @override bool isSupportedForProject(FlutterProject flutterProject) => true; @override Future<void> buildForDevice({ String? mainPath, BuildInfo? buildInfo, }) async { lastBuiltMainPath = mainPath; lastBuildInfo = buildInfo; } // Dummy implementation that just returns the build mode name. @override String? executablePathForDevice(ApplicationPackage package, BuildInfo buildInfo) { if (nullExecutablePathForDevice) { return null; } return buildInfo.mode.cliName; } } class FakeApplicationPackage extends Fake implements ApplicationPackage { } class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils { @override String get name => 'Example'; }
flutter/packages/flutter_tools/test/general.shard/desktop_device_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/desktop_device_test.dart", "repo_id": "flutter", "token_count": 6133 }
780
// Copyright 2014 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:file/memory.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/user_messages.dart'; import 'package:flutter_tools/src/doctor.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/version.dart'; import 'package:test/fake.dart'; import '../src/common.dart'; import '../src/fake_process_manager.dart'; import '../src/fakes.dart'; /// Matches a doctor validation result. Matcher _matchDoctorValidation({ required ValidationType validationType, required String statusInfo, required Object messages }) { return const TypeMatcher<ValidationResult>() .having((ValidationResult result) => result.type, 'type', validationType) .having((ValidationResult result) => result.statusInfo, 'statusInfo', statusInfo) .having((ValidationResult result) => result.messages, 'messages', messages); } void main() { testWithoutContext('FlutterValidator shows an error message if gen_snapshot is ' 'downloaded and exits with code 1', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Artifacts artifacts = Artifacts.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( localeName: 'en_US.UTF-8', environment: <String, String>{}, ), flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: artifacts, fileSystem: fileSystem, flutterRoot: () => '/sdk/flutter', operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['Artifact.genSnapshot'], exitCode: 1, ), ]) ); fileSystem.file(artifacts.getArtifactPath(Artifact.genSnapshot)).createSync(recursive: true); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage.error( 'Downloaded executables cannot execute on host.\n' 'See https://github.com/flutter/flutter/issues/6207 for more information.\n' 'On Debian/Ubuntu/Mint: sudo apt-get install lib32stdc++6\n' 'On Fedora: dnf install libstdc++.i686\n' 'On Arch: pacman -S lib32-gcc-libs\n', ), ])), ); }); testWithoutContext('FlutterValidator shows an error message if Rosetta is needed', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Artifacts artifacts = Artifacts.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( operatingSystem: 'macos', localeName: 'en_US.UTF-8', environment: <String, String>{}, ), flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: artifacts, fileSystem: fileSystem, flutterRoot: () => 'sdk/flutter', operatingSystemUtils: FakeOperatingSystemUtils(name: 'macOS', hostPlatform: HostPlatform.darwin_arm64), processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['Artifact.genSnapshot'], exitCode: 1, ), ]) ); fileSystem.file(artifacts.getArtifactPath(Artifact.genSnapshot)).createSync(recursive: true); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on macOS, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage.error( 'Downloaded executables cannot execute on host.\n' 'See https://github.com/flutter/flutter/issues/6207 for more information.\n' 'Flutter requires the Rosetta translation environment on ARM Macs. Try running:\n' ' sudo softwareupdate --install-rosetta --agree-to-license\n' ), ])), ); }); testWithoutContext('FlutterValidator does not run gen_snapshot binary check if it is not already downloaded', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( operatingSystem: 'windows', localeName: 'en_US.UTF-8', environment: <String, String>{}, ), flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Windows'), processManager: FakeProcessManager.empty(), flutterRoot: () => '/sdk/flutter', ); // gen_snapshot is downloaded on demand, and the doctor should not // fail if the gen_snapshot binary is not present. expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Windows, locale en_US.UTF-8', messages: anything, )); }); testWithoutContext('FlutterValidator handles exception thrown by version checking', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(operatingSystem: 'windows', localeName: 'en_US.UTF-8'), flutterVersion: () => FakeThrowingFlutterVersion(), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Windows'), processManager: FakeProcessManager.empty(), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 0.0.0, on Windows, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage('Flutter version 0.0.0 on channel beta at /sdk/flutter'), ValidationMessage.error('version error'), ]), )); }); testWithoutContext('FlutterValidator shows mirrors on pub and flutter cloud storage', () async { final FakeFlutterVersion flutterVersion = FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', ); final Platform platform = FakePlatform( operatingSystem: 'windows', localeName: 'en_US.UTF-8', environment: <String, String>{ 'PUB_HOSTED_URL': 'https://example.com/pub', 'FLUTTER_STORAGE_BASE_URL': 'https://example.com/flutter', }, ); final MemoryFileSystem fileSystem = MemoryFileSystem.test(); final Artifacts artifacts = Artifacts.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: platform, flutterVersion: () => flutterVersion, devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: artifacts, fileSystem: fileSystem, processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Windows'), flutterRoot: () => '/sdk/flutter' ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Windows, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage('Pub download mirror https://example.com/pub'), ValidationMessage('Flutter download mirror https://example.com/flutter'), ]) )); }); testWithoutContext('FlutterValidator shows FLUTTER_GIT_URL when set and fails if upstream is not the same', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform( localeName: 'en_US.UTF-8', environment: <String, String> { 'FLUTTER_GIT_URL': 'https://githubmirror.com/flutter.git', }, ), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(const <ValidationMessage>[ ValidationMessage.hint('Upstream repository https://github.com/flutter/flutter.git is not the same as FLUTTER_GIT_URL'), ValidationMessage('FLUTTER_GIT_URL = https://githubmirror.com/flutter.git'), ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); }); testWithoutContext('FlutterValidator fails when channel is unknown', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( branch: 'unknown', frameworkVersion: '1.0.0', ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel [user-branch], 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Flutter version 1.0.0 on channel [user-branch] at /sdk/flutter\n' 'Currently on an unknown channel. Run `flutter channel` to switch to an official channel.\n' "If that doesn't fix the issue, reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install." ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); }); testWithoutContext('FlutterValidator fails when framework version is unknown', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '0.0.0-unknown', branch: 'beta', ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 0.0.0-unknown, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Flutter version 0.0.0-unknown on channel beta at /sdk/flutter\n' 'Cannot resolve current version, possibly due to local changes.\n' 'Reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.' ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); }); group('FlutterValidator shows flutter upstream remote', () { testWithoutContext('standard url', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: contains(const ValidationMessage('Upstream repository https://github.com/flutter/flutter.git')), )); }); testWithoutContext('non-standard url', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', repositoryUrl: 'https://githubmirror.com/flutter.git' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => 'sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Upstream repository https://githubmirror.com/flutter.git is not a standard remote.\n' 'Set environment variable "FLUTTER_GIT_URL" to ' 'https://githubmirror.com/flutter.git to dismiss this error.' ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); }); testWithoutContext('as unknown if upstream is null', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta', repositoryUrl: null, ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => 'sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: containsAll(<ValidationMessage>[ const ValidationMessage.hint( 'Unknown upstream repository.\n' 'Reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.' ), const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' ), ]), )); }); }); testWithoutContext('Do not show the message for intentional errors if FlutterValidator passes', () async { final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils(name: 'Linux'), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: isNot( contains(const ValidationMessage( 'If those were intentional, you can disregard the above warnings; however it is ' 'recommended to use "git" directly to perform update checks and upgrades.' )), ), )); }); testWithoutContext('detects no flutter and dart on path', () async { const String flutterRoot = 'sdk/flutter'; final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: MemoryFileSystem.test(), processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils( name: 'Linux', whichLookup: const <String, File>{}, ), flutterRoot: () => flutterRoot, ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: contains(const ValidationMessage.hint( 'The flutter binary is not on your path. Consider adding $flutterRoot/bin to your path.', )), )); }); testWithoutContext('allows case differences in paths on Windows', () async { const String flutterRoot = r'c:\path\to\flutter-sdk'; const String osName = 'Microsoft Windows'; final MemoryFileSystem fs = MemoryFileSystem.test( style: FileSystemStyle.windows, ); // The windows' file system is not case sensitive, so changing the case // here should not matter. final File flutterBinary = fs.file('${flutterRoot.toUpperCase()}\\bin\\flutter') ..createSync(recursive: true); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(operatingSystem: 'windows', localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.empty(), operatingSystemUtils: FakeOperatingSystemUtils( name: osName, whichLookup: <String, File>{ 'flutter': flutterBinary, }, ), flutterRoot: () => flutterRoot, ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on $osName, locale en_US.UTF-8', messages: everyElement(isA<ValidationMessage>().having( (ValidationMessage message) => message.message, 'message', isNot(contains('Warning: `flutter` on your path resolves to')), )), )); }); testWithoutContext('allows different separator types in paths on Windows', () async { const String flutterRoot = r'c:\path\to\flutter-sdk'; const String osName = 'Microsoft Windows'; final MemoryFileSystem fs = MemoryFileSystem.test( style: FileSystemStyle.windows, ); const String filePath = '$flutterRoot\\bin\\flutter'; // force posix style path separators final File flutterBinary = fs.file(filePath.replaceAll(r'\', '/')) ..createSync(recursive: true); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(operatingSystem: 'windows', localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.empty(), operatingSystemUtils: FakeOperatingSystemUtils( name: osName, whichLookup: <String, File>{ 'flutter': flutterBinary, }, ), flutterRoot: () => flutterRoot, ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on $osName, locale en_US.UTF-8', messages: everyElement(isA<ValidationMessage>().having( (ValidationMessage message) => message.message, 'message', isNot(contains('Warning: `flutter` on your path resolves to')), )), )); }); testWithoutContext('detects flutter and dart from outside flutter sdk', () async { final FileSystem fs = MemoryFileSystem.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils( name: 'Linux', whichLookup: <String, File>{ 'flutter': fs.file('/sdk/flutter-beta')..createSync(recursive: true), 'dart': fs.file('/sdk/flutter-beta')..createSync(recursive: true), }, ), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.partial, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: contains(const ValidationMessage.hint( 'Warning: `flutter` on your path resolves to /sdk/flutter-beta, which ' 'is not inside your current Flutter SDK checkout at /sdk/flutter. ' 'Consider adding /sdk/flutter/bin to the front of your path.', )), )); }); testWithoutContext('no warnings if flutter & dart binaries are inside the Flutter SDK', () async { final FileSystem fs = MemoryFileSystem.test(); final FlutterValidator flutterValidator = FlutterValidator( platform: FakePlatform(localeName: 'en_US.UTF-8'), flutterVersion: () => FakeFlutterVersion( frameworkVersion: '1.0.0', branch: 'beta' ), devToolsVersion: () => '2.8.0', userMessages: UserMessages(), artifacts: Artifacts.test(), fileSystem: fs, processManager: FakeProcessManager.any(), operatingSystemUtils: FakeOperatingSystemUtils( name: 'Linux', whichLookup: <String, File>{ 'flutter': fs.file('/sdk/flutter/bin/flutter')..createSync(recursive: true), 'dart': fs.file('/sdk/flutter/bin/dart')..createSync(recursive: true), }, ), flutterRoot: () => '/sdk/flutter', ); expect(await flutterValidator.validate(), _matchDoctorValidation( validationType: ValidationType.success, statusInfo: 'Channel beta, 1.0.0, on Linux, locale en_US.UTF-8', messages: isNot(contains(isA<ValidationMessage>().having( (ValidationMessage message) => message.message, 'message', contains('Consider adding /sdk/flutter/bin to the front of your path'), ))), )); }); } class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils { FakeOperatingSystemUtils({ required this.name, this.hostPlatform = HostPlatform.linux_x64, this.whichLookup, FileSystem? fs, }) { fs ??= MemoryFileSystem.test(); whichLookup ??= <String, File>{ 'flutter': fs.file('/sdk/flutter/bin/flutter')..createSync(recursive: true), 'dart': fs.file('/sdk/flutter/bin/dart')..createSync(recursive: true), }; } /// A map of [File]s that calls to [which] will return. Map<String, File>? whichLookup; @override File? which(String execName) => whichLookup![execName]; @override final String name; @override final HostPlatform hostPlatform; } class FakeThrowingFlutterVersion extends FakeFlutterVersion { @override String get channel => 'beta'; @override String get frameworkCommitDate { throw VersionCheckError('version error'); } }
flutter/packages/flutter_tools/test/general.shard/flutter_validator_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/flutter_validator_test.dart", "repo_id": "flutter", "token_count": 9911 }
781
// Copyright 2014 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' as io; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/version.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/device_port_forwarder.dart'; import 'package:flutter_tools/src/ios/application_package.dart'; import 'package:flutter_tools/src/ios/core_devices.dart'; import 'package:flutter_tools/src/ios/devices.dart'; import 'package:flutter_tools/src/ios/ios_deploy.dart'; import 'package:flutter_tools/src/ios/ios_workflow.dart'; import 'package:flutter_tools/src/ios/iproxy.dart'; import 'package:flutter_tools/src/ios/mac.dart'; import 'package:flutter_tools/src/ios/xcode_debug.dart'; import 'package:flutter_tools/src/macos/xcdevice.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; void main() { final FakePlatform macPlatform = FakePlatform(operatingSystem: 'macos'); final FakePlatform linuxPlatform = FakePlatform(); final FakePlatform windowsPlatform = FakePlatform(operatingSystem: 'windows'); group('IOSDevice', () { final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform]; late Cache cache; late Logger logger; late IOSDeploy iosDeploy; late IMobileDevice iMobileDevice; late FileSystem fileSystem; late IOSCoreDeviceControl coreDeviceControl; late XcodeDebug xcodeDebug; setUp(() { final Artifacts artifacts = Artifacts.test(); cache = Cache.test(processManager: FakeProcessManager.any()); logger = BufferLogger.test(); fileSystem = MemoryFileSystem.test(); iosDeploy = IOSDeploy( artifacts: artifacts, cache: cache, logger: logger, platform: macPlatform, processManager: FakeProcessManager.any(), ); iMobileDevice = IMobileDevice( artifacts: artifacts, cache: cache, logger: logger, processManager: FakeProcessManager.any(), ); coreDeviceControl = FakeIOSCoreDeviceControl(); xcodeDebug = FakeXcodeDebug(); }); testWithoutContext('successfully instantiates on Mac OS', () { final IOSDevice device = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', sdkVersion: '13.3', cpuArchitecture: DarwinArch.arm64, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); expect(device.isSupported(), isTrue); }); testWithoutContext('32-bit devices are unsupported', () { final IOSDevice device = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.armv7, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); expect(device.isSupported(), isFalse); }); testWithoutContext('parses major version', () { expect(IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '1.0.0', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).majorSdkVersion, 1); expect(IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '13.1.1', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).majorSdkVersion, 13); expect(IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '10', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).majorSdkVersion, 10); expect(IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '0', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).majorSdkVersion, 0); expect(IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: 'bogus', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).majorSdkVersion, 0); }); testWithoutContext('parses sdk version', () { Version? sdkVersion = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '13.3.1', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).sdkVersion; Version expectedVersion = Version(13, 3, 1, text: '13.3.1'); expect(sdkVersion, isNotNull); expect(sdkVersion!.toString(), expectedVersion.toString()); expect(sdkVersion.compareTo(expectedVersion), 0); sdkVersion = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '13.3.1 (20ADBC)', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).sdkVersion; expectedVersion = Version(13, 3, 1, text: '13.3.1 (20ADBC)'); expect(sdkVersion, isNotNull); expect(sdkVersion!.toString(), expectedVersion.toString()); expect(sdkVersion.compareTo(expectedVersion), 0); sdkVersion = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '16.4.1(a) (20ADBC)', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).sdkVersion; expectedVersion = Version(16, 4, 1, text: '16.4.1(a) (20ADBC)'); expect(sdkVersion, isNotNull); expect(sdkVersion!.toString(), expectedVersion.toString()); expect(sdkVersion.compareTo(expectedVersion), 0); sdkVersion = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: '0', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).sdkVersion; expectedVersion = Version(0, 0, 0, text: '0'); expect(sdkVersion, isNotNull); expect(sdkVersion!.toString(), expectedVersion.toString()); expect(sdkVersion.compareTo(expectedVersion), 0); sdkVersion = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).sdkVersion; expect(sdkVersion, isNull); sdkVersion = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', cpuArchitecture: DarwinArch.arm64, sdkVersion: 'bogus', connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ).sdkVersion; expect(sdkVersion, isNull); }); testWithoutContext('has build number in sdkNameAndVersion', () async { final IOSDevice device = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', sdkVersion: '13.3 17C54', cpuArchitecture: DarwinArch.arm64, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); expect(await device.sdkNameAndVersion,'iOS 13.3 17C54'); }); testWithoutContext('Supports debug, profile, and release modes', () { final IOSDevice device = IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', sdkVersion: '13.3', cpuArchitecture: DarwinArch.arm64, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); expect(device.supportsRuntimeMode(BuildMode.debug), true); expect(device.supportsRuntimeMode(BuildMode.profile), true); expect(device.supportsRuntimeMode(BuildMode.release), true); expect(device.supportsRuntimeMode(BuildMode.jitRelease), false); }); for (final Platform platform in unsupportedPlatforms) { testWithoutContext('throws UnsupportedError exception if instantiated on ${platform.operatingSystem}', () { expect( () { IOSDevice( 'device-123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: platform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', sdkVersion: '13.3', cpuArchitecture: DarwinArch.arm64, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); }, throwsAssertionError, ); }); } group('.dispose()', () { late IOSDevice device; late FakeIOSApp appPackage1; late FakeIOSApp appPackage2; late IOSDeviceLogReader logReader1; late IOSDeviceLogReader logReader2; late FakeProcess process1; late FakeProcess process2; late FakeProcess process3; late IOSDevicePortForwarder portForwarder; late ForwardedPort forwardedPort; late Cache cache; late Logger logger; late IOSDeploy iosDeploy; late FileSystem fileSystem; late IProxy iproxy; IOSDevicePortForwarder createPortForwarder( ForwardedPort forwardedPort, IOSDevice device) { iproxy = IProxy.test(logger: logger, processManager: FakeProcessManager.any()); final IOSDevicePortForwarder portForwarder = IOSDevicePortForwarder( id: device.id, logger: logger, operatingSystemUtils: OperatingSystemUtils( fileSystem: fileSystem, logger: logger, platform: FakePlatform(operatingSystem: 'macos'), processManager: FakeProcessManager.any(), ), iproxy: iproxy, ); portForwarder.addForwardedPorts(<ForwardedPort>[forwardedPort]); return portForwarder; } IOSDeviceLogReader createLogReader( IOSDevice device, IOSApp appPackage, Process process) { final IOSDeviceLogReader logReader = IOSDeviceLogReader.create( device: device, app: appPackage, iMobileDevice: IMobileDevice.test(processManager: FakeProcessManager.any()), ); logReader.idevicesyslogProcess = process; return logReader; } setUp(() { appPackage1 = FakeIOSApp('flutterApp1'); appPackage2 = FakeIOSApp('flutterApp2'); process1 = FakeProcess(); process2 = FakeProcess(); process3 = FakeProcess(); forwardedPort = ForwardedPort.withContext(123, 456, process3); cache = Cache.test( processManager: FakeProcessManager.any(), ); fileSystem = MemoryFileSystem.test(); logger = BufferLogger.test(); iosDeploy = IOSDeploy( artifacts: Artifacts.test(), cache: cache, logger: logger, platform: macPlatform, processManager: FakeProcessManager.any(), ); }); testWithoutContext('kills all log readers & port forwarders', () async { device = IOSDevice( '123', iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), fileSystem: fileSystem, logger: logger, platform: macPlatform, iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, name: 'iPhone 1', sdkVersion: '13.3', cpuArchitecture: DarwinArch.arm64, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); logReader1 = createLogReader(device, appPackage1, process1); logReader2 = createLogReader(device, appPackage2, process2); portForwarder = createPortForwarder(forwardedPort, device); device.setLogReader(appPackage1, logReader1); device.setLogReader(appPackage2, logReader2); device.portForwarder = portForwarder; await device.dispose(); expect(process1.killed, true); expect(process2.killed, true); expect(process3.killed, true); }); }); }); group('polling', () { late FakeXcdevice xcdevice; late Cache cache; late FakeProcessManager fakeProcessManager; late BufferLogger logger; late IOSDeploy iosDeploy; late IMobileDevice iMobileDevice; late IOSWorkflow iosWorkflow; late IOSCoreDeviceControl coreDeviceControl; late XcodeDebug xcodeDebug; late IOSDevice device1; late IOSDevice device2; setUp(() { xcdevice = FakeXcdevice(); final Artifacts artifacts = Artifacts.test(); cache = Cache.test(processManager: FakeProcessManager.any()); logger = BufferLogger.test(); iosWorkflow = FakeIOSWorkflow(); fakeProcessManager = FakeProcessManager.any(); iosDeploy = IOSDeploy( artifacts: artifacts, cache: cache, logger: logger, platform: macPlatform, processManager: fakeProcessManager, ); iMobileDevice = IMobileDevice( artifacts: artifacts, cache: cache, processManager: fakeProcessManager, logger: logger, ); coreDeviceControl = FakeIOSCoreDeviceControl(); xcodeDebug = FakeXcodeDebug(); device1 = IOSDevice( 'd83d5bc53967baa0ee18626ba87b6254b2ab5418', name: 'Paired iPhone', sdkVersion: '13.3', cpuArchitecture: DarwinArch.arm64, iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, logger: logger, platform: macPlatform, fileSystem: MemoryFileSystem.test(), connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); device2 = IOSDevice( '00008027-00192736010F802E', name: 'iPad Pro', sdkVersion: '13.3', cpuArchitecture: DarwinArch.arm64, iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, logger: logger, platform: macPlatform, fileSystem: MemoryFileSystem.test(), connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); }); testWithoutContext('start polling without Xcode', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = false; await iosDevices.startPolling(); expect(xcdevice.getAvailableIOSDevicesCount, 0); }); testWithoutContext('start polling', () async { final TestIOSDevices iosDevices = TestIOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.devices ..add(<IOSDevice>[]) ..add(<IOSDevice>[device1, device2]); int addedCount = 0; final Completer<void> added = Completer<void>(); iosDevices.onAdded.listen((Device device) { addedCount++; // 2 devices will be added. // Will throw over-completion if called more than twice. if (addedCount >= 2) { added.complete(); } }); final Completer<void> removed = Completer<void>(); iosDevices.onRemoved.listen((Device device) { // Will throw over-completion if called more than once. removed.complete(); }); await iosDevices.startPolling(); expect(xcdevice.getAvailableIOSDevicesCount, 1); expect(iosDevices.deviceNotifier!.items, isEmpty); expect(xcdevice.deviceEventController.hasListener, isTrue); xcdevice.deviceEventController.add( XCDeviceEventNotification( XCDeviceEvent.attach, XCDeviceEventInterface.usb, 'd83d5bc53967baa0ee18626ba87b6254b2ab5418' ), ); await added.future; expect(iosDevices.deviceNotifier!.items.length, 2); expect(iosDevices.deviceNotifier!.items, contains(device1)); expect(iosDevices.deviceNotifier!.items, contains(device2)); expect(iosDevices.eventsReceived, 1); iosDevices.resetEventCompleter(); xcdevice.deviceEventController.add( XCDeviceEventNotification( XCDeviceEvent.attach, XCDeviceEventInterface.wifi, 'd83d5bc53967baa0ee18626ba87b6254b2ab5418' ), ); await iosDevices.receivedEvent.future; expect(iosDevices.deviceNotifier!.items.length, 2); expect(iosDevices.deviceNotifier!.items, contains(device1)); expect(iosDevices.deviceNotifier!.items, contains(device2)); expect(iosDevices.eventsReceived, 2); iosDevices.resetEventCompleter(); xcdevice.deviceEventController.add( XCDeviceEventNotification( XCDeviceEvent.detach, XCDeviceEventInterface.usb, 'd83d5bc53967baa0ee18626ba87b6254b2ab5418' ), ); await iosDevices.receivedEvent.future; expect(iosDevices.deviceNotifier!.items.length, 2); expect(iosDevices.deviceNotifier!.items, contains(device1)); expect(iosDevices.deviceNotifier!.items, contains(device2)); expect(iosDevices.eventsReceived, 3); xcdevice.deviceEventController.add( XCDeviceEventNotification( XCDeviceEvent.detach, XCDeviceEventInterface.wifi, 'd83d5bc53967baa0ee18626ba87b6254b2ab5418' ), ); await removed.future; expect(iosDevices.deviceNotifier!.items, <Device>[device2]); expect(iosDevices.eventsReceived, 4); iosDevices.resetEventCompleter(); xcdevice.deviceEventController.add( XCDeviceEventNotification( XCDeviceEvent.detach, XCDeviceEventInterface.usb, 'bogus' ), ); await iosDevices.receivedEvent.future; expect(iosDevices.eventsReceived, 5); expect(addedCount, 2); await iosDevices.stopPolling(); expect(xcdevice.deviceEventController.hasListener, isFalse); }); testWithoutContext('polling can be restarted if stream is closed', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.devices.add(<IOSDevice>[]); xcdevice.devices.add(<IOSDevice>[]); final StreamController<XCDeviceEventNotification> rescheduledStream = StreamController<XCDeviceEventNotification>(); unawaited(xcdevice.deviceEventController.done.whenComplete(() { xcdevice.deviceEventController = rescheduledStream; })); await iosDevices.startPolling(); expect(xcdevice.deviceEventController.hasListener, isTrue); expect(xcdevice.getAvailableIOSDevicesCount, 1); // Pretend xcdevice crashed. await xcdevice.deviceEventController.close(); expect(logger.traceText, contains('xcdevice observe stopped')); // Confirm a restart still gets streamed events. await iosDevices.startPolling(); expect(rescheduledStream.hasListener, isTrue); await iosDevices.stopPolling(); expect(rescheduledStream.hasListener, isFalse); }); testWithoutContext('dispose cancels polling subscription', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.devices.add(<IOSDevice>[]); await iosDevices.startPolling(); expect(iosDevices.deviceNotifier!.items, isEmpty); expect(xcdevice.deviceEventController.hasListener, isTrue); iosDevices.dispose(); expect(xcdevice.deviceEventController.hasListener, isFalse); }); final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform]; for (final Platform unsupportedPlatform in unsupportedPlatforms) { testWithoutContext('pollingGetDevices throws Unsupported Operation exception on ${unsupportedPlatform.operatingSystem}', () async { final IOSDevices iosDevices = IOSDevices( platform: unsupportedPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = false; expect( () async { await iosDevices.pollingGetDevices(); }, throwsUnsupportedError, ); }); } testWithoutContext('pollingGetDevices returns attached devices', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.devices.add(<IOSDevice>[device1]); final List<Device> devices = await iosDevices.pollingGetDevices(); expect(devices, hasLength(1)); expect(devices.first, same(device1)); }); }); group('getDiagnostics', () { late FakeXcdevice xcdevice; late IOSWorkflow iosWorkflow; late Logger logger; setUp(() { xcdevice = FakeXcdevice(); iosWorkflow = FakeIOSWorkflow(); logger = BufferLogger.test(); }); final List<Platform> unsupportedPlatforms = <Platform>[linuxPlatform, windowsPlatform]; for (final Platform unsupportedPlatform in unsupportedPlatforms) { testWithoutContext('throws returns platform diagnostic exception on ${unsupportedPlatform.operatingSystem}', () async { final IOSDevices iosDevices = IOSDevices( platform: unsupportedPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = false; expect((await iosDevices.getDiagnostics()).first, 'Control of iOS devices or simulators only supported on macOS.'); }); } testWithoutContext('returns diagnostics', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.diagnostics.add('Generic pairing error'); final List<String> diagnostics = await iosDevices.getDiagnostics(); expect(diagnostics, hasLength(1)); expect(diagnostics.first, 'Generic pairing error'); }); }); group('waitForDeviceToConnect', () { late FakeXcdevice xcdevice; late Cache cache; late FakeProcessManager fakeProcessManager; late BufferLogger logger; late IOSDeploy iosDeploy; late IMobileDevice iMobileDevice; late IOSWorkflow iosWorkflow; late IOSCoreDeviceControl coreDeviceControl; late XcodeDebug xcodeDebug; late IOSDevice notConnected1; setUp(() { xcdevice = FakeXcdevice(); final Artifacts artifacts = Artifacts.test(); cache = Cache.test(processManager: FakeProcessManager.any()); logger = BufferLogger.test(); iosWorkflow = FakeIOSWorkflow(); fakeProcessManager = FakeProcessManager.any(); iosDeploy = IOSDeploy( artifacts: artifacts, cache: cache, logger: logger, platform: macPlatform, processManager: fakeProcessManager, ); iMobileDevice = IMobileDevice( artifacts: artifacts, cache: cache, processManager: fakeProcessManager, logger: logger, ); coreDeviceControl = FakeIOSCoreDeviceControl(); xcodeDebug = FakeXcodeDebug(); notConnected1 = IOSDevice( '00000001-0000000000000000', name: 'iPad', sdkVersion: '13.3', cpuArchitecture: DarwinArch.arm64, iProxy: IProxy.test(logger: logger, processManager: FakeProcessManager.any()), iosDeploy: iosDeploy, iMobileDevice: iMobileDevice, coreDeviceControl: coreDeviceControl, xcodeDebug: xcodeDebug, logger: logger, platform: macPlatform, fileSystem: MemoryFileSystem.test(), connectionInterface: DeviceConnectionInterface.attached, isConnected: false, isPaired: true, devModeEnabled: true, isCoreDevice: false, ); }); testWithoutContext('wait for device to connect via wifi', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.waitForDeviceEvent = XCDeviceEventNotification( XCDeviceEvent.attach, XCDeviceEventInterface.wifi, '00000001-0000000000000000' ); final Device? device = await iosDevices.waitForDeviceToConnect( notConnected1, logger ); expect(device?.isConnected, isTrue); expect(device?.connectionInterface, DeviceConnectionInterface.wireless); }); testWithoutContext('wait for device to connect via usb', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.waitForDeviceEvent = XCDeviceEventNotification( XCDeviceEvent.attach, XCDeviceEventInterface.usb, '00000001-0000000000000000' ); final Device? device = await iosDevices.waitForDeviceToConnect( notConnected1, logger ); expect(device?.isConnected, isTrue); expect(device?.connectionInterface, DeviceConnectionInterface.attached); }); testWithoutContext('wait for device returns null', () async { final IOSDevices iosDevices = IOSDevices( platform: macPlatform, xcdevice: xcdevice, iosWorkflow: iosWorkflow, logger: logger, ); xcdevice.isInstalled = true; xcdevice.waitForDeviceEvent = null; final Device? device = await iosDevices.waitForDeviceToConnect( notConnected1, logger ); expect(device, isNull); }); }); } class FakeIOSApp extends Fake implements IOSApp { FakeIOSApp(this.name); @override final String name; } class TestIOSDevices extends IOSDevices { TestIOSDevices({required super.platform, required super.xcdevice, required super.iosWorkflow, required super.logger,}); Completer<void> receivedEvent = Completer<void>(); int eventsReceived = 0; void resetEventCompleter() { receivedEvent = Completer<void>(); } @override Future<void> onDeviceEvent(XCDeviceEventNotification event) async { await super.onDeviceEvent(event); if (!receivedEvent.isCompleted) { receivedEvent.complete(); } eventsReceived++; return; } } class FakeIOSWorkflow extends Fake implements IOSWorkflow { } class FakeXcdevice extends Fake implements XCDevice { int getAvailableIOSDevicesCount = 0; final List<List<IOSDevice>> devices = <List<IOSDevice>>[]; final List<String> diagnostics = <String>[]; StreamController<XCDeviceEventNotification> deviceEventController = StreamController<XCDeviceEventNotification>(); XCDeviceEventNotification? waitForDeviceEvent; @override bool isInstalled = true; @override Future<List<String>> getDiagnostics() async { return diagnostics; } @override Stream<XCDeviceEventNotification> observedDeviceEvents() { return deviceEventController.stream; } @override Future<List<IOSDevice>> getAvailableIOSDevices({Duration? timeout}) async { return devices[getAvailableIOSDevicesCount++]; } @override Future<XCDeviceEventNotification?> waitForDeviceToConnect(String deviceId) async { final XCDeviceEventNotification? waitEvent = waitForDeviceEvent; if (waitEvent != null) { return XCDeviceEventNotification(waitEvent.eventType, waitEvent.eventInterface, waitEvent.deviceIdentifier); } else { return null; } } } class FakeProcess extends Fake implements Process { bool killed = false; @override bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) { killed = true; return true; } } class FakeXcodeDebug extends Fake implements XcodeDebug { @override bool get debugStarted => false; } class FakeIOSCoreDeviceControl extends Fake implements IOSCoreDeviceControl {}
flutter/packages/flutter_tools/test/general.shard/ios/devices_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/ios/devices_test.dart", "repo_id": "flutter", "token_count": 14910 }
782
// Copyright 2014 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:file/memory.dart'; import 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/common.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/native_assets/android/native_assets.dart'; import 'package:native_assets_cli/native_assets_cli_internal.dart' as native_assets_cli; import 'package:native_assets_cli/native_assets_cli_internal.dart' hide BuildMode, Target; import 'package:package_config/package_config_types.dart'; import '../../../src/common.dart'; import '../../../src/context.dart'; import '../../../src/fakes.dart'; import '../fake_native_assets_build_runner.dart'; void main() { late FakeProcessManager processManager; late Environment environment; late Artifacts artifacts; late FileSystem fileSystem; late BufferLogger logger; late Uri projectUri; setUp(() { processManager = FakeProcessManager.empty(); logger = BufferLogger.test(); artifacts = Artifacts.test(); fileSystem = MemoryFileSystem.test(); environment = Environment.test( fileSystem.currentDirectory, inputs: <String, String>{}, artifacts: artifacts, processManager: processManager, fileSystem: fileSystem, logger: logger, ); environment.buildDir.createSync(recursive: true); projectUri = environment.projectDir.uri; }); testUsingContext('dry run with no package config', overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.empty(), }, () async { expect( await dryRunNativeAssetsAndroid( projectUri: projectUri, fileSystem: fileSystem, buildRunner: FakeNativeAssetsBuildRunner( hasPackageConfigResult: false, ), ), null, ); expect( (globals.logger as BufferLogger).traceText, contains('No package config found. Skipping native assets compilation.'), ); }); testUsingContext('build with no package config', overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.empty(), }, () async { await buildNativeAssetsAndroid( androidArchs: <AndroidArch>[AndroidArch.arm64_v8a], targetAndroidNdkApi: 21, projectUri: projectUri, buildMode: BuildMode.debug, fileSystem: fileSystem, yamlParentDirectory: environment.buildDir.uri, buildRunner: FakeNativeAssetsBuildRunner( hasPackageConfigResult: false, ), ); expect( (globals.logger as BufferLogger).traceText, contains('No package config found. Skipping native assets compilation.'), ); }); testUsingContext('dry run with assets but not enabled', overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); expect( () => dryRunNativeAssetsAndroid( projectUri: projectUri, fileSystem: fileSystem, buildRunner: FakeNativeAssetsBuildRunner( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], ), ), throwsToolExit( message: 'Package(s) bar require the native assets feature to be enabled. ' 'Enable using `flutter config --enable-native-assets`.', ), ); }); testUsingContext('dry run with assets', overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); final Uri? nativeAssetsYaml = await dryRunNativeAssetsAndroid( projectUri: projectUri, fileSystem: fileSystem, buildRunner: FakeNativeAssetsBuildRunner( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], dryRunResult: FakeNativeAssetsBuilderResult( assets: <Asset>[ Asset( id: 'package:bar/bar.dart', linkMode: LinkMode.dynamic, target: native_assets_cli.Target.macOSArm64, path: AssetAbsolutePath(Uri.file('libbar.so')), ), Asset( id: 'package:bar/bar.dart', linkMode: LinkMode.dynamic, target: native_assets_cli.Target.macOSX64, path: AssetAbsolutePath(Uri.file('libbar.so')), ), ], ), ), ); expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder(<String>[ 'Dry running native assets for android.', 'Dry running native assets for android done.', ]), ); expect( nativeAssetsYaml, projectUri.resolve('build/native_assets/android/native_assets.yaml'), ); expect( await fileSystem.file(nativeAssetsYaml).readAsString(), contains('package:bar/bar.dart'), ); }); testUsingContext('build with assets but not enabled', () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); expect( () => buildNativeAssetsAndroid( androidArchs: <AndroidArch>[AndroidArch.arm64_v8a], targetAndroidNdkApi: 21, projectUri: projectUri, buildMode: BuildMode.debug, fileSystem: fileSystem, yamlParentDirectory: environment.buildDir.uri, buildRunner: FakeNativeAssetsBuildRunner( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], ), ), throwsToolExit( message: 'Package(s) bar require the native assets feature to be enabled. ' 'Enable using `flutter config --enable-native-assets`.', ), ); }); testUsingContext('build no assets', overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); await buildNativeAssetsAndroid( androidArchs: <AndroidArch>[AndroidArch.arm64_v8a], targetAndroidNdkApi: 21, projectUri: projectUri, buildMode: BuildMode.debug, fileSystem: fileSystem, yamlParentDirectory: environment.buildDir.uri, buildRunner: FakeNativeAssetsBuildRunner( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], ), ); expect( environment.buildDir.childFile('native_assets.yaml'), exists, ); }); testUsingContext('build with assets', skip: const LocalPlatform().isWindows, // [intended] Backslashes in commands, but we will never run these commands on Windows. overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); final File dylibAfterCompiling = fileSystem.file('libbar.so'); // The mock doesn't create the file, so create it here. await dylibAfterCompiling.create(); await buildNativeAssetsAndroid( androidArchs: <AndroidArch>[AndroidArch.arm64_v8a], targetAndroidNdkApi: 21, projectUri: projectUri, buildMode: BuildMode.debug, fileSystem: fileSystem, yamlParentDirectory: environment.buildDir.uri, buildRunner: FakeNativeAssetsBuildRunner( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], buildResult: FakeNativeAssetsBuilderResult( assets: <Asset>[ Asset( id: 'package:bar/bar.dart', linkMode: LinkMode.dynamic, target: native_assets_cli.Target.androidArm64, path: AssetAbsolutePath(Uri.file('libbar.so')), ), ], ), ), ); expect( (globals.logger as BufferLogger).traceText, stringContainsInOrder(<String>[ 'Building native assets for [android_arm64] debug.', 'Building native assets for [android_arm64] done.', ]), ); expect( environment.buildDir.childFile('native_assets.yaml'), exists, ); }); // Ensure no exceptions for a non installed NDK are thrown if no native // assets have to be build. testUsingContext( 'does not throw if NDK not present but no native assets present', overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.create(recursive: true); await buildNativeAssetsAndroid( androidArchs: <AndroidArch>[AndroidArch.x86_64], targetAndroidNdkApi: 21, projectUri: projectUri, buildMode: BuildMode.debug, fileSystem: fileSystem, buildRunner: _BuildRunnerWithoutNdk(), ); expect( (globals.logger as BufferLogger).traceText, isNot(contains('Building native assets for ')), ); }); testUsingContext('throw if NDK not present and there are native assets', overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); expect( () => buildNativeAssetsAndroid( androidArchs: <AndroidArch>[AndroidArch.arm64_v8a], targetAndroidNdkApi: 21, projectUri: projectUri, buildMode: BuildMode.debug, fileSystem: fileSystem, yamlParentDirectory: environment.buildDir.uri, buildRunner: _BuildRunnerWithoutNdk( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], ), ), throwsToolExit( message: 'Android NDK Clang could not be found.', ), ); }); testUsingContext('Native assets dry run error', overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); expect( () => dryRunNativeAssetsAndroid( projectUri: projectUri, fileSystem: fileSystem, buildRunner: FakeNativeAssetsBuildRunner( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], dryRunResult: const FakeNativeAssetsBuilderResult( success: false, ), ), ), throwsToolExit( message: 'Building native assets failed. See the logs for more details.', ), ); }); testUsingContext('Native assets build error', overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), ProcessManager: () => FakeProcessManager.empty(), }, () async { final File packageConfig = environment.projectDir.childFile('.dart_tool/package_config.json'); await packageConfig.parent.create(); await packageConfig.create(); expect( () => buildNativeAssetsAndroid( androidArchs: <AndroidArch>[AndroidArch.arm64_v8a], targetAndroidNdkApi: 21, projectUri: projectUri, buildMode: BuildMode.debug, fileSystem: fileSystem, yamlParentDirectory: environment.buildDir.uri, buildRunner: FakeNativeAssetsBuildRunner( packagesWithNativeAssetsResult: <Package>[ Package('bar', projectUri), ], buildResult: const FakeNativeAssetsBuilderResult( success: false, ), ), ), throwsToolExit( message: 'Building native assets failed. See the logs for more details.', ), ); }); } class _BuildRunnerWithoutNdk extends FakeNativeAssetsBuildRunner { _BuildRunnerWithoutNdk({ super.packagesWithNativeAssetsResult = const <Package>[], }); @override Future<CCompilerConfig> get ndkCCompilerConfig async => throwToolExit('Android NDK Clang could not be found.'); }
flutter/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/isolated/android/native_assets_test.dart", "repo_id": "flutter", "token_count": 5235 }
783
// Copyright 2014 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_tools/src/base/user_messages.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/macos/cocoapods.dart'; import 'package:flutter_tools/src/macos/cocoapods_validator.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; void main() { group('CocoaPods validation', () { testWithoutContext('Emits installed status when CocoaPods is installed', () async { final CocoaPodsValidator workflow = CocoaPodsValidator(FakeCocoaPods(CocoaPodsStatus.recommended, '1000.0.0'), UserMessages()); final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.success); }); testWithoutContext('Emits missing status when CocoaPods is not installed', () async { final CocoaPodsValidator workflow = CocoaPodsValidator(FakeCocoaPods(CocoaPodsStatus.notInstalled), UserMessages()); final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.missing); }); testWithoutContext('Emits partial status when CocoaPods is installed with unknown version', () async { final CocoaPodsValidator workflow = CocoaPodsValidator(FakeCocoaPods(CocoaPodsStatus.unknownVersion), UserMessages()); final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); }); testWithoutContext('Emits partial status when CocoaPods version is too low', () async { const String currentVersion = '1.4.0'; final CocoaPods fakeCocoaPods = FakeCocoaPods(CocoaPodsStatus.belowRecommendedVersion, currentVersion); final CocoaPodsValidator workflow = CocoaPodsValidator(fakeCocoaPods, UserMessages()); final ValidationResult result = await workflow.validate(); expect(result.type, ValidationType.partial); expect(result.messages.length, 1); final ValidationMessage message = result.messages.first; expect(message.type, ValidationMessageType.hint); expect(message.message, contains('CocoaPods $currentVersion out of date')); expect(message.message, contains('(1.13.0 is recommended)')); expect(message.message, contains('getting-started.html#updating-cocoapods')); }); }); } class FakeCocoaPods extends Fake implements CocoaPods { FakeCocoaPods(this._evaluateCocoaPodsInstallation, [this._cocoaPodsVersionText]); @override Future<CocoaPodsStatus> get evaluateCocoaPodsInstallation async => _evaluateCocoaPodsInstallation; final CocoaPodsStatus _evaluateCocoaPodsInstallation; @override Future<String?> get cocoaPodsVersionText async => _cocoaPodsVersionText; final String? _cocoaPodsVersionText; }
flutter/packages/flutter_tools/test/general.shard/macos/cocoapods_validator_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/macos/cocoapods_validator_test.dart", "repo_id": "flutter", "token_count": 952 }
784
// Copyright 2014 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/memory.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/project_validator.dart'; import 'package:flutter_tools/src/project_validator_result.dart'; import '../src/common.dart'; class ProjectValidatorTaskImpl extends ProjectValidator { @override Future<List<ProjectValidatorResult>> start(FlutterProject project) async { const ProjectValidatorResult error = ProjectValidatorResult( name: 'result_1', value: 'this is an error', status: StatusProjectValidator.error, ); const ProjectValidatorResult success = ProjectValidatorResult( name: 'result_2', value: 'correct', status: StatusProjectValidator.success, ); const ProjectValidatorResult warning = ProjectValidatorResult( name: 'result_3', value: 'this passed', status: StatusProjectValidator.success, warning: 'with a warning' ); return <ProjectValidatorResult>[error, success, warning]; } @override bool supportsProject(FlutterProject project) { return true; } @override String get title => 'Impl'; } void main() { group('ProjectValidatorResult', () { testWithoutContext('success status', () { const ProjectValidatorResult result = ProjectValidatorResult( name: 'name', value: 'value', status: StatusProjectValidator.success, ); expect(result.toString(), 'name: value'); expect(result.status, StatusProjectValidator.success); }); testWithoutContext('success status with warning', () { const ProjectValidatorResult result = ProjectValidatorResult( name: 'name', value: 'value', status: StatusProjectValidator.success, warning: 'my warning' ); expect(result.toString(), 'name: value (warning: my warning)'); expect(result.status, StatusProjectValidator.success); }); testWithoutContext('error status', () { const ProjectValidatorResult result = ProjectValidatorResult( name: 'name', value: 'my error', status: StatusProjectValidator.error, ); expect(result.toString(), 'name: my error'); expect(result.status, StatusProjectValidator.error); }); }); group('ProjectValidatorTask', () { late ProjectValidatorTaskImpl task; setUp(() { task = ProjectValidatorTaskImpl(); }); testWithoutContext('error status', () async { final MemoryFileSystem fs = MemoryFileSystem.test(); final FlutterProject project = FlutterProject.fromDirectoryTest(fs.currentDirectory); final List<ProjectValidatorResult> results = await task.start(project); expect(results.length, 3); expect(results[0].toString(), 'result_1: this is an error'); expect(results[1].toString(), 'result_2: correct'); expect(results[2].toString(), 'result_3: this passed (warning: with a warning)'); }); }); }
flutter/packages/flutter_tools/test/general.shard/project_validator_result_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/project_validator_result_test.dart", "repo_id": "flutter", "token_count": 1068 }
785
// Copyright 2014 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/memory.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/user_messages.dart'; import 'package:flutter_tools/src/runner/local_engine.dart'; import '../../src/common.dart'; const String kEngineRoot = '/flutter/engine'; const String kArbitraryEngineRoot = '/arbitrary/engine'; const String kDotPackages = '.packages'; void main() { testWithoutContext('works if --local-engine is specified and --local-engine-src-path ' 'is determined by sky_engine', () async { final FileSystem fileSystem = MemoryFileSystem.test(); fileSystem .directory('$kArbitraryEngineRoot/src/out/ios_debug/gen/dart-pkg/sky_engine/lib/') .createSync(recursive: true); fileSystem .directory('$kArbitraryEngineRoot/src/out/host_debug') .createSync(recursive: true); fileSystem .file(kDotPackages) .writeAsStringSync('sky_engine:file://$kArbitraryEngineRoot/src/out/ios_debug/gen/dart-pkg/sky_engine/lib/'); fileSystem .file('bin/cache/pkg/sky_engine/lib') .createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: '', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: 'ios_debug', localHostEngine: 'host_debug'), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug', targetEngine: '/arbitrary/engine/src/out/ios_debug', ), ); expect(logger.traceText, contains('Local engine source at /arbitrary/engine/src')); // Verify that this also works if the sky_engine path is a symlink to the engine root. fileSystem.link('/symlink').createSync(kArbitraryEngineRoot); fileSystem .file(kDotPackages) .writeAsStringSync('sky_engine:file:///symlink/src/out/ios_debug/gen/dart-pkg/sky_engine/lib/'); expect( await localEngineLocator.findEnginePath(localEngine: 'ios_debug', localHostEngine: 'host_debug'), matchesEngineBuildPaths( hostEngine: '/symlink/src/out/host_debug', targetEngine: '/symlink/src/out/ios_debug', ), ); expect(logger.traceText, contains('Local engine source at /symlink/src')); }); testWithoutContext('works if --local-engine is specified and --local-engine-src-path ' 'is specified', () async { final FileSystem fileSystem = MemoryFileSystem.test(); // Intentionally do not create a package_config to verify that it is not required. fileSystem.directory('$kArbitraryEngineRoot/src/out/ios_debug').createSync(recursive: true); fileSystem.directory('$kArbitraryEngineRoot/src/out/host_debug').createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: '', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(engineSourcePath: '$kArbitraryEngineRoot/src', localEngine: 'ios_debug', localHostEngine: 'host_debug'), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug', targetEngine: '/arbitrary/engine/src/out/ios_debug', ), ); expect(logger.traceText, contains('Local engine source at /arbitrary/engine/src')); }); testWithoutContext('works if --local-engine is specified and --local-engine-host is specified', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/android_debug_unopt_arm64/') ..createSync(recursive: true); fileSystem.directory('$kArbitraryEngineRoot/src/out/host_debug_unopt_arm64/').createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: localEngine.path, localHostEngine: 'host_debug_unopt_arm64'), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug_unopt_arm64', targetEngine: '/arbitrary/engine/src/out/android_debug_unopt_arm64', ), ); expect(logger.traceText, contains('Local engine source at /arbitrary/engine/src')); }); testWithoutContext('fails if --local-engine-host is omitted', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/android_debug_unopt_arm64/') ..createSync(recursive: true); fileSystem.directory('$kArbitraryEngineRoot/src/out/host_debug_unopt/').createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); await expectLater( localEngineLocator.findEnginePath(localEngine: localEngine.path), throwsToolExit(message: 'You are using a locally built engine (--local-engine) but have not specified --local-engine-host'), ); }); testWithoutContext('works if --local-engine is specified and --local-engine-src-path ' 'is determined by --local-engine', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/ios_debug/') ..createSync(recursive: true); fileSystem.directory('$kArbitraryEngineRoot/src/out/host_debug/').createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: localEngine.path, localHostEngine: 'host_debug'), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug', targetEngine: '/arbitrary/engine/src/out/ios_debug', ), ); expect(logger.traceText, contains('Parsed engine source from local engine as /arbitrary/engine/src')); expect(logger.traceText, contains('Local engine source at /arbitrary/engine/src')); }); testWithoutContext('works if local engine is host engine', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/host_debug/') ..createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: localEngine.path, localHostEngine: localEngine.path), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug', targetEngine: '/arbitrary/engine/src/out/host_debug', ), ); expect(logger.traceText, contains('Local engine source at /arbitrary/engine/src')); }); testWithoutContext('works if local engine is host engine with suffixes', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/host_debug_unopt_arm64/') ..createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: localEngine.path, localHostEngine: localEngine.path), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug_unopt_arm64', targetEngine: '/arbitrary/engine/src/out/host_debug_unopt_arm64', ), ); }); testWithoutContext('works if local engine is simulator', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/ios_debug_sim/') ..createSync(recursive: true); fileSystem .directory('$kArbitraryEngineRoot/src/out/host_debug/') .createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: localEngine.path, localHostEngine: 'host_debug'), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug', targetEngine: '/arbitrary/engine/src/out/ios_debug_sim', ), ); }); testWithoutContext('works if local engine is simulator unoptimized', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/ios_debug_sim_unopt/') ..createSync(recursive: true); fileSystem .directory('$kArbitraryEngineRoot/src/out/host_debug_unopt/') .createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: localEngine.path, localHostEngine: 'host_debug_unopt'), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/host_debug_unopt', targetEngine: '/arbitrary/engine/src/out/ios_debug_sim_unopt', ), ); }); testWithoutContext('fails if host_debug does not exist', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/ios_debug/') ..createSync(recursive: true); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: BufferLogger.test(), userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); await expectToolExitLater( localEngineLocator.findEnginePath(localEngine: localEngine.path, localHostEngine: 'host_debug'), contains('No Flutter engine build found at /arbitrary/engine/src/out/host_debug'), ); }); testWithoutContext('works if --local-engine is specified and --local-engine-src-path ' 'is determined by flutter root', () async { final FileSystem fileSystem = MemoryFileSystem.test(); fileSystem.file(kDotPackages).writeAsStringSync('\n'); fileSystem .directory('$kEngineRoot/src/out/ios_debug') .createSync(recursive: true); fileSystem .directory('$kEngineRoot/src/out/host_debug') .createSync(recursive: true); fileSystem .file('bin/cache/pkg/sky_engine/lib') .createSync(recursive: true); final BufferLogger logger = BufferLogger.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: logger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localEngineLocator.findEnginePath(localEngine: 'ios_debug', localHostEngine: 'host_debug'), matchesEngineBuildPaths( hostEngine: 'flutter/engine/src/out/host_debug', targetEngine: 'flutter/engine/src/out/ios_debug', ), ); expect(logger.traceText, contains('Local engine source at flutter/engine/src')); }); testWithoutContext('fails if --local-engine is specified and --local-engine-src-path ' 'cannot be determined', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final LocalEngineLocator localEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: BufferLogger.test(), userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); await expectToolExitLater( localEngineLocator.findEnginePath(localEngine: '/path/to/nothing', localHostEngine: '/path/to/nothing'), contains('Unable to detect local Flutter engine src directory'), ); }); testWithoutContext('works for local web engine', () async { final FileSystem fileSystem = MemoryFileSystem.test(); final Directory localWasmEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/wasm_whatever/') ..createSync(recursive: true); final Directory localWebEngine = fileSystem .directory('$kArbitraryEngineRoot/src/out/web_whatever/') ..createSync(recursive: true); final BufferLogger wasmLogger = BufferLogger.test(); final LocalEngineLocator localWasmEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: wasmLogger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localWasmEngineLocator.findEnginePath(localEngine: localWasmEngine.path, localHostEngine: localWasmEngine.path), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/wasm_whatever', targetEngine: '/arbitrary/engine/src/out/wasm_whatever', ), ); expect(wasmLogger.traceText, contains('Local engine source at /arbitrary/engine/src')); final BufferLogger webLogger = BufferLogger.test(); final LocalEngineLocator localWebEngineLocator = LocalEngineLocator( fileSystem: fileSystem, flutterRoot: 'flutter/flutter', logger: webLogger, userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); expect( await localWebEngineLocator.findEnginePath(localEngine: localWebEngine.path, localHostEngine: localWebEngine.path), matchesEngineBuildPaths( hostEngine: '/arbitrary/engine/src/out/web_whatever', targetEngine: '/arbitrary/engine/src/out/web_whatever', ), ); expect(webLogger.traceText, contains('Local engine source at /arbitrary/engine/src')); }); test('returns null without throwing if nothing is specified', () async { final LocalEngineLocator localWebEngineLocator = LocalEngineLocator( fileSystem: MemoryFileSystem.test(), flutterRoot: 'flutter/flutter', logger: BufferLogger.test(), userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{}), ); final EngineBuildPaths? paths = await localWebEngineLocator.findEnginePath(); expect(paths, isNull); }); test('throws if nothing is specified but the FLUTTER_ENGINE environment variable is set', () async { final LocalEngineLocator localWebEngineLocator = LocalEngineLocator( fileSystem: MemoryFileSystem.test(), flutterRoot: 'flutter/flutter', logger: BufferLogger.test(), userMessages: UserMessages(), platform: FakePlatform(environment: <String, String>{'FLUTTER_ENGINE': 'blah'}), ); await expectToolExitLater( localWebEngineLocator.findEnginePath(), contains('Unable to detect a Flutter engine build directory in blah'), ); }); } Matcher matchesEngineBuildPaths({ String? hostEngine, String? targetEngine, }) { return const TypeMatcher<EngineBuildPaths>() .having((EngineBuildPaths paths) => paths.hostEngine, 'hostEngine', hostEngine) .having((EngineBuildPaths paths) => paths.targetEngine, 'targetEngine', targetEngine); }
flutter/packages/flutter_tools/test/general.shard/runner/local_engine_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/runner/local_engine_test.dart", "repo_id": "flutter", "token_count": 6181 }
786
// Copyright 2014 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_tools/src/base/terminal.dart'; import 'package:flutter_tools/src/base/utils.dart'; import 'package:flutter_tools/src/base/version.dart'; import '../src/common.dart'; void main() { group('SettingsFile', () { testWithoutContext('parse', () { final SettingsFile file = SettingsFile.parse(''' # ignore comment foo=bar baz=qux '''); expect(file.values['foo'], 'bar'); expect(file.values['baz'], 'qux'); expect(file.values, hasLength(2)); }); }); group('Version', () { testWithoutContext('can parse and compare', () { expect(Version(0, null, null).toString(), equals('0')); expect(const Version.withText(1, 2, 3, 'versionText').toString(), 'versionText'); final Version v1 = Version.parse('1')!; expect(v1.major, equals(1)); expect(v1.minor, equals(0)); expect(v1.patch, equals(0)); expect(v1, greaterThan(Version(0, 0, 0))); final Version v2 = Version.parse('1.2')!; expect(v2.major, equals(1)); expect(v2.minor, equals(2)); expect(v2.patch, equals(0)); final Version v3 = Version.parse('1.2.3')!; expect(v3.major, equals(1)); expect(v3.minor, equals(2)); expect(v3.patch, equals(3)); final Version v4 = Version.parse('1.12')!; expect(v4, greaterThan(v2)); expect(v3, greaterThan(v2)); expect(v2, greaterThan(v1)); final Version v5 = Version(1, 2, 0, text: 'foo'); expect(v5, equals(v2)); expect(Version.parse('Preview2.2'), isNull); }); group('isWithinVersionRange', () { test('unknown not included', () { expect(isWithinVersionRange('unknown', min: '1.0.0', max: '1.1.3'), isFalse); }); test('pre java 8 format included', () { expect(isWithinVersionRange('1.0.0_201', min: '1.0.0', max: '1.1.3'), isTrue); }); test('min included by default', () { expect( isWithinVersionRange('1.0.0', min: '1.0.0', max: '1.1.3'), isTrue); }); test('max included by default', () { expect( isWithinVersionRange('1.1.3', min: '1.0.0', max: '1.1.3'), isTrue); }); test('inclusive min excluded', () { expect( isWithinVersionRange('1.0.0', min: '1.0.0', max: '1.1.3', inclusiveMin: false), isFalse); }); test('inclusive max excluded', () { expect( isWithinVersionRange('1.1.3', min: '1.0.0', max: '1.1.3', inclusiveMax: false), isFalse); }); test('lower value excluded', () { expect( isWithinVersionRange('0.1.0', min: '1.0.0', max: '1.1.3'), isFalse); }); test('higher value excluded', () { expect( isWithinVersionRange('1.1.4', min: '1.0.0', max: '1.1.3'), isFalse); }); test('middle value included', () { expect( isWithinVersionRange('1.1.0', min: '1.0.0', max: '1.1.3'), isTrue); }); }); }); group('Misc', () { testWithoutContext('snakeCase', () async { expect(snakeCase('abc'), equals('abc')); expect(snakeCase('abC'), equals('ab_c')); expect(snakeCase('aBc'), equals('a_bc')); expect(snakeCase('aBC'), equals('a_b_c')); expect(snakeCase('Abc'), equals('abc')); expect(snakeCase('AbC'), equals('ab_c')); expect(snakeCase('ABc'), equals('a_bc')); expect(snakeCase('ABC'), equals('a_b_c')); }); testWithoutContext('kebabCase', () async { expect(kebabCase('abc'), equals('abc')); expect(kebabCase('abC'), equals('ab-c')); expect(kebabCase('aBc'), equals('a-bc')); expect(kebabCase('aBC'), equals('a-b-c')); expect(kebabCase('Abc'), equals('abc')); expect(kebabCase('AbC'), equals('ab-c')); expect(kebabCase('ABc'), equals('a-bc')); expect(kebabCase('ABC'), equals('a-b-c')); }); testWithoutContext('sentenceCase', () async { expect(sentenceCase('abc'), equals('Abc')); expect(sentenceCase('ab_c'), equals('Ab_c')); expect(sentenceCase('a b c'), equals('A b c')); expect(sentenceCase('a B c'), equals('A B c')); expect(sentenceCase('Abc'), equals('Abc')); expect(sentenceCase('ab_c'), equals('Ab_c')); expect(sentenceCase('a_bc'), equals('A_bc')); expect(sentenceCase('a_b_c'), equals('A_b_c')); }); testWithoutContext('snakeCaseToTitleCase', () async { expect(snakeCaseToTitleCase('abc'), equals('Abc')); expect(snakeCaseToTitleCase('ab_c'), equals('Ab C')); expect(snakeCaseToTitleCase('a_b_c'), equals('A B C')); expect(snakeCaseToTitleCase('a_B_c'), equals('A B C')); expect(snakeCaseToTitleCase('Abc'), equals('Abc')); expect(snakeCaseToTitleCase('ab_c'), equals('Ab C')); expect(snakeCaseToTitleCase('a_bc'), equals('A Bc')); expect(snakeCaseToTitleCase('a_b_c'), equals('A B C')); }); }); group('text wrapping', () { const int lineLength = 40; const String longLine = 'This is a long line that needs to be wrapped.'; final String longLineWithNewlines = 'This is a long line with newlines that\n' 'needs to be wrapped.\n\n' '${'0123456789' * 5}'; final String longAnsiLineWithNewlines = '${AnsiTerminal.red}This${AnsiTerminal.resetAll} is a long line with newlines that\n' 'needs to be wrapped.\n\n' '${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}' '${'0123456789' * 3}' '${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}'; const String onlyAnsiSequences = '${AnsiTerminal.red}${AnsiTerminal.resetAll}'; final String indentedLongLineWithNewlines = ' This is an indented long line with newlines that\n' 'needs to be wrapped.\n\tAnd preserves tabs.\n \n ' '${'0123456789' * 5}'; const String shortLine = 'Short line.'; const String indentedLongLine = ' This is an indented long line that needs to be ' 'wrapped and indentation preserved.'; testWithoutContext('does not wrap by default in tests', () { expect(wrapText(longLine, columnWidth: 80, shouldWrap: true), equals(longLine)); }); testWithoutContext('can override wrap preference if preference is off', () { expect(wrapText(longLine, columnWidth: lineLength, shouldWrap: true), equals(''' This is a long line that needs to be wrapped.''')); }); testWithoutContext('can override wrap preference if preference is on', () { expect(wrapText(longLine, shouldWrap: false, columnWidth: 80), equals(longLine)); }); testWithoutContext('does not wrap at all if not told to wrap', () { expect(wrapText(longLine, columnWidth: 80, shouldWrap: false), equals(longLine)); }); testWithoutContext('does not wrap short lines.', () { expect(wrapText(shortLine, columnWidth: lineLength, shouldWrap: true), equals(shortLine)); }); testWithoutContext('able to wrap long lines', () { expect(wrapText(longLine, columnWidth: lineLength, shouldWrap: true), equals(''' This is a long line that needs to be wrapped.''')); }); testWithoutContext('able to handle dynamically changing terminal column size', () { expect(wrapText(longLine, columnWidth: 20, shouldWrap: true), equals(''' This is a long line that needs to be wrapped.''')); expect(wrapText(longLine, columnWidth: lineLength, shouldWrap: true), equals(''' This is a long line that needs to be wrapped.''')); }); testWithoutContext('wrap long lines with no whitespace', () { expect(wrapText('0123456789' * 5, columnWidth: lineLength, shouldWrap: true), equals(''' 0123456789012345678901234567890123456789 0123456789''')); }); testWithoutContext('refuses to wrap to a column smaller than 10 characters', () { expect(wrapText('$longLine ${'0123456789' * 4}', columnWidth: 1, shouldWrap: true), equals(''' This is a long line that needs to be wrapped. 0123456789 0123456789 0123456789 0123456789''')); }); testWithoutContext('preserves indentation', () { expect(wrapText(indentedLongLine, columnWidth: lineLength, shouldWrap: true), equals(''' This is an indented long line that needs to be wrapped and indentation preserved.''')); }); testWithoutContext('preserves indentation and stripping trailing whitespace', () { expect(wrapText('$indentedLongLine ', columnWidth: lineLength, shouldWrap: true), equals(''' This is an indented long line that needs to be wrapped and indentation preserved.''')); }); testWithoutContext('wraps text with newlines', () { expect(wrapText(longLineWithNewlines, columnWidth: lineLength, shouldWrap: true), equals(''' This is a long line with newlines that needs to be wrapped. 0123456789012345678901234567890123456789 0123456789''')); }); testWithoutContext('wraps text with ANSI sequences embedded', () { expect(wrapText(longAnsiLineWithNewlines, columnWidth: lineLength, shouldWrap: true), equals(''' ${AnsiTerminal.red}This${AnsiTerminal.resetAll} is a long line with newlines that needs to be wrapped. ${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}012345678901234567890123456789 ${AnsiTerminal.green}0123456789${AnsiTerminal.resetAll}''')); }); testWithoutContext('wraps text with only ANSI sequences', () { expect(wrapText(onlyAnsiSequences, columnWidth: lineLength, shouldWrap: true), equals('${AnsiTerminal.red}${AnsiTerminal.resetAll}')); }); testWithoutContext('preserves indentation in the presence of newlines', () { expect(wrapText(indentedLongLineWithNewlines, columnWidth: lineLength, shouldWrap: true), equals(''' This is an indented long line with newlines that needs to be wrapped. \tAnd preserves tabs. 01234567890123456789012345678901234567 890123456789''')); }); testWithoutContext('removes trailing whitespace when wrapping', () { expect(wrapText('$longLine \t', columnWidth: lineLength, shouldWrap: true), equals(''' This is a long line that needs to be wrapped.''')); }); testWithoutContext('honors hangingIndent parameter', () { expect(wrapText(longLine, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' This is a long line that needs to be wrapped.''')); }); testWithoutContext('handles hangingIndent with a single unwrapped line.', () { expect(wrapText(shortLine, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' Short line.''')); }); testWithoutContext('handles hangingIndent with two unwrapped lines and the second is empty.', () { expect(wrapText('$shortLine\n', columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' Short line. ''')); }); testWithoutContext('honors hangingIndent parameter on already indented line.', () { expect(wrapText(indentedLongLine, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' This is an indented long line that needs to be wrapped and indentation preserved.''')); }); testWithoutContext('honors hangingIndent and indent parameters at the same time.', () { expect(wrapText(indentedLongLine, columnWidth: lineLength, indent: 6, hangingIndent: 6, shouldWrap: true), equals(''' This is an indented long line that needs to be wrapped and indentation preserved.''')); }); testWithoutContext('honors indent parameter on already indented line.', () { expect(wrapText(indentedLongLine, columnWidth: lineLength, indent: 6, shouldWrap: true), equals(''' This is an indented long line that needs to be wrapped and indentation preserved.''')); }); testWithoutContext('honors hangingIndent parameter on already indented line.', () { expect(wrapText(indentedLongLineWithNewlines, columnWidth: lineLength, hangingIndent: 6, shouldWrap: true), equals(''' This is an indented long line with newlines that needs to be wrapped. And preserves tabs. 01234567890123456789012345678901234567 890123456789''')); }); testWithoutContext('', () { expect(wrapText( '${' ' * 7}abc def ghi', columnWidth: 20, hangingIndent: 5, indent: 3, shouldWrap: true), equals( ' abc def\n' ' ghi' ), ); expect(wrapText( 'abc def ghi', columnWidth: 0, hangingIndent: 5, shouldWrap: true), equals( 'abc def\n' 'ghi' ), ); expect(wrapText( 'abc def ghi', columnWidth: 0, indent: 5, shouldWrap: true), equals( 'abc def\n' 'ghi' ), ); expect(wrapText( ' abc def ghi', columnWidth: 0, shouldWrap: true), equals( 'abc def\n' 'ghi' ), ); expect(wrapText( 'abc def ghi', columnWidth: kMinColumnWidth - 2, hangingIndent: 5, shouldWrap: true), equals( 'abc def\n' 'ghi' ), ); expect(wrapText( 'abc def ghi', columnWidth: kMinColumnWidth - 2, indent: 5, shouldWrap: true), equals( 'abc def\n' 'ghi' ), ); expect(wrapText( ' abc def ghi', columnWidth: kMinColumnWidth - 2, shouldWrap: true), equals( 'abc def\n' 'ghi' ), ); expect(wrapText( 'abc def ghi jkl', columnWidth: kMinColumnWidth + 2, hangingIndent: 5, shouldWrap: true), equals( 'abc def ghi\n' ' jkl' ), ); expect(wrapText( 'abc def ghi', columnWidth: kMinColumnWidth + 2, indent: 5, shouldWrap: true), equals( ' abc def\n' ' ghi' ), ); expect(wrapText( ' abc def ghi', columnWidth: kMinColumnWidth + 2, shouldWrap: true), equals( ' abc def\n' ' ghi' ), ); }); }); }
flutter/packages/flutter_tools/test/general.shard/utils_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/utils_test.dart", "repo_id": "flutter", "token_count": 5929 }
787
// Copyright 2014 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/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/os.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/web/chrome.dart'; import 'package:flutter_tools/src/web/web_validator.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; void main() { late Platform platform; late FakeProcessManager fakeProcessManager; late ChromiumLauncher chromeLauncher; late FileSystem fileSystem; late ChromiumValidator webValidator; setUp(() { fileSystem = MemoryFileSystem.test(); fakeProcessManager = FakeProcessManager.empty(); platform = FakePlatform( operatingSystem: 'macos', environment: <String, String>{}, ); chromeLauncher = ChromiumLauncher( fileSystem: fileSystem, platform: platform, processManager: fakeProcessManager, operatingSystemUtils: OperatingSystemUtils( fileSystem: fileSystem, logger: BufferLogger.test(), platform: platform, processManager: fakeProcessManager, ), browserFinder: findChromeExecutable, logger: BufferLogger.test(), ); webValidator = webValidator = ChromeValidator( platform: platform, chromiumLauncher: chromeLauncher, ); }); testWithoutContext('WebValidator can find executable on macOS', () async { final ValidationResult result = await webValidator.validate(); expect(result.type, ValidationType.success); }); testWithoutContext('WebValidator Can notice missing macOS executable ', () async { fakeProcessManager.excludedExecutables.add(kMacOSExecutable); final ValidationResult result = await webValidator.validate(); expect(result.type, ValidationType.missing); }); testWithoutContext('WebValidator does not warn about CHROME_EXECUTABLE unless it cant find chrome ', () async { fakeProcessManager.excludedExecutables.add(kMacOSExecutable); final ValidationResult result = await webValidator.validate(); expect(result.messages, const <ValidationMessage>[ ValidationMessage.hint( 'Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.'), ]); expect(result.type, ValidationType.missing); }); }
flutter/packages/flutter_tools/test/general.shard/web/web_validator_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/web/web_validator_test.dart", "repo_id": "flutter", "token_count": 852 }
788
// Copyright 2014 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_testing/file_testing.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import '../integration.shard/test_utils.dart'; import '../src/common.dart'; void main() { final String flutterBin = fileSystem.path.join( getFlutterRoot(), 'bin', 'flutter', ); setUpAll(() { processManager.runSync(<String>[ flutterBin, 'config', '--enable-macos-desktop', ]); }); test('verify FlutterMacOS.xcframework artifact', () { final String flutterRoot = getFlutterRoot(); final Directory xcframeworkArtifact = fileSystem.directory( fileSystem.path.join( flutterRoot, 'bin', 'cache', 'artifacts', 'engine', 'darwin-x64', 'FlutterMacOS.xcframework', ), ); final Directory tempDir = createResolvedTempDirectorySync('macos_content_validation.'); // Pre-cache iOS engine Flutter.xcframework artifacts. final ProcessResult result = processManager.runSync( <String>[ flutterBin, ...getLocalEngineArguments(), 'precache', '--macos', ], workingDirectory: tempDir.path, ); expect(result, const ProcessResultMatcher()); expect(xcframeworkArtifact.existsSync(), isTrue); }); for (final String buildMode in <String>['Debug', 'Release']) { final String buildModeLower = buildMode.toLowerCase(); test('flutter build macos --$buildModeLower builds a valid app', () { final String workingDirectory = fileSystem.path.join( getFlutterRoot(), 'dev', 'integration_tests', 'flutter_gallery', ); processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'clean', ], workingDirectory: workingDirectory); final File podfile = fileSystem.file(fileSystem.path.join(workingDirectory, 'macos', 'Podfile')); final File podfileLock = fileSystem.file(fileSystem.path.join(workingDirectory, 'macos', 'Podfile.lock')); expect(podfile, exists); expect(podfileLock, exists); // Simulate a newer Podfile than Podfile.lock. podfile.setLastModifiedSync(DateTime.now()); podfileLock.setLastModifiedSync(DateTime.now().subtract(const Duration(days: 1))); expect(podfileLock.lastModifiedSync().isBefore(podfile.lastModifiedSync()), isTrue); final List<String> buildCommand = <String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'macos', '--$buildModeLower', ]; final ProcessResult result = processManager.runSync(buildCommand, workingDirectory: workingDirectory); printOnFailure('Output of flutter build macos:'); printOnFailure(result.stdout.toString()); printOnFailure(result.stderr.toString()); expect(result.exitCode, 0); expect(result.stdout, contains('Running pod install')); expect(podfile.lastModifiedSync().isBefore(podfileLock.lastModifiedSync()), isTrue); final Directory buildPath = fileSystem.directory(fileSystem.path.join( workingDirectory, 'build', 'macos', 'Build', 'Products', buildMode, )); final Directory outputApp = buildPath.childDirectory('Flutter Gallery.app'); final Directory outputAppFramework = fileSystem.directory(fileSystem.path.join( outputApp.path, 'Contents', 'Frameworks', 'App.framework', )); final File libBinary = outputAppFramework.childFile('App'); final File libDsymBinary = buildPath.childFile('App.framework.dSYM/Contents/Resources/DWARF/App'); _checkFatBinary(libBinary, buildModeLower, 'dynamically linked shared library'); final List<String> libSymbols = AppleTestUtils.getExportedSymbols(libBinary.path); if (buildMode == 'Debug') { // dSYM is not created for a debug build. expect(libDsymBinary.existsSync(), isFalse); expect(libSymbols, isEmpty); } else { _checkFatBinary(libDsymBinary, buildModeLower, 'dSYM companion file'); expect(libSymbols, equals(AppleTestUtils.requiredSymbols)); final List<String> dSymSymbols = AppleTestUtils.getExportedSymbols(libDsymBinary.path); expect(dSymSymbols, containsAll(AppleTestUtils.requiredSymbols)); // The actual number of symbols is going to vary but there should // be "many" in the dSYM. At the time of writing, it was 19195. expect(dSymSymbols.length, greaterThanOrEqualTo(15000)); } expect(outputAppFramework.childLink('Resources'), exists); final File vmSnapshot = fileSystem.file(fileSystem.path.join( outputApp.path, 'Contents', 'Frameworks', 'App.framework', 'Resources', 'flutter_assets', 'vm_snapshot_data', )); expect(vmSnapshot.existsSync(), buildMode == 'Debug'); final Directory outputFlutterFramework = fileSystem.directory( fileSystem.path.join( outputApp.path, 'Contents', 'Frameworks', 'FlutterMacOS.framework', ), ); // Check complicated macOS framework symlink structure. final Link current = outputFlutterFramework.childDirectory('Versions').childLink('Current'); expect(current.targetSync(), 'A'); expect(outputFlutterFramework.childLink('FlutterMacOS').targetSync(), fileSystem.path.join('Versions', 'Current', 'FlutterMacOS')); expect(outputFlutterFramework.childLink('Resources'), exists); expect(outputFlutterFramework.childLink('Resources').targetSync(), fileSystem.path.join('Versions', 'Current', 'Resources')); expect(outputFlutterFramework.childLink('Headers'), isNot(exists)); expect(outputFlutterFramework.childDirectory('Headers'), isNot(exists)); expect(outputFlutterFramework.childLink('Modules'), isNot(exists)); expect(outputFlutterFramework.childDirectory('Modules'), isNot(exists)); // Build again without cleaning. final ProcessResult secondBuild = processManager.runSync(buildCommand, workingDirectory: workingDirectory); printOnFailure('Output of second build:'); printOnFailure(secondBuild.stdout.toString()); printOnFailure(secondBuild.stderr.toString()); expect(secondBuild.exitCode, 0); expect(secondBuild.stdout, isNot(contains('Running pod install'))); processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'clean', ], workingDirectory: workingDirectory); }, skip: !platform.isMacOS); // [intended] only makes sense for macos platform. } } void _checkFatBinary(File file, String buildModeLower, String expectedType) { final String archs = processManager.runSync( <String>['file', file.path], ).stdout as String; final bool containsX64 = archs.contains('Mach-O 64-bit $expectedType x86_64'); final bool containsArm = archs.contains('Mach-O 64-bit $expectedType arm64'); if (buildModeLower == 'debug') { // Only build the architecture matching the machine running this test, not both. expect(containsX64 ^ containsArm, isTrue, reason: 'Unexpected architecture $archs'); } else { expect(containsX64, isTrue, reason: 'Unexpected architecture $archs'); expect(containsArm, isTrue, reason: 'Unexpected architecture $archs'); } }
flutter/packages/flutter_tools/test/host_cross_arch.shard/macos_content_validation_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/host_cross_arch.shard/macos_content_validation_test.dart", "repo_id": "flutter", "token_count": 2902 }
789
// Copyright 2014 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:math'; import 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/cache.dart'; import '../src/common.dart'; import 'test_utils.dart'; void main() { late Directory tempDir; setUp(() { Cache.flutterRoot = getFlutterRoot(); tempDir = createResolvedTempDirectorySync('android_plugin_new_output_dir_test.'); }); tearDown(() async { tryToDelete(tempDir); }); test("error logged when plugin's build output dir was not private.", () async { final String flutterBin = fileSystem.path.join( getFlutterRoot(), 'bin', 'flutter', ); // create flutter module project ProcessResult result = processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'create', '--template=module', 'flutter_project' ], workingDirectory: tempDir.path); final String projectPath = fileSystem.path.join(tempDir.path, 'flutter_project'); final File modulePubspec = fileSystem.file(fileSystem.path.join(projectPath, 'pubspec.yaml')); String pubspecContent = modulePubspec.readAsStringSync(); pubspecContent = pubspecContent.replaceFirst( 'dependencies:', ''' dependencies: image_picker: 0.8.5+3''', ); modulePubspec.writeAsStringSync(pubspecContent); // Run flutter build apk to build module example project result = processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'aar', '--target-platform=android-arm', ], workingDirectory: projectPath); log(result.exitCode); // Check outputDir existed final Directory outputDir = fileSystem.directory(fileSystem.path.join( projectPath, '.android', 'plugins_build_output', 'image_picker_android' )); expect(outputDir, exists); }); }
flutter/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/android_plugin_new_output_dir_test.dart", "repo_id": "flutter", "token_count": 749 }
790
// Copyright 2014 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:convert'; import 'dart:io'; import 'package:dds/dap.dart' show Logger; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/debug_adapters/server.dart'; import 'package:flutter_tools/src/globals.dart' as globals; /// Enable to run from local source when running out-of-process (useful in /// development to avoid having to keep rebuilding the flutter tool). const bool _runFromSource = false; abstract class DapTestServer { Future<void> stop(); StreamSink<List<int>> get sink; Stream<List<int>> get stream; void Function(String message)? onStderrOutput; } /// An instance of a DAP server running in-process (to aid debugging). /// /// All communication still goes over the socket to ensure all messages are /// serialized and deserialized but it's not quite the same running out of /// process. class InProcessDapTestServer extends DapTestServer { InProcessDapTestServer._(List<String> args) { _server = DapServer( stdinController.stream, stdoutController.sink, fileSystem: globals.fs, platform: globals.platform, // Simulate flags based on the args to aid testing. enableDds: !args.contains('--no-dds'), ipv6: args.contains('--ipv6'), test: args.contains('--test'), ); } late final DapServer _server; final StreamController<List<int>> stdinController = StreamController<List<int>>(); final StreamController<List<int>> stdoutController = StreamController<List<int>>(); @override StreamSink<List<int>> get sink => stdinController.sink; @override Stream<List<int>> get stream => stdoutController.stream; @override Future<void> stop() async { _server.stop(); } static Future<InProcessDapTestServer> create({ Logger? logger, List<String>? additionalArgs, }) async { return InProcessDapTestServer._(additionalArgs ?? <String>[]); } } /// An instance of a DAP server running out-of-process. /// /// This is how an editor will usually consume DAP so is a more accurate test /// but will be a little more difficult to debug tests as the debugger will not /// be attached to the process. class OutOfProcessDapTestServer extends DapTestServer { OutOfProcessDapTestServer._( this._process, Logger? logger, ) { // Unless we're given an error handler, treat anything written to stderr as // the DAP crashing and fail the test unless it's "Waiting for another // flutter command to release the startup lock" or we're tearing down. _process.stderr .transform(utf8.decoder) .where((String error) => !error.contains('Waiting for another flutter command to release the startup lock')) .listen((String error) { logger?.call(error); if (!_isShuttingDown) { final void Function(String message)? stderrHandler = onStderrOutput; if (stderrHandler != null) { stderrHandler(error); } else { throw Exception(error); } } }); unawaited(_process.exitCode.then((int code) { final String message = 'Out-of-process DAP server terminated with code $code'; logger?.call(message); if (!_isShuttingDown && code != 0 && onStderrOutput == null) { throw Exception(message); } })); } bool _isShuttingDown = false; final Process _process; Future<int> get exitCode => _process.exitCode; @override StreamSink<List<int>> get sink => _process.stdin; @override Stream<List<int>> get stream => _process.stdout; @override Future<void> stop() async { _isShuttingDown = true; _process.kill(); await _process.exitCode; } static Future<OutOfProcessDapTestServer> create({ Logger? logger, List<String>? additionalArgs, }) async { // runFromSource=true will run "dart bin/flutter_tools.dart ..." to avoid // having to rebuild the flutter_tools snapshot. // runFromSource=false will run "flutter ..." final String flutterToolPath = globals.fs.path.join(Cache.flutterRoot!, 'bin', Platform.isWindows ? 'flutter.bat' : 'flutter'); final String flutterToolsEntryScript = globals.fs.path.join(Cache.flutterRoot!, 'packages', 'flutter_tools', 'bin', 'flutter_tools.dart'); // When running from source, run "dart bin/flutter_tools.dart debug_adapter" // instead of directly using "flutter debug_adapter". final String executable = _runFromSource ? Platform.resolvedExecutable : flutterToolPath; final List<String> args = <String>[ if (_runFromSource) flutterToolsEntryScript, 'debug-adapter', ...?additionalArgs, ]; final Process process = await Process.start(executable, args); return OutOfProcessDapTestServer._(process, logger); } }
flutter/packages/flutter_tools/test/integration.shard/debug_adapter/test_server.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/debug_adapter/test_server.dart", "repo_id": "flutter", "token_count": 1682 }
791
// Copyright 2014 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 'package:file/file.dart'; import '../src/common.dart'; import 'test_data/basic_project.dart'; import 'test_driver.dart'; import 'test_utils.dart'; void main() { late Directory tempDir; final BasicProjectWithFlutterGen project = BasicProjectWithFlutterGen(); late FlutterRunTestDriver flutter; setUp(() async { tempDir = createResolvedTempDirectorySync('run_test.'); await project.setUpIn(tempDir); flutter = FlutterRunTestDriver(tempDir); }); tearDown(() async { await flutter.stop(); tryToDelete(tempDir); }); testWithoutContext('can correctly reference flutter generated code.', () async { await flutter.run(); final dynamic jsonContent = json.decode(project.dir .childDirectory('.dart_tool') .childFile('package_config.json') .readAsStringSync()); final Map<String, dynamic> collection = ((jsonContent as Map<String, dynamic>)['packages'] as Iterable<dynamic>) .firstWhere((dynamic entry) => (entry as Map<String, dynamic>)['name'] == 'collection') as Map<String, dynamic>; expect( Uri.parse(collection['rootUri'] as String).isAbsolute, isTrue, reason: 'The generated package_config.json should use absolute root urls', ); expect( collection['packageUri'] as String, 'lib/', reason: 'The generated package_config.json should have package urls ending with /' ); }); }
flutter/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/flutter_gen_test.dart", "repo_id": "flutter", "token_count": 545 }
792
// Copyright 2014 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:flutter_tools/src/convert.dart'; import '../src/common.dart'; import 'test_utils.dart'; /// Checks that all active template files are defined in the template_manifest.json file. void main() { testWithoutContext('Check template manifest is up to date', () { final Map<String, Object?> manifest = json.decode( fileSystem.file('templates/template_manifest.json').readAsStringSync(), ) as Map<String, Object?>; final Set<Uri> declaredFileList = Set<Uri>.from( (manifest['files']! as List<Object?>).cast<String>().map<Uri>(fileSystem.path.toUri)); final Set<Uri> activeTemplateList = fileSystem.directory('templates') .listSync(recursive: true) .whereType<File>() .where((File file) => fileSystem.path.basename(file.path) != 'template_manifest.json' && fileSystem.path.basename(file.path) != 'README.md' && fileSystem.path.basename(file.path) != '.DS_Store') .map((File file) => file.uri) .toSet(); final Set<Uri> difference = activeTemplateList.difference(declaredFileList); expect(difference, isEmpty, reason: 'manifest and template directory should be in-sync'); }); }
flutter/packages/flutter_tools/test/integration.shard/template_manifest_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/template_manifest_test.dart", "repo_id": "flutter", "token_count": 475 }
793
// Copyright 2014 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 '../test_utils.dart'; import 'deferred_components_config.dart'; const String _kDefaultHtml = ''' <html> <head> <title>Hello, World</title> </head> <body> <script src="main.dart.js"></script> </body> </html> '''; abstract class Project { /// Creates a flutter Project for testing. /// /// If passed, `indexHtml` is used as the contents of the web/index.html file. Project({this.indexHtml = _kDefaultHtml}); late Directory dir; String get pubspec; String? get main => null; String? get test => null; String? get generatedFile => null; DeferredComponentsConfig? get deferredComponents => null; Uri get mainDart => Uri.parse('package:test/main.dart'); /// The contents for the index.html file of this `Project`. /// /// Defaults to [_kDefaultHtml] via the Project constructor. /// /// (Used by [HotReloadProject].) final String indexHtml; Future<void> setUpIn(Directory dir) async { this.dir = dir; writeFile(fileSystem.path.join(dir.path, 'pubspec.yaml'), pubspec); final String? main = this.main; if (main != null) { writeFile(fileSystem.path.join(dir.path, 'lib', 'main.dart'), main); } final String? test = this.test; if (test != null) { writeFile(fileSystem.path.join(dir.path, 'test', 'test.dart'), test); } final String? generatedFile = this.generatedFile; if (generatedFile != null) { writeFile(fileSystem.path.join(dir.path, '.dart_tool', 'flutter_gen', 'flutter_gen.dart'), generatedFile); } deferredComponents?.setUpIn(dir); // Setup for different flutter web initializations writeFile(fileSystem.path.join(dir.path, 'web', 'index.html'), indexHtml); writeFile(fileSystem.path.join(dir.path, 'web', 'flutter.js'), ''); writeFile(fileSystem.path.join(dir.path, 'web', 'flutter_service_worker.js'), ''); writePackages(dir.path); await getPackages(dir.path); } int lineContaining(String contents, String search) { final int index = contents.split('\n').indexWhere((String l) => l.contains(search)); if (index == -1) { throw Exception("Did not find '$search' inside the file"); } return index + 1; // first line is line 1, not line 0 } }
flutter/packages/flutter_tools/test/integration.shard/test_data/project.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/test_data/project.dart", "repo_id": "flutter", "token_count": 872 }
794
// Copyright 2014 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:args/command_runner.dart'; import 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/create.dart'; import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import '../src/common.dart'; import '../src/context.dart'; import '../src/test_flutter_command_runner.dart'; import 'test_utils.dart'; void main() { late Directory tempDir; late Directory projectDir; setUpAll(() async { Cache.disableLocking(); await _ensureFlutterToolsSnapshot(); }); setUp(() { tempDir = globals.fs.systemTempDirectory .createTempSync('flutter_tools_generated_plugin_registrant_test.'); projectDir = tempDir.childDirectory('flutter_project'); }); tearDown(() { tryToDelete(tempDir); }); tearDownAll(() async { await _restoreFlutterToolsSnapshot(); }); testUsingContext('generated plugin registrant passes analysis', () async { await _createProject(projectDir, <String>[]); // We need a dependency so the plugin registrant is not completely empty. await _editPubspecFile(projectDir, _addDependencyEditor('shared_preferences', version: '^2.0.0')); // The plugin registrant is created on build... await _buildWebProject(projectDir); // Find the web_plugin_registrant, now that it lives outside "lib": final Directory buildDir = projectDir .childDirectory('.dart_tool/flutter_build') .listSync() .firstWhere((FileSystemEntity entity) => entity is Directory) as Directory; // Ensure the file exists, and passes analysis. final File registrant = buildDir.childFile('web_plugin_registrant.dart'); expect(registrant, exists); await _analyzeEntity(registrant); // Ensure the contents match what we expect for a non-empty plugin registrant. final String contents = registrant.readAsStringSync(); expect(contents, contains('// @dart = 2.13')); expect(contents, contains("import 'package:shared_preferences_web/shared_preferences_web.dart';")); expect(contents, contains('void registerPlugins([final Registrar? pluginRegistrar]) {')); expect(contents, contains('SharedPreferencesPlugin.registerWith(registrar);')); expect(contents, contains('registrar.registerMessageHandler();')); }, overrides: <Type, Generator>{ Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: globals.stdio, ), }); testUsingContext('generated plugin registrant passes analysis with null safety', () async { await _createProject(projectDir, <String>[]); // We need a dependency so the plugin registrant is not completely empty. await _editPubspecFile(projectDir, _composeEditors(<PubspecEditor>[ _addDependencyEditor('shared_preferences', version: '^2.0.0'), _setDartSDKVersionEditor('>=2.12.0 <4.0.0'), ])); // Replace main file with a no-op dummy. We aren't testing it in this scenario anyway. await _replaceMainFile(projectDir, 'void main() {}'); // The plugin registrant is created on build... await _buildWebProject(projectDir); // Find the web_plugin_registrant, now that it lives outside "lib": final Directory buildDir = projectDir .childDirectory('.dart_tool/flutter_build') .listSync() .firstWhere((FileSystemEntity entity) => entity is Directory) as Directory; // Ensure the file exists, and passes analysis. final File registrant = buildDir.childFile('web_plugin_registrant.dart'); expect(registrant, exists); await _analyzeEntity(registrant); // Ensure the contents match what we expect for a non-empty plugin registrant. final String contents = registrant.readAsStringSync(); expect(contents, contains('// @dart = 2.13')); expect(contents, contains("import 'package:shared_preferences_web/shared_preferences_web.dart';")); expect(contents, contains('void registerPlugins([final Registrar? pluginRegistrar]) {')); expect(contents, contains('SharedPreferencesPlugin.registerWith(registrar);')); expect(contents, contains('registrar.registerMessageHandler();')); }, overrides: <Type, Generator>{ Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: globals.stdio, ), }); testUsingContext('(no-op) generated plugin registrant passes analysis', () async { await _createProject(projectDir, <String>[]); // No dependencies on web plugins this time! await _buildWebProject(projectDir); // Find the web_plugin_registrant, now that it lives outside "lib": final Directory buildDir = projectDir .childDirectory('.dart_tool/flutter_build') .listSync() .firstWhere((FileSystemEntity entity) => entity is Directory) as Directory; // Ensure the file exists, and passes analysis. final File registrant = buildDir.childFile('web_plugin_registrant.dart'); expect(registrant, exists); await _analyzeEntity(registrant); // Ensure the contents match what we expect for an empty (noop) plugin registrant. final String contents = registrant.readAsStringSync(); expect(contents, contains('void registerPlugins() {}')); }, overrides: <Type, Generator>{ Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: globals.stdio, ), }); // See: https://github.com/dart-lang/dart-services/pull/874 testUsingContext('generated plugin registrant for dartpad is created on pub get', () async { await _createProject(projectDir, <String>[]); await _editPubspecFile(projectDir, _addDependencyEditor('shared_preferences', version: '^2.0.0')); // The plugin registrant for dartpad is created on flutter pub get. await _doFlutterPubGet(projectDir); final File registrant = projectDir .childDirectory('.dart_tool/dartpad') .childFile('web_plugin_registrant.dart'); // Ensure the file exists, and passes analysis. expect(registrant, exists); await _analyzeEntity(registrant); // Assert the full build hasn't happened! final Directory buildDir = projectDir.childDirectory('.dart_tool/flutter_build'); expect(buildDir, isNot(exists)); }, overrides: <Type, Generator>{ Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: globals.stdio, ), }); testUsingContext( 'generated plugin registrant ignores lines longer than 80 chars', () async { await _createProject(projectDir, <String>[]); await _addAnalysisOptions( projectDir, <String>['lines_longer_than_80_chars']); await _createProject(tempDir.childDirectory('test_plugin'), <String>[ '--template=plugin', '--platforms=web', '--project-name', 'test_web_plugin_with_a_purposefully_extremely_long_package_name', ]); // The line for the test web plugin (` TestWebPluginWithAPurposefullyExtremelyLongPackageNameWeb.registerWith(registrar);`) // exceeds 80 chars. // With the above lint rule added, we want to ensure that the `generated_plugin_registrant.dart` // file does not fail analysis (this is a regression test - an ignore was // added to cover this case). await _editPubspecFile( projectDir, _addDependencyEditor( 'test_web_plugin_with_a_purposefully_extremely_long_package_name', path: '../test_plugin', ) ); // The plugin registrant is only created after a build... await _buildWebProject(projectDir); // Find the web_plugin_registrant, now that it lives outside "lib": final Directory buildDir = projectDir .childDirectory('.dart_tool/flutter_build') .listSync() .firstWhere((FileSystemEntity entity) => entity is Directory) as Directory; expect( buildDir.childFile('web_plugin_registrant.dart'), exists, ); await _analyzeEntity(buildDir.childFile('web_plugin_registrant.dart')); }, overrides: <Type, Generator>{ Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: globals.stdio, ), }); } Future<void> _ensureFlutterToolsSnapshot() async { final String flutterToolsPath = globals.fs.path.absolute(globals.fs.path.join( 'bin', 'flutter_tools.dart', )); final String flutterToolsSnapshotPath = globals.fs.path.absolute( globals.fs.path.join( '..', '..', 'bin', 'cache', 'flutter_tools.snapshot', ), ); final String dotPackages = globals.fs.path.absolute(globals.fs.path.join( '.dart_tool/package_config.json', )); final File snapshotFile = globals.fs.file(flutterToolsSnapshotPath); if (snapshotFile.existsSync()) { snapshotFile.renameSync('$flutterToolsSnapshotPath.bak'); } final List<String> snapshotArgs = <String>[ '--snapshot=$flutterToolsSnapshotPath', '--packages=$dotPackages', flutterToolsPath, ]; final ProcessResult snapshotResult = await Process.run( '../../bin/cache/dart-sdk/bin/dart', snapshotArgs, ); printOnFailure('Output of dart ${snapshotArgs.join(" ")}:'); printOnFailure(snapshotResult.stdout.toString()); printOnFailure(snapshotResult.stderr.toString()); expect(snapshotResult, const ProcessResultMatcher()); } Future<void> _restoreFlutterToolsSnapshot() async { final String flutterToolsSnapshotPath = globals.fs.path.absolute( globals.fs.path.join( '..', '..', 'bin', 'cache', 'flutter_tools.snapshot', ), ); final File snapshotBackup = globals.fs.file('$flutterToolsSnapshotPath.bak'); if (!snapshotBackup.existsSync()) { // No backup to restore. return; } snapshotBackup.renameSync(flutterToolsSnapshotPath); } Future<void> _createProject(Directory dir, List<String> createArgs) async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', ...createArgs, dir.path, ]); } typedef PubspecEditor = void Function(List<String> pubSpecContents); Future<void> _editPubspecFile( Directory projectDir, PubspecEditor editor, ) async { final File pubspecYaml = projectDir.childFile('pubspec.yaml'); expect(pubspecYaml, exists); final List<String> lines = await pubspecYaml.readAsLines(); editor(lines); await pubspecYaml.writeAsString(lines.join('\n')); } Future<void> _replaceMainFile(Directory projectDir, String fileContents) async { final File mainFile = projectDir.childDirectory('lib').childFile('main.dart'); await mainFile.writeAsString(fileContents); } PubspecEditor _addDependencyEditor(String packageToAdd, {String? version, String? path}) { assert(version != null || path != null, 'Need to define a source for the package.'); assert(version == null || path == null, 'Cannot only load a package from path or from Pub, not both.'); void editor(List<String> lines) { for (int i = 0; i < lines.length; i++) { final String line = lines[i]; if (line.startsWith('dependencies:')) { lines.insert( i + 1, ' $packageToAdd: ${version ?? '\n' ' path: $path'}'); break; } } } return editor; } PubspecEditor _setDartSDKVersionEditor(String version) { void editor(List<String> lines) { for (int i = 0; i < lines.length; i++) { final String line = lines[i]; if (line.startsWith('environment:')) { for (i++; i < lines.length; i++) { final String innerLine = lines[i]; final String sdkLine = " sdk: '$version'"; if (innerLine.isNotEmpty && !innerLine.startsWith(' ')) { lines.insert(i, sdkLine); break; } if (innerLine.startsWith(' sdk:')) { lines[i] = sdkLine; break; } } break; } } } return editor; } PubspecEditor _composeEditors(Iterable<PubspecEditor> editors) { void composedEditor(List<String> lines) { for (final PubspecEditor editor in editors) { editor(lines); } } return composedEditor; } Future<void> _addAnalysisOptions( Directory projectDir, List<String> linterRules) async { assert(linterRules.isNotEmpty); await projectDir.childFile('analysis_options.yaml').writeAsString(''' linter: rules: ${linterRules.map((String rule) => ' - $rule').join('\n')} '''); } Future<void> _analyzeEntity(FileSystemEntity target) async { final String flutterToolsSnapshotPath = globals.fs.path.absolute( globals.fs.path.join( '..', '..', 'bin', 'cache', 'flutter_tools.snapshot', ), ); final List<String> args = <String>[ flutterToolsSnapshotPath, 'analyze', target.path, ]; final ProcessResult exec = await Process.run( globals.artifacts!.getArtifactPath(Artifact.engineDartBinary, platform: TargetPlatform.web_javascript), args, workingDirectory: target is Directory ? target.path : target.dirname, ); expect(exec, const ProcessResultMatcher()); } Future<void> _buildWebProject(Directory workingDir) async { return _runFlutterSnapshot(<String>['build', 'web'], workingDir); } Future<void> _doFlutterPubGet(Directory workingDir) async { return _runFlutterSnapshot(<String>['pub', 'get'], workingDir); } // Runs a flutter command from a snapshot build. // `flutterCommandArgs` are the arguments passed to flutter, like: ['build', 'web'] // to run `flutter build web`. // `workingDir` is the directory on which the flutter command will be run. Future<void> _runFlutterSnapshot(List<String> flutterCommandArgs, Directory workingDir) async { final String flutterToolsSnapshotPath = globals.fs.path.absolute( globals.fs.path.join( '..', '..', 'bin', 'cache', 'flutter_tools.snapshot', ), ); final List<String> args = <String>[ globals.artifacts!.getArtifactPath(Artifact.engineDartBinary, platform: TargetPlatform.web_javascript), flutterToolsSnapshotPath, ...flutterCommandArgs ]; final ProcessResult exec = await globals.processManager.run( args, workingDirectory: workingDir.path, ); expect(exec, const ProcessResultMatcher()); }
flutter/packages/flutter_tools/test/integration.shard/web_plugin_registrant_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/web_plugin_registrant_test.dart", "repo_id": "flutter", "token_count": 5627 }
795
// Copyright 2014 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'; /// Produces a per-library coverage summary when fed an lcov file, sorted by /// increasing code coverage percentage. /// /// Usage: `dart tool/unit_coverage lcov.info` void main(List<String> args) { if (args.isEmpty || args.length > 1) { print('Usage: dart tool/unit_coverage lcov.info'); return; } final List<String> lines = File(args.single).readAsLinesSync(); final List<Coverage> coverages = <Coverage>[]; Coverage? currentCoverage; for (final String line in lines) { if (line.startsWith('SF:')) { final String library = line.split('SF:')[1]; currentCoverage = Coverage()..library = library; coverages.add(currentCoverage); } if (line.startsWith('DA')) { currentCoverage?.totalLines += 1; if (!line.endsWith(',0')) { currentCoverage?.testedLines += 1; } } if (line == 'end_of_record') { currentCoverage = null; } } coverages.sort((Coverage left, Coverage right) { final double leftPercent = left.testedLines / left.totalLines; final double rightPercent = right.testedLines / right.totalLines; return leftPercent.compareTo(rightPercent); }); double overallNumerator = 0; double overallDenominator = 0; print('% | tested | total'); for (final Coverage coverage in coverages) { overallNumerator += coverage.testedLines; overallDenominator += coverage.totalLines; final String coveragePercent = (coverage.testedLines / coverage.totalLines * 100).toStringAsFixed(2); print('${coverage.library}: $coveragePercent% | ${coverage.testedLines} | ${coverage.totalLines}'); } print('OVERALL: ${overallNumerator/overallDenominator}'); } class Coverage { String? library; int totalLines = 0; int testedLines = 0; }
flutter/packages/flutter_tools/tool/unit_coverage.dart/0
{ "file_path": "flutter/packages/flutter_tools/tool/unit_coverage.dart", "repo_id": "flutter", "token_count": 675 }
796
// Copyright 2014 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. /// Provides an API to test/debug Flutter applications on remote Fuchsia devices /// and emulators. /// /// The application typically runs in a separate process from the actual /// test, wherein the user can supply the process with various events to test /// the behavior of said application. /// /// The API will provide methods to connect to one or more instances of the /// Dart VM and operate on Isolates and Flutter Views, including affordances to /// subscribe to creation and destruction of Dart VM instances, Isolates, and /// Flutter Views. Not all of these features are yet implemented, as this /// library is a work in progress. library fuchsia_remote_debug_protocol; export 'src/common/network.dart'; export 'src/dart/dart_vm.dart'; export 'src/fuchsia_remote_connection.dart'; export 'src/runners/ssh_command_runner.dart';
flutter/packages/fuchsia_remote_debug_protocol/lib/fuchsia_remote_debug_protocol.dart/0
{ "file_path": "flutter/packages/fuchsia_remote_debug_protocol/lib/fuchsia_remote_debug_protocol.dart", "repo_id": "flutter", "token_count": 259 }
797
// Copyright 2014 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. group 'dev.flutter.plugins.integration_test' version '1.0-SNAPSHOT' buildscript { repositories { google() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:7.3.1' } } rootProject.allprojects { repositories { google() mavenCentral() } } // project.getTasks().withType(JavaCompile){ // options.compilerArgs << "-Xlint:all" << "-Werror" // } apply plugin: 'com.android.library' android { // Conditional for compatibility with AGP <4.2. if (project.android.hasProperty("namespace")) { namespace 'dev.flutter.integration_test' } compileSdk 34 compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } defaultConfig { minSdkVersion 21 testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" consumerProguardFiles 'lib-proguard-rules.txt' } dependencies { // TODO(egarciad): These dependencies should not be added to release builds. // https://github.com/flutter/flutter/issues/56591 testImplementation 'androidx.test.ext:junit:1.1.4-alpha07' testImplementation 'org.robolectric:robolectric:4.11' testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-inline:5.1.0' api 'androidx.test:runner:1.2+' api 'androidx.test:rules:1.2+' api 'androidx.test.espresso:espresso-core:3.2+' implementation 'com.google.guava:guava:28.1-android' } }
flutter/packages/integration_test/android/build.gradle/0
{ "file_path": "flutter/packages/integration_test/android/build.gradle", "repo_id": "flutter", "token_count": 716 }
798
// Copyright 2014 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:html' as html; import 'package:flutter/material.dart'; // ignore_for_file: public_member_api_docs void startApp() => runApp(const MyWebApp()); class MyWebApp extends StatefulWidget { const MyWebApp({super.key}); @override State<MyWebApp> createState() => _MyWebAppState(); } class _MyWebAppState extends State<MyWebApp> { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Plugin example app'), ), body: Center( key: const Key('mainapp'), child: Text('Platform: ${html.window.navigator.platform}\n'), ), ), ); } }
flutter/packages/integration_test/example/lib/my_web_app.dart/0
{ "file_path": "flutter/packages/integration_test/example/lib/my_web_app.dart", "repo_id": "flutter", "token_count": 322 }
799
name: integration_test_macos description: Desktop implementation of integration_test plugin version: 0.0.1+1 homepage: https://github.com/flutter/flutter/tree/master/packages/integration_test/integration_test_macos flutter: plugin: platforms: macos: pluginClass: IntegrationTestPlugin environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: flutter: sdk: flutter characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" meta: 1.12.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade" dev_dependencies: pedantic: 1.11.1 # PUBSPEC CHECKSUM: 235c
flutter/packages/integration_test/integration_test_macos/pubspec.yaml/0
{ "file_path": "flutter/packages/integration_test/integration_test_macos/pubspec.yaml", "repo_id": "flutter", "token_count": 353 }
800
// Copyright 2014 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 is a CLI library; we use prints as part of the interface. // ignore_for_file: avoid_print import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter_driver/flutter_driver.dart'; import 'package:path/path.dart' as path; import 'common.dart'; /// Flutter Driver test output directory. /// /// Tests should write any output files to this directory. Defaults to the path /// set in the FLUTTER_TEST_OUTPUTS_DIR environment variable, or `build` if /// unset. String testOutputsDirectory = Platform.environment['FLUTTER_TEST_OUTPUTS_DIR'] ?? 'build'; /// The callback type to handle [Response.data] after the test /// succeeds. typedef ResponseDataCallback = FutureOr<void> Function(Map<String, dynamic>?); /// Writes a json-serializable data to /// [testOutputsDirectory]/`testOutputFilename.json`. /// /// This is the default `responseDataCallback` in [integrationDriver]. Future<void> writeResponseData( Map<String, dynamic>? data, { String testOutputFilename = 'integration_response_data', String? destinationDirectory, }) async { destinationDirectory ??= testOutputsDirectory; await fs.directory(destinationDirectory).create(recursive: true); final File file = fs.file(path.join( destinationDirectory, '$testOutputFilename.json', )); final String resultString = _encodeJson(data, true); await file.writeAsString(resultString); } /// Adaptor to run an integration test using `flutter drive`. /// /// To an integration test `<test_name>.dart` using `flutter drive`, put a file named /// `<test_name>_test.dart` in the app's `test_driver` directory: /// /// ```dart /// import 'dart:async'; /// /// import 'package:flutter_driver/flutter_driver.dart'; /// import 'package:integration_test/integration_test_driver_extended.dart'; /// /// Future<void> main() async { /// final FlutterDriver driver = await FlutterDriver.connect(); /// await integrationDriver( /// driver: driver, /// onScreenshot: (String name, List<int> image, [Map<String, Object?>? args]) async { /// return true; /// }, /// ); /// } /// ``` /// /// ## Parameters: /// /// `driver` A custom driver. Defaults to `FlutterDriver.connect()`. /// /// `onScreenshot` can be used to process the screenshots taken during the test. /// An example could be that this callback compares the byte array against a baseline image, /// and it returns `true` if both images are equal. /// /// As a result, returning `false` from `onScreenshot` will make the test fail. /// /// `responseDataCallback` is the handler for processing [Response.data]. /// The default value is `writeResponseData`. /// /// `writeResponseOnFailure` determines whether the `responseDataCallback` /// function will be called to process the [Response.data] when a test fails. /// The default value is `false`. Future<void> integrationDriver({ FlutterDriver? driver, ScreenshotCallback? onScreenshot, ResponseDataCallback? responseDataCallback = writeResponseData, bool writeResponseOnFailure = false, }) async { driver ??= await FlutterDriver.connect(); // Test states that it's waiting on web driver commands. // [DriverTestMessage] is converted to string since json format causes an // error if it's used as a message for requestData. String jsonResponse = await driver.requestData(DriverTestMessage.pending().toString()); final Map<String, bool> onScreenshotResults = <String, bool>{}; Response response = Response.fromJson(jsonResponse); // Until `integration_test` returns a [WebDriverCommandType.noop], keep // executing WebDriver commands. while (response.data != null && response.data!['web_driver_command'] != null && response.data!['web_driver_command'] != '${WebDriverCommandType.noop}') { final String? webDriverCommand = response.data!['web_driver_command'] as String?; if (webDriverCommand == '${WebDriverCommandType.screenshot}') { assert(onScreenshot != null, 'screenshot command requires an onScreenshot callback'); // Use `driver.screenshot()` method to get a screenshot of the web page. final List<int> screenshotImage = await driver.screenshot(); final String screenshotName = response.data!['screenshot_name']! as String; final Map<String, Object?>? args = (response.data!['args'] as Map<String, Object?>?)?.cast<String, Object?>(); final bool screenshotSuccess = await onScreenshot!(screenshotName, screenshotImage, args); onScreenshotResults[screenshotName] = screenshotSuccess; if (screenshotSuccess) { jsonResponse = await driver.requestData(DriverTestMessage.complete().toString()); } else { jsonResponse = await driver.requestData(DriverTestMessage.error().toString()); } response = Response.fromJson(jsonResponse); } else if (webDriverCommand == '${WebDriverCommandType.ack}') { // Previous command completed ask for a new one. jsonResponse = await driver.requestData(DriverTestMessage.pending().toString()); response = Response.fromJson(jsonResponse); } else { break; } } // If No-op command is sent, ask for the result of all tests. if (response.data != null && response.data!['web_driver_command'] != null && response.data!['web_driver_command'] == '${WebDriverCommandType.noop}') { jsonResponse = await driver.requestData(null); response = Response.fromJson(jsonResponse); print('result $jsonResponse'); } if (response.data != null && response.data!['screenshots'] != null && onScreenshot != null) { final List<dynamic> screenshots = response.data!['screenshots'] as List<dynamic>; final List<String> failures = <String>[]; for (final dynamic screenshot in screenshots) { final Map<String, dynamic> data = screenshot as Map<String, dynamic>; final List<dynamic> screenshotBytes = data['bytes'] as List<dynamic>; final String screenshotName = data['screenshotName'] as String; bool ok = false; try { ok = onScreenshotResults[screenshotName] ?? await onScreenshot(screenshotName, screenshotBytes.cast<int>()); } catch (exception) { throw StateError( 'Screenshot failure:\n' 'onScreenshot("$screenshotName", <bytes>) threw an exception: $exception', ); } if (!ok) { failures.add(screenshotName); } } if (failures.isNotEmpty) { throw StateError('The following screenshot tests failed: ${failures.join(', ')}'); } } await driver.close(); if (response.allTestsPassed) { print('All tests passed.'); if (responseDataCallback != null) { await responseDataCallback(response.data); } exit(0); } else { print('Failure Details:\n${response.formattedFailureDetails}'); if (responseDataCallback != null && writeResponseOnFailure) { await responseDataCallback(response.data); } exit(1); } } const JsonEncoder _prettyEncoder = JsonEncoder.withIndent(' '); String _encodeJson(Map<String, dynamic>? jsonObject, bool pretty) { return pretty ? _prettyEncoder.convert(jsonObject) : json.encode(jsonObject); }
flutter/packages/integration_test/lib/integration_test_driver_extended.dart/0
{ "file_path": "flutter/packages/integration_test/lib/integration_test_driver_extended.dart", "repo_id": "flutter", "token_count": 2330 }
801
// Copyright 2014 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:integration_test/common.dart'; void main() { test('Serialize and deserialize Failure', () { final Failure fail = Failure('what a name', 'no detail'); final Failure restored = Failure.fromJsonString(fail.toString()); expect(restored.methodName, fail.methodName); expect(restored.details, fail.details); }); test('Serialize and deserialize Response', () { Response response, restored; String jsonString; response = Response.allTestsPassed(); jsonString = response.toJson(); expect(jsonString, '{"result":"true","failureDetails":[]}'); restored = Response.fromJson(jsonString); expect(restored.allTestsPassed, response.allTestsPassed); expect(restored.data, null); expect(restored.formattedFailureDetails, ''); final Failure fail = Failure('what a name', 'no detail'); final Failure fail2 = Failure('what a name2', 'no detail2'); response = Response.someTestsFailed(<Failure>[fail, fail2]); jsonString = response.toJson(); restored = Response.fromJson(jsonString); expect(restored.allTestsPassed, response.allTestsPassed); expect(restored.data, null); expect(restored.formattedFailureDetails, response.formattedFailureDetails); final Map<String, dynamic> data = <String, dynamic>{'aaa': 'bbb'}; response = Response.allTestsPassed(data: data); jsonString = response.toJson(); restored = Response.fromJson(jsonString); expect(restored.data!.keys, <String>['aaa']); expect(restored.data!.values, <String>['bbb']); response = Response.someTestsFailed(<Failure>[fail, fail2], data: data); jsonString = response.toJson(); restored = Response.fromJson(jsonString); expect(restored.data!.keys, <String>['aaa']); expect(restored.data!.values, <String>['bbb']); }); }
flutter/packages/integration_test/test/response_serialization_test.dart/0
{ "file_path": "flutter/packages/integration_test/test/response_serialization_test.dart", "repo_id": "flutter", "token_count": 675 }
802
#include "Generated.xcconfig"
flutter_clock/analog_clock/ios/Flutter/Release.xcconfig/0
{ "file_path": "flutter_clock/analog_clock/ios/Flutter/Release.xcconfig", "repo_id": "flutter_clock", "token_count": 12 }
803
// Copyright 2019 The Chromium 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 'hand.dart'; /// A clock hand that is built out of the child of a [Container]. /// /// This hand does not scale according to the clock's size. /// This hand is used as the hour hand in our analog clock, and demonstrates /// building a hand using existing Flutter widgets. class ContainerHand extends Hand { /// Create a const clock [Hand]. /// /// All of the parameters are required and must not be null. const ContainerHand({ @required Color color, @required double size, @required double angleRadians, this.child, }) : assert(size != null), assert(angleRadians != null), super( color: color, size: size, angleRadians: angleRadians, ); /// The child widget used as the clock hand and rotated by [angleRadians]. final Widget child; @override Widget build(BuildContext context) { return Center( child: SizedBox.expand( child: Transform.rotate( angle: angleRadians, alignment: Alignment.center, child: Transform.scale( scale: size, alignment: Alignment.center, child: Container( color: color, child: Center(child: child), ), ), ), ), ); } }
flutter_clock/analog_clock/lib/container_hand.dart/0
{ "file_path": "flutter_clock/analog_clock/lib/container_hand.dart", "repo_id": "flutter_clock", "token_count": 565 }
804
#include "Generated.xcconfig"
flutter_clock/digital_clock/ios/Flutter/Release.xcconfig/0
{ "file_path": "flutter_clock/digital_clock/ios/Flutter/Release.xcconfig", "repo_id": "flutter_clock", "token_count": 12 }
805
// Copyright 2019 The Chromium 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_clock_helper/customizer.dart'; import 'package:flutter_clock_helper/model.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'digital_clock.dart'; void main() { // A temporary measure until Platform supports web and TargetPlatform supports // macOS. if (!kIsWeb && Platform.isMacOS) { // TODO(gspencergoog): Update this when TargetPlatform includes macOS. // https://github.com/flutter/flutter/issues/31366 // See https://github.com/flutter/flutter/wiki/Desktop-shells#target-platform-override. debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia; } // This creates a clock that enables you to customize it. // // The [ClockCustomizer] takes in a [ClockBuilder] that consists of: // - A clock widget (in this case, [DigitalClock]) // - A model (provided to you by [ClockModel]) // For more information, see the flutter_clock_helper package. // // Your job is to edit [DigitalClock], or replace it with your // own clock widget. (Look in digital_clock.dart for more details!) runApp(ClockCustomizer((ClockModel model) => DigitalClock(model))); }
flutter_clock/digital_clock/lib/main.dart/0
{ "file_path": "flutter_clock/digital_clock/lib/main.dart", "repo_id": "flutter_clock", "token_count": 410 }
806
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dist="http://schemas.android.com/apk/distribution"> <dist:module dist:instant="false" dist:title="@string/craneName"> <dist:delivery> <dist:on-demand /> </dist:delivery> <dist:fusing dist:include="true" /> </dist:module> </manifest>
gallery/android/crane/src/main/AndroidManifest.xml/0
{ "file_path": "gallery/android/crane/src/main/AndroidManifest.xml", "repo_id": "gallery", "token_count": 174 }
807
// Copyright 2019 The Flutter team. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Only put constants shared between files here. import 'dart:typed_data'; import 'package:transparent_image/transparent_image.dart' as transparent_image; // Height of the 'Gallery' header const double galleryHeaderHeight = 64; // The font size delta for headline4 font. const double desktopDisplay1FontDelta = 16; // The width of the settingsDesktop. const double desktopSettingsWidth = 520; // Sentinel value for the system text scale factor option. const double systemTextScaleFactorOption = -1; // The splash page animation duration. const Duration splashPageAnimationDuration = Duration(milliseconds: 300); // Half the splash page animation duration. const Duration halfSplashPageAnimationDuration = Duration(milliseconds: 150); // Duration for settings panel to open on mobile. const Duration settingsPanelMobileAnimationDuration = Duration(milliseconds: 200); // Duration for settings panel to open on desktop. const Duration settingsPanelDesktopAnimationDuration = Duration(milliseconds: 600); // Duration for home page elements to fade in. const Duration entranceAnimationDuration = Duration(milliseconds: 200); // The desktop top padding for a page's first header (e.g. Gallery, Settings) const double firstHeaderDesktopTopPadding = 5.0; // A transparent image used to avoid loading images when they are not needed. final Uint8List kTransparentImage = transparent_image.kTransparentImage;
gallery/lib/constants.dart/0
{ "file_path": "gallery/lib/constants.dart", "repo_id": "gallery", "token_count": 393 }
808
// Copyright 2019 The Flutter team. 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/cupertino.dart'; import 'package:flutter_gen/gen_l10n/gallery_localizations.dart'; // BEGIN cupertinoSwitchDemo class CupertinoSwitchDemo extends StatefulWidget { const CupertinoSwitchDemo({super.key}); @override State<CupertinoSwitchDemo> createState() => _CupertinoSwitchDemoState(); } class _CupertinoSwitchDemoState extends State<CupertinoSwitchDemo> with RestorationMixin { final RestorableBool _switchValueA = RestorableBool(false); final RestorableBool _switchValueB = RestorableBool(true); @override String get restorationId => 'cupertino_switch_demo'; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_switchValueA, 'switch_valueA'); registerForRestoration(_switchValueB, 'switch_valueB'); } @override Widget build(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( automaticallyImplyLeading: false, middle: Text( localizations.demoSelectionControlsSwitchTitle, ), ), child: Center( child: Semantics( container: true, label: localizations.demoSelectionControlsSwitchTitle, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CupertinoSwitch( value: _switchValueA.value, onChanged: (value) { setState(() { _switchValueA.value = value; }); }, ), CupertinoSwitch( value: _switchValueB.value, onChanged: (value) { setState(() { _switchValueB.value = value; }); }, ), ], ), // Disabled switches Row( mainAxisAlignment: MainAxisAlignment.center, children: [ CupertinoSwitch( value: _switchValueA.value, onChanged: null, ), CupertinoSwitch( value: _switchValueB.value, onChanged: null, ), ], ), ], ), ), ), ); } } // END
gallery/lib/demos/cupertino/cupertino_switch_demo.dart/0
{ "file_path": "gallery/lib/demos/cupertino/cupertino_switch_demo.dart", "repo_id": "gallery", "token_count": 1413 }
809
// Copyright 2019 The Flutter team. 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:flutter_gen/gen_l10n/gallery_localizations.dart'; import 'package:gallery/demos/material/material_demo_types.dart'; // BEGIN listDemo class ListDemo extends StatelessWidget { const ListDemo({super.key, required this.type}); final ListDemoType type; @override Widget build(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text(localizations.demoListsTitle), ), body: Scrollbar( child: ListView( restorationId: 'list_demo_list_view', padding: const EdgeInsets.symmetric(vertical: 8), children: [ for (int index = 1; index < 21; index++) ListTile( leading: ExcludeSemantics( child: CircleAvatar(child: Text('$index')), ), title: Text( localizations.demoBottomSheetItem(index), ), subtitle: type == ListDemoType.twoLine ? Text(localizations.demoListsSecondary) : null, ), ], ), ), ); } } // END
gallery/lib/demos/material/list_demo.dart/0
{ "file_path": "gallery/lib/demos/material/list_demo.dart", "repo_id": "gallery", "token_count": 650 }
810
// Copyright 2019 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:animations/animations.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/gallery_localizations.dart'; // BEGIN fadeScaleTransitionDemo class FadeScaleTransitionDemo extends StatefulWidget { const FadeScaleTransitionDemo({super.key}); @override State<FadeScaleTransitionDemo> createState() => _FadeScaleTransitionDemoState(); } class _FadeScaleTransitionDemoState extends State<FadeScaleTransitionDemo> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController( value: 0, duration: const Duration(milliseconds: 150), reverseDuration: const Duration(milliseconds: 75), vsync: this, )..addStatusListener((status) { setState(() { // setState needs to be called to trigger a rebuild because // the 'HIDE FAB'/'SHOW FAB' button needs to be updated based // the latest value of [_controller.status]. }); }); } @override void dispose() { _controller.dispose(); super.dispose(); } bool get _isAnimationRunningForwardsOrComplete { switch (_controller.status) { case AnimationStatus.forward: case AnimationStatus.completed: return true; case AnimationStatus.reverse: case AnimationStatus.dismissed: return false; } } Widget _showExampleAlertDialog() { return Theme( data: Theme.of(context), child: _ExampleAlertDialog(), ); } @override Widget build(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Column( children: [ Text(localizations.demoFadeScaleTitle), Text( '(${localizations.demoFadeScaleDemoInstructions})', style: Theme.of(context) .textTheme .titleSmall! .copyWith(color: Colors.white), ), ], ), ), floatingActionButton: AnimatedBuilder( animation: _controller, builder: (context, child) { return FadeScaleTransition( animation: _controller, child: child, ); }, child: Visibility( visible: _controller.status != AnimationStatus.dismissed, child: FloatingActionButton( onPressed: () {}, child: const Icon(Icons.add), ), ), ), bottomNavigationBar: Column( mainAxisSize: MainAxisSize.min, children: [ const Divider(height: 0), Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( onPressed: () { showModal<void>( context: context, builder: (context) => _showExampleAlertDialog()); }, child: Text(localizations.demoFadeScaleShowAlertDialogButton), ), const SizedBox(width: 10), ElevatedButton( onPressed: () { if (_isAnimationRunningForwardsOrComplete) { _controller.reverse(); } else { _controller.forward(); } }, child: Text( _isAnimationRunningForwardsOrComplete ? localizations.demoFadeScaleHideFabButton : localizations.demoFadeScaleShowFabButton, ), ), ], ), ), ], ), ); } } class _ExampleAlertDialog extends StatelessWidget { @override Widget build(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; return AlertDialog( content: Text(localizations.demoFadeScaleAlertDialogHeader), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text(localizations.demoFadeScaleAlertDialogCancelButton), ), TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text(localizations.demoFadeScaleAlertDialogDiscardButton), ), ], ); } } // END fadeScaleTransitionDemo
gallery/lib/demos/reference/motion_demo_fade_scale_transition.dart/0
{ "file_path": "gallery/lib/demos/reference/motion_demo_fade_scale_transition.dart", "repo_id": "gallery", "token_count": 2258 }
811
{ "loading": "በመጫን ላይ", "deselect": "አትምረጥ", "select": "ምረጥ", "selectable": "ሊመረጥ የሚችል (ረዥም መጫን)", "selected": "ተመርጧል", "demo": "ቅንጭብ ማሳያ", "bottomAppBar": "የግርጌ መተግበሪያ አሞሌ", "notSelected": "አልተመረጠም", "demoCupertinoSearchTextFieldTitle": "የፍለጋ ጽሑፍ መስክ", "demoCupertinoPicker": "መራጮች", "demoCupertinoSearchTextFieldSubtitle": "የiOS-ቅጥ የፍለጋ ጽሑፍ መስክ", "demoCupertinoSearchTextFieldDescription": "ተጠቃሚው ጽሑፍ በማስገባት እንዲፈልግ የሚፈቅድ እና ጥቆማዎችን ማቅረብ እና ማጣራት የሚችል የፍለጋ ጽሑፍ መስክ።", "demoCupertinoSearchTextFieldPlaceholder": "የተወሰነ ጽሑፍ ያስገቡ", "demoCupertinoScrollbarTitle": "ማሸብለያ አሞሌ", "demoCupertinoScrollbarSubtitle": "የiOS-ቅጥ ማሸብለያ አሞሌ", "demoCupertinoScrollbarDescription": "የተሰጠውን ልጅ የሚጠቀልል ማሸብለያ አሞሌ", "demoTwoPaneItem": "ንጥል {value}", "demoTwoPaneList": "ዝርዝር", "demoTwoPaneFoldableLabel": "ሊታጠፍ የሚችል", "demoTwoPaneSmallScreenLabel": "ትንሽ ማያ ገፅ", "demoTwoPaneSmallScreenDescription": "ባለሁለት ፔን ትንሽ ማያ ገፅ ያለው መሣሪያ ላይ እንደዚህ ነው የሚሰራው።", "demoTwoPaneTabletLabel": "ጡባዊ / ዴስክቶፕ", "demoTwoPaneTabletDescription": "ባለሁለት ፔን እንደ ጡባዊ ወይም ዴስክቶፕ ዓይነት ተለቅ ያለ ማያ ገፅ ላይ እንደዚህ ነው የሚሰራው።", "demoTwoPaneTitle": "ባለሁለት-ፔን", "demoTwoPaneSubtitle": "ሊታጠፍ በሚችል ትልቅ እና ትንሽ ማያ ገጾች ላይ ምላሽ ሰጪ አቀማመጦች", "splashSelectDemo": "ቅንጭብ ማሳያ ይምረጡ", "demoTwoPaneFoldableDescription": "ባለሁለት ፔን ሊታጠፍ የሚችል መሣሪያ ላይ እንደዚህ ነው የሚሰራው።", "demoTwoPaneDetails": "ዝርዝሮች", "demoTwoPaneSelectItem": "አንድ ንጥል ይምረጡ", "demoTwoPaneItemDetails": "የንጥል {value} ዝርዝሮች", "demoCupertinoContextMenuActionText": "ተገቢ ሁኔታ ምናሌውን ለማየት የFlutter አርማውን መታ አድርገው ይያዙ።", "demoCupertinoContextMenuDescription": "አባለ-ነገሩ በረጅሙ ሲጫን የሚታይ የiOS-ቅጥ ሙሉ ገፅ ዕይታ ተገቢ ሁኔታ ምናሌ።", "demoAppBarTitle": "የመተግበሪያ አሞሌ", "demoAppBarDescription": "የመተግበሪያ አሞሌው አሁን ካለው ማያ ገፅ ጋር ተዛማጅ የሆነ ይዘትን እና እርምጃዎችን ያቀርባል። ለምርት ስያሜ፣ ለማያ ገፅ አርዕስቶች፣ ለአሰሳ እና ለእርምጃዎች ስራ ላይ ይውላል", "demoDividerTitle": "አካፋይ", "demoDividerSubtitle": "አካፋይ ይዘትን በዝርዝሮች እና በአቀማመጦች የሚያከፋፍል ቀጭን መስመር ነው።", "demoDividerDescription": "አካፋዮች ይዘትን ለመለየት በዝርዝሮች፣ በመሳቢያዎች እና በሌሎች ቦታዎች ውስጥ ጥቅም ላይ ሊውሉ ይችላሉ።", "demoVerticalDividerTitle": "አቀባዊ አካፋይ", "demoCupertinoContextMenuTitle": "ተገቢ ሁኔታ ምናሌ", "demoCupertinoContextMenuSubtitle": "የiOS-ቅጥ ተገቢ ሁኔታ ምናሌ", "demoAppBarSubtitle": "ከአሁኑ ማያ ገፅ ጋር የተያያዙ መረጃዎችን እና እርምጃዎችን ያሳያል", "demoCupertinoContextMenuActionOne": "እርምጃ አንድ", "demoCupertinoContextMenuActionTwo": "እርምጃ ሁለት", "demoDateRangePickerDescription": "የቁስ ንድፍ ከ..እስከ ቀን መራጭ የያዘ መገናኛን ያሳያል።", "demoDateRangePickerTitle": "ከ..እስከ ቀን መራጭ", "demoNavigationDrawerUserName": "የተጠቃሚ ስም", "demoNavigationDrawerUserEmail": "[email protected]", "demoNavigationDrawerText": "መሳቢያውን ለማየት ከጠርዙ ላይ ያንሸራትቱ ወይም የላይኛውን ግራ አዶ መታ ያድርጉ", "demoNavigationRailTitle": "የአሰሳ ሐዲድ", "demoNavigationRailSubtitle": "የአሰሳ ሐዲድን በመተግበሪያ ውስጥ በማሳየት ላይ", "demoNavigationRailDescription": "በአይነተኛነት በሶስት እና አምስት መካከል የሆነ ትንሽ የዕይታዎች ቁጥር መካከል ለመዳሰስ በመተግበሪያው ግራ ወይም ቀኝ እንዲታይ የታሰበ የቁስ መግብር።", "demoNavigationRailFirst": "መጀመሪያ", "demoNavigationDrawerTitle": "የአሰሳ መሳቢያ", "demoNavigationRailThird": "ሦስተኛ", "replyStarredLabel": "ኮከብ የተደረገባቸው", "demoTextButtonDescription": "በመጫን ጊዜ የጽሑፍ አዝራር የቀለም ርጭትን ያሳያል ነገር ግን አያነሳም። የጽሑፍ አዝራሮችን በመሳሪያ አሞሌዎች ላይ፣ በንግግሮች እና በመስመር ውስጥ ከድብዳብ ጋር ይጠቀሙ።", "demoElevatedButtonTitle": "ከፍ ያለ አዝራር", "demoElevatedButtonDescription": "ከፍ ያሉ አዝራሮች በአብዛኛው ዝርግ ለሆኑ አቀማመጦች ልኬት ያክላሉ። በባተሌ ወይም ሰፊ ቦታዎች ላይ ተግባራት ላይ አጽዕኖት ይሰጣሉ።", "demoOutlinedButtonTitle": "ባለቢጋር አዝራር", "demoOutlinedButtonDescription": "የቢጋር አዝራሮች የማያሳዩ ይሆኑና በሚጫኑበት ጊዜ ከፍ ይላሉ። አማራጭን፣ ሁለተኛ እርምጃን ለመጠቆም ብዙውን ጊዜ ከፍ ካሉ አዝራሮች ጋር ይጣመራሉ።", "demoContainerTransformDemoInstructions": "ካርዶች፣ ዝርዝሮች እና FAB", "demoNavigationDrawerSubtitle": "በመተግበሪያ አሞሌ ውስጥ መሳቢያ በማሳየት ላይ", "replyDescription": "ቀልጣፋ፣ የተተኮረበት የኢሜይል መተግበሪያ", "demoNavigationDrawerDescription": "በመተግበሪያው ውስጥ የአሰሳ አገናኞችን ለማሳየት ከማያ ገጹ ጠርዝ ላይ በአግድም የሚንሸራተት የቁሳዊ ንድፍ ፓነል።", "replyDraftsLabel": "ረቂቆች", "demoNavigationDrawerToPageOne": "ንጥል አንድ", "replyInboxLabel": "የገቢ መልዕክት ሳጥን", "demoSharedXAxisDemoInstructions": "ቀጣይ እና ተመለስ አዘራሮች", "replySpamLabel": "አይፈለጌ መልዕክት", "replyTrashLabel": "መጣያ", "replySentLabel": "ተልኳል", "demoNavigationRailSecond": "ሰከንድ", "demoNavigationDrawerToPageTwo": "ንጥል ሁለት", "demoFadeScaleDemoInstructions": "ሞዳል እና FAB", "demoFadeThroughDemoInstructions": "የታች ዳሰሳ", "demoSharedZAxisDemoInstructions": "የቅንብሮች አዶ አዝራር", "demoSharedYAxisDemoInstructions": "በ«ቅርብ በተጫወቱ» ደርድር", "demoTextButtonTitle": "የጽሑፍ አዝራር", "demoSharedZAxisBeefSandwichRecipeTitle": "የበሬ ስጋ ሳንድዊች", "demoSharedZAxisDessertRecipeDescription": "የጣፋጭ ምግብ አሰራር", "demoSharedYAxisAlbumTileSubtitle": "አርቲስት", "demoSharedYAxisAlbumTileTitle": "አልበም", "demoSharedYAxisRecentSortTitle": "በቅርቡ የተጫወቱ", "demoSharedYAxisAlphabeticalSortTitle": "ሀ-ፐ", "demoSharedYAxisAlbumCount": "268 አልበሞች", "demoSharedYAxisTitle": "የተጋራ y-ዘንግ", "demoSharedXAxisCreateAccountButtonText": "መለያ ፍጠር", "demoFadeScaleAlertDialogDiscardButton": "ጣለው", "demoSharedXAxisSignInTextFieldLabel": "ኢሜይል ወይም ስልክ ቁጥር", "demoSharedXAxisSignInSubtitleText": "በመለያዎ ይግቡ", "demoSharedXAxisSignInWelcomeText": "ሰላም David Park", "demoSharedXAxisIndividualCourseSubtitle": "በተናጠል የሚታይ", "demoSharedXAxisBundledCourseSubtitle": "የተጠቃለለ", "demoFadeThroughAlbumsDestination": "አልበሞች", "demoSharedXAxisDesignCourseTitle": "ንድፍ", "demoSharedXAxisIllustrationCourseTitle": "ስዕላዊ ማብራሪያ", "demoSharedXAxisBusinessCourseTitle": "ንግድ", "demoSharedXAxisArtsAndCraftsCourseTitle": "ስነ ጥበባት እና ዕደ ጥበባት", "demoMotionPlaceholderSubtitle": "ሁለተኛ ጽሁፍ", "demoFadeScaleAlertDialogCancelButton": "ይቅር", "demoFadeScaleAlertDialogHeader": "የማንቂያ ንግግር", "demoFadeScaleHideFabButton": "FAB ደብቅ", "demoFadeScaleShowFabButton": "FAB አሳይ", "demoFadeScaleShowAlertDialogButton": "ሞዳል አሳይ", "demoFadeScaleDescription": "የአደብዝዝ ስርዓተ-ጥለት እንደ ወደ የማያ ገጹ መሃል የሚደበዝዝ መገናኛ ላሉ በማያ ገጹ ወሰን ውስጥ ለሚገቡ ወይም ለሚወጡት ዩአይ ክፍለ-አካላት ያገለግላል።", "demoFadeScaleTitle": "አደብዝዝ", "demoFadeThroughTextPlaceholder": "123 ፎቶዎች", "demoFadeThroughSearchDestination": "ፍለጋ", "demoFadeThroughPhotosDestination": "ፎቶዎች", "demoSharedXAxisCoursePageSubtitle": "የተጠቃለሉ ምድቦች በምግብዎ ላይ እንደ ቡድን ሆነው ይታያሉ። ይህን በኋላ ላይ በማንኛውም ጊዜ መቀየር ይችላሉ።", "demoFadeThroughDescription": "በስርዓተ-ጥለት በኩል አደብዝዝ እርስ ከራሳቸው ጠንካራ ግንኙነት በሌላቸው የዩአይ ክፍለ-አካላት መካከል ላለ ሽግግር ስራ ላይ ይውላል።", "demoFadeThroughTitle": "በዚህ በኩል አደብዝዝ፦", "demoSharedZAxisHelpSettingLabel": "እገዛ", "demoMotionSubtitle": "ሁሉም ቅድሚያ የተገለጹ የሽግግር ስርዓተ ጥለቶች", "demoSharedZAxisNotificationSettingLabel": "ማሳወቂያዎች", "demoSharedZAxisProfileSettingLabel": "መገለጫ", "demoSharedZAxisSavedRecipesListTitle": "የተቀመጡ የምግብ አሰራሮች", "demoSharedZAxisBeefSandwichRecipeDescription": "የበሬ ስጋ ሳንድዊች አሰራር", "demoSharedZAxisCrabPlateRecipeDescription": "የሸርጣን ምግብ አሰራር", "demoSharedXAxisCoursePageTitle": "ትምህርቶችዎን ያሳልጡ", "demoSharedZAxisCrabPlateRecipeTitle": "ሸርጣን", "demoSharedZAxisShrimpPlateRecipeDescription": "የሽሪምፕ ምግብ አሰራር", "demoSharedZAxisShrimpPlateRecipeTitle": "ሽሪምፕ", "demoContainerTransformTypeFadeThrough": "በዚህ በኩል አደብዝዝ፦", "demoSharedZAxisDessertRecipeTitle": "ጣፋጭ ምግብ", "demoSharedZAxisSandwichRecipeDescription": "የበርገር አሰራር", "demoSharedZAxisSandwichRecipeTitle": "ሳንድዊች", "demoSharedZAxisBurgerRecipeDescription": "የበርገር አሰራር", "demoSharedZAxisBurgerRecipeTitle": "በርገር", "demoSharedZAxisSettingsPageTitle": "ቅንብሮች", "demoSharedZAxisTitle": "የተጋራ z-ዘንግ", "demoSharedZAxisPrivacySettingLabel": "ግላዊነት", "demoMotionTitle": "እንቅስቃሴ", "demoContainerTransformTitle": "መያዣን መቀየር", "demoContainerTransformDescription": "የመያዣው መቀየር ስርዓተ-ጥለት መያዣን በሚያካትቱ ዩአይ አካላት መካከል ላሉት ሽግግሮች የተነደፈ ነው። ይህ ስርዓተ-ጥለት በሁለት ዩአይ አካላት መካከል የሚታይ ግንኙነትን ይፈጥራል", "demoContainerTransformModalBottomSheetTitle": "የአደብዝዝ ሁነታ", "demoContainerTransformTypeFade": "አደብዝዝ", "demoSharedYAxisAlbumTileDurationUnit": "ደቂቃ", "demoMotionPlaceholderTitle": "ርዕስ", "demoSharedXAxisForgotEmailButtonText": "ኢሜይል ረስተዋል?", "demoMotionSmallPlaceholderSubtitle": "ሁለተኛ", "demoMotionDetailsPageTitle": "የዝርዝሮች ገፅ", "demoMotionListTileTitle": "የዝርዝር ንጥል", "demoSharedAxisDescription": "የተጋራ የዘንግ ስርዓተ-ጥለት የቦታ ወይም የዳሰሳ ግንኙነት ባላቸው ዩአይ ክፍለ-አካላት መካከል ላሉት ሽግግሮች ያገለግላል። በክፍለ-አካላት መካከል ያለውን ግንኙነት ለማጠናከር ይህ ስርዓተ-ጥለት በ x፣ y ወይም z ዘንግ ላይ የጋራ ሽግግርን ይጠቀማል።", "demoSharedXAxisTitle": "የተጋራ x-ዘንግ", "demoSharedXAxisBackButtonText": "ተመለስ", "demoSharedXAxisNextButtonText": "ቀጣይ", "demoSharedXAxisCulinaryCourseTitle": "የምግብ አሰራር", "githubRepo": "{repoName} የGitHub ውሂብ ማከማቻ", "fortnightlyMenuUS": "አሜሪካ", "fortnightlyMenuBusiness": "ንግድ", "fortnightlyMenuScience": "ሳይንስ", "fortnightlyMenuSports": "ስፖርት", "fortnightlyMenuTravel": "ጉዞ", "fortnightlyMenuCulture": "ባህል", "fortnightlyTrendingTechDesign": "የቴክ ንድፍ", "rallyBudgetDetailAmountLeft": "የቀረ መጠን", "fortnightlyHeadlineArmy": "አረንጓዴውን ሠራዊት ከውስጥ መለወጥ", "fortnightlyDescription": "ይዘት ላይ ያተኮረ የዜና መተግበሪያ", "rallyBillDetailAmountDue": "መከፈል ያለበት መጠን", "rallyBudgetDetailTotalCap": "ጠቅላላ ካፒታል", "rallyBudgetDetailAmountUsed": "ጥቅም ላይ የዋለው መጠን", "fortnightlyTrendingHealthcareRevolution": "የጤና እንክብካቤ አብዮት", "fortnightlyMenuFrontPage": "የፊት ገፅ", "fortnightlyMenuWorld": "ዓለም", "rallyBillDetailAmountPaid": "የተከፈለው መጠን", "fortnightlyMenuPolitics": "ፖለቲካ", "fortnightlyHeadlineBees": "የእርሻ መሬት ንቦች እጥረት አለ", "fortnightlyHeadlineGasoline": "የናፍጣ የወደፊት ዕጣ ፈንታ", "fortnightlyTrendingGreenArmy": "አረንጓዴ ሰራዊት", "fortnightlyHeadlineFeminists": "የሴት መብት ተሟጋቾች ወገንተኝነት ላይ ያላቸው አቋም", "fortnightlyHeadlineFabrics": "የወደፊት ጨርቆችን ለማምረት ነዳፊዎች ቴክኖሎጂን ይጠቀማሉ", "fortnightlyHeadlineStocks": "አክሲዮኖች ባሉበት ሲቆሙ ብዙዎች ምንዛሬን ያያሉ", "fortnightlyTrendingReform": "ለውጥ", "fortnightlyMenuTech": "ቴክኖሎጂ", "fortnightlyHeadlineWar": "በጦርነት ጊዜ የተከፋፈሉ የአሜሪካ ሕይወቶች", "fortnightlyHeadlineHealthcare": "ጸጥተኛው፣ ግን ኃይለኛው የጤና እንክብካቤ አብዮት", "fortnightlyLatestUpdates": "የቅርብ ጊዜ ዝማኔዎች", "fortnightlyTrendingStocks": "አክሲዮኖች", "rallyBillDetailTotalAmount": "ጠቅላላ መጠን", "demoCupertinoPickerDateTime": "ቀን እና ሰዓት", "signIn": "ግባ", "dataTableRowWithSugar": "{value} ከስኳር ጋር", "dataTableRowApplePie": "የፖም ፓይ", "dataTableRowDonut": "ዶናት", "dataTableRowHoneycomb": "የማር እሸት", "dataTableRowLollipop": "ሊሎፖፕ", "dataTableRowJellyBean": "ጀሊ ቢን", "dataTableRowGingerbread": "ጂንጀርብሬድ", "dataTableRowCupcake": "ዘቢብ ኬክ", "dataTableRowEclair": "ኢክሌር", "dataTableRowIceCreamSandwich": "አይስ ክሬም ሳንድዊች", "dataTableRowFrozenYogurt": "ቀዝቃዛ እርጎ", "dataTableColumnIron": "ብረት (%)", "dataTableColumnCalcium": "ካልሲየም (%)", "dataTableColumnSodium": "ሶዲየም (ሚግ)", "demoTimePickerTitle": "የሰዓት መራጭ", "demo2dTransformationsResetTooltip": "ቅየራዎችን ዳግም ያቀናብሩ", "dataTableColumnFat": "ስብ (ግ)", "dataTableColumnCalories": "ካሎሪ", "dataTableColumnDessert": "መክሰስ (1 ሳህን)", "cardsDemoTravelDestinationLocation1": "ታንጃቩር፣ ታሚል ናዱ", "demoTimePickerDescription": "የቁሳዊ ንድፍ ሰዓት መራጭ የያዘ ማሳያን ያሳያል።", "demoPickersShowPicker": "መራጭን አሳይ", "demoTabsScrollingTitle": "ሽብለላ", "demoTabsNonScrollingTitle": "ሽብለላ ያልሆነ", "craneHours": "{hours,plural,=1{1 ሰ}other{{hours} ሰ}}", "craneMinutes": "{minutes,plural,=1{1 ደ}other{{minutes}ደ}}", "craneFlightDuration": "{hoursShortForm} {minutesShortForm}", "dataTableHeader": "ስነ ምግብ", "demoDatePickerTitle": "ቀን መራጭ", "demoPickersSubtitle": "የቀን እና ሰዓት ምርጫ", "demoPickersTitle": "መራጮች", "demo2dTransformationsEditTooltip": "ስድርን አርትዕ ያድርጉ", "demoDataTableDescription": "የውሂብ ሠንጠረዦች መረጃን የፍርግርግ ዓይነት በሆነ የረድፎች እና አምዶች ቅርጸት ያሳያሉ። ተጠቃሚዎች ስርዓተ ጥለቶችን እና ግንዛቤዎችን መፈለግ እንዲችሉ መረጃን ለመቃኘት ቀላል በሆነ መንገድ ያደራጁታል።", "demo2dTransformationsDescription": "ስድሮችን አርትዕ ለማድረግ መታ ያድርጉ እና በትዕይንቱ አካባቢ ለማንቀሳቀስ የእጅ ውዝዋዜዎችን ይጠቀሙ። ለማንፏቀቅ ይጎትቱ፣ ለማጉላት ይቆንጥጡ፣ በሁለት ጣቶች ያሽከርክሩ። ወደ ማስጀመሪያው አቀማመጥ ለመመለስ የዳግም አቀናብር አዝራሩን ይጫኑ።", "demo2dTransformationsSubtitle": "ማንፏቀቅ፣ ማጉላት፣ ማሽከርከር", "demo2dTransformationsTitle": "2ል ቅየራዎች", "demoCupertinoTextFieldPIN": "ፒን", "demoCupertinoTextFieldDescription": "የጽሁፍ መስክ ተጠቃሚው በሃርድዌር ቁልፍ ሰሌዳ ወይም በማያ ገፅ ላይ ቁልፍ ሰሌዳ ጽሁፍ እንዲያስገቡ ያስችላቸዋል።", "demoCupertinoTextFieldSubtitle": "የiOS-ቅጥ የጽሑፍ መስኮች", "demoCupertinoTextFieldTitle": "የጽሑፍ መስኮች", "demoDatePickerDescription": "የቁሳዊ ንድፍ ቀን መራጭ የያዘ ማሳያን ያሳያል።", "demoCupertinoPickerTime": "ሰዓት", "demoCupertinoPickerDate": "ቀን", "demoCupertinoPickerTimer": "ሰዓት ቆጣሪ", "demoCupertinoPickerDescription": "የiOS-ቅጥ ያለው መራጭ ምግብር ሕብረቁምፊዎችን፣ ቀኖችን፣ ሰዓቶችን ወይም ሁለቱም ቀን እና ሰዓት ለመምረጥ ስራ ላይ መዋል ይችላሉ።", "demoCupertinoPickerSubtitle": "የiOS-ቅጥ መራጮች", "demoCupertinoPickerTitle": "መራጮች", "dataTableRowWithHoney": "{value} ከማር ጋር", "cardsDemoTravelDestinationCity2": "ቼቲናድ", "bannerDemoResetText": "ሰንደቁን ዳግም ያስጀምሩት", "bannerDemoMultipleText": "በርካታ እርምጃዎች", "bannerDemoLeadingText": "መሪ አዶ", "dismiss": "አሰናብት", "cardsDemoTappable": "መታ ሊደረግ የሚችል", "cardsDemoSelectable": "ሊመረጥ የሚችል (ተጭኖ መያዝ)", "cardsDemoExplore": "አስስ", "cardsDemoExploreSemantics": "አስስ {destinationName}", "cardsDemoShareSemantics": "አጋራ {destinationName}", "cardsDemoTravelDestinationTitle1": "በታሚል ናዱ ውጽጥ የሚጎበኙ ከፍተኛዎቹ 10 ከተማዎች", "cardsDemoTravelDestinationDescription1": "10 ቁጥር", "cardsDemoTravelDestinationCity1": "ታንጃቩር", "dataTableColumnProtein": "ፕሮቲን (ግ)", "cardsDemoTravelDestinationTitle2": "የደቡባዊ ህንድ ጠቢባን", "cardsDemoTravelDestinationDescription2": "ሐር ፈታዮች", "bannerDemoText": "የይለፍ ቃልዎ በሌላኛው መሣሪያዎ ላይ ተዘምኗል። እባክዎ እንደገና ይግቡ።", "cardsDemoTravelDestinationLocation2": "ሲቫጋንጋ፣ ታሚል ናዱ", "cardsDemoTravelDestinationTitle3": "ብሪሃዲስቫራ ቤተ-መቅደስ", "cardsDemoTravelDestinationDescription3": "ቤተ-መቅደሶች", "demoBannerTitle": "ሰንደቅ", "demoBannerSubtitle": "በአንድ ዝርዝር ውስጥ ሰንደቅን ማሳየት", "demoBannerDescription": "አንድ ሰንደቅ አስፈላጊና እጥር ምጥን ያለ መልዕክት ያሳያል፣ እና ተጠቃሚዎች የሆነ ነገር የሚያደርጓቸውን እርምጃዎች ያቀርብላቸዋል (ወይም ሰንደቁን ያሰናብታል)። እሱን ለማሰናበት የተጠቃሚ እርምጃ ያስፈልጋል።", "demoCardTitle": "ካርዶች", "demoCardSubtitle": "የተድቦለቦሉ ጫፎች ያላቸው የመነሻ ነጥብ ካርዶች", "demoCardDescription": "ካርድ ማለት አንዳንድ ተዛማጅ መረጃን ለመወከል ስራ ላይ የሚውል የቁሳዊ ሉህ ነው፣ ለምሳሌ፣ አልበም፣ ጂዮግራፊያዊ አካባቢ፣ ምግብ፣ የእውቂያ ዝርዝሮች፣ ወዘተ።", "demoDataTableTitle": "የውሂብ ሠንጠረዦች", "demoDataTableSubtitle": "የመረጃ ረድፎች እና አምዶች", "dataTableColumnCarbs": "ካርቦሃድሬት (ግ)", "placeTanjore": "ታንጆሬ", "demoGridListsTitle": "ፍርግርግ ዝርዝሮች", "placeFlowerMarket": "የአበባ ገበያ", "placeBronzeWorks": "የነሐስ ሥራዎች", "placeMarket": "ገበያ", "placeThanjavurTemple": "የታንጁቩር ቤተ መቅደስ", "placeSaltFarm": "የጨው እርሻ", "placeScooters": "ዶቅደቄዎች", "placeSilkMaker": "ሐር ሠሪ", "placeLunchPrep": "የምሳ ዝግጅት", "placeBeach": "የባሕር ዳርቻ", "placeFisherman": "ዓሣ አስጋሪ", "demoMenuSelected": "ተመርጧል፦ {value}", "demoMenuRemove": "አስወግድ", "demoMenuGetLink": "አገናኝ ያግኙ", "demoMenuShare": "አጋራ", "demoBottomAppBarSubtitle": "ዳሰሳን እና እርምጃዎችን በግርጌው ላይ ያሳያል", "demoMenuAnItemWithASectionedMenu": "ከተከፋፈለ ምናሌ ጋር ያለ ንጥል", "demoMenuADisabledMenuItem": "የተሰናከለ ምናሌ ንጥል", "demoLinearProgressIndicatorTitle": "የቀጥታ መስመር የግስጋሴ ጠቋሚ", "demoMenuContextMenuItemOne": "ዓውድ ምናሌ ንጥል አንድ", "demoMenuAnItemWithASimpleMenu": "ንጥል ከቀላል ምናሌ ጋር", "demoCustomSlidersTitle": "ብጁ ተንሸራታቾች", "demoMenuAnItemWithAChecklistMenu": "ንጥል ከማረጋገጫ ምናሌ ጋር", "demoCupertinoActivityIndicatorTitle": "የእንቅስቃሴ ጠቋሚ", "demoCupertinoActivityIndicatorSubtitle": "iOS-ቅጥ እንቅስቃሴ ጠቋሚዎች", "demoCupertinoActivityIndicatorDescription": "በሰዓት አቅጣጫ የሚሽከረከር የiOS-ቅጥ እንቅስቃሴ ጠቋሚ", "demoCupertinoNavigationBarTitle": "የአሰሳ አሞሌ", "demoCupertinoNavigationBarSubtitle": "iOS-ቅጥ የአሰሳ ምናሌ", "demoCupertinoNavigationBarDescription": "የiOS-ቅጥ አሰሳ ምናሌ። የአሰሳ ምናሌ በመሣሪያ አሞሌ መሃል የገጽ አርዕስትን በውስጡ ቢያንስ የያዘ የመሣሪያ አሞሌ ነው።", "demoCupertinoPullToRefreshTitle": "ለማደስ ይጎትቱ", "demoCupertinoPullToRefreshSubtitle": "መቆጣጠሪያን ለማደስ የiOS-ቅጥ መጎተት", "demoCupertinoPullToRefreshDescription": "የይዘት መቆጣጠሪያን ለማደስ የiOS-ቅጥ መጎተትን ተግባራዊ የሚያደርግ ምግብር።", "demoProgressIndicatorTitle": "የግስጋሴ ጠቋሚዎች", "demoProgressIndicatorSubtitle": "ቀጥታ መስመር፣ ክበባዊ፣ ያልተወሰነ", "demoCircularProgressIndicatorTitle": "ክበባዊ የግስጋሴ ጠቋሚ", "demoCircularProgressIndicatorDescription": "መተግበሪያው ባተሌ እንደሆነ ለመጠቆም የሚሽከረከር የቁስ ንድፍ ክበባዊ ግስጋሴ ጠቋሚ።", "demoMenuFour": "አራት", "demoLinearProgressIndicatorDescription": "የቁስ ንድፍ የቀጥታ መስመር የግስጋሴ ጠቋሚ፣ በተጨማሪ የግስጋሴ አሞሌ በመባል የሚታወቅ", "demoTooltipTitle": "የመሣሪያ ጥቆማዎች", "demoTooltipSubtitle": "በረዥም መጫን ወይም ማንዣበብ ላይ የሚታይ አጭር መልዕክት", "demoTooltipDescription": "የመሣሪያ ጥቆማዎች የአዝራርን ወይም ሌላ የተጠቃሚ በይነገጽ እርምጃ ለማብራራት የሚያግዙ የጽሑፍ መሰየሚያዎችን ያቀርባሉ። የመሣሪያ ጥቆማዎች ተጠቃሚዎች አንድ አባለ ነገር ላይ ሲያንዣብቡ፣ ሲያተኩሩ ወይም በረዥም ሲጫኑ መረጃ ሰጪ ጽሑፍን ያሳያል።", "demoTooltipInstructions": "የመሣሪያ ጥቆማን ለማሳየት ረዥም ይጫኑ ወይም ያንዣብቡ።", "placeChennai": "ቸናይ", "demoMenuChecked": "ምልክት ተደርጎበታል፦ {value}", "placeChettinad": "የቼቲናድ", "demoMenuPreview": "ቅድመ ዕይታ", "demoBottomAppBarTitle": "የግርጌ መተግበሪያ አሞሌ", "demoBottomAppBarDescription": "የግርጌ መተግበሪያ አሞሌዎች ለግርጌ ዳሰሳ መሳቢያ እና እስከ አራት ለሚደርሱ እርምጃዎች ለተንሳፋፊ የእርምጃ አዝራር ጨምሮ መዳረሻን ያቀርባሉ።", "bottomAppBarNotch": "ስርጉድ", "bottomAppBarPosition": "ተንሳፋፊ የድርጊት አዝራር አቀማመጥ", "bottomAppBarPositionDockedEnd": "ተሰክቷል - ማብቂያ", "bottomAppBarPositionDockedCenter": "ተሰክቷል - መሃል", "bottomAppBarPositionFloatingEnd": "ተንሳፋፊ - ማብቂያ", "bottomAppBarPositionFloatingCenter": "ተንሳፋፊ - መሃል", "demoSlidersEditableNumericalValue": "አርትዕ ሊደረግ የሚችል አሃዛዊ እሴት", "demoGridListsSubtitle": "የረድፍ እና የዓምድ አቀማመጥ", "demoGridListsDescription": "ፍርግርግ ዝርዝሮች ተመሳሳይነት ያለውን ውሂብ በተለይ ደግሞ ምስሎች ለማቅረብ በጣም የተሻሉ አማራጮች ናቸው። በፍርግርግ ዝርዝር ውስጥ ያለው እያንዳንዱ ንጥል ስድር ይባላል።", "demoGridListsImageOnlyTitle": "ምስል ብቻ", "demoGridListsHeaderTitle": "ከአርዕስት ጋር", "demoGridListsFooterTitle": "ከግርጌ ማስታወሻ ጋር", "demoSlidersTitle": "ተንሸራታቾች", "demoSlidersSubtitle": "በጣት ጠረግ በማድረግ እሴት ለመምረጥ የሚሆኑ ምግብሮች", "demoSlidersDescription": "ተጠቃሚዎች አንድን ነጠላ እሴት ሊመርጡ የሚችሉበት አሞሌ ላይ ያሉትን የእሴቶች ክልል ተንሸራታቾች ያንጸባርቃሉ። እንደ ድምፅ፣ ብሩህነት የመሳሰሉ ቅንብሮችን ለማስተካከል ወይም የምስል ማጣሪያዎችን ተፈጻሚ ለማድረግ ተመራጭ ናቸው።", "demoRangeSlidersTitle": "የክልል ተንሸራታቾች", "demoRangeSlidersDescription": "ተንሸራታቾች ከአሞሌ ጋር የእሴቶችን ክልል ያንጸባርቃሉ። የእሴቶችን ክልል በሚያንጸባርቀው አሞሌ ሁለቱም ማብቂያዎች ላይ አዶዎች ሊኖራቸው ይችላል። እንደ ድምፅ፣ ብሩህነት የመሳሰሉ ቅንብሮችን ለማስተካከል ወይም የምስል ማጣሪያዎችን ተፈጻሚ ለማድረግ ተመራጭ ናቸው።", "demoMenuAnItemWithAContextMenuButton": "ከዓውድ ምናሌ ጋር ያለ ንጥል", "demoCustomSlidersDescription": "ተጠቃሚዎች አንድን ነጠላ እሴት ወይም የእሴቶች ክልል ሊመርጡ የሚችሉበት አሞሌ ላይ ያሉትን የእሴቶች ክልል ተንሸራታቾች ያንጸባርቃሉ። ተንሸራታቾቹ ገጽታ ሊኖራቸው እና ብጁ ሊደረጉ ይችላሉ።", "demoSlidersContinuousWithEditableNumericalValue": "አርትዕ ሊደረግ ከሚችል አሃዛዊ እሴት ጋር ቀጣይ", "demoSlidersDiscrete": "ውሱን", "demoSlidersDiscreteSliderWithCustomTheme": "ውሱን ተንሸራታች ከብጁ ገጽታ ጋር", "demoSlidersContinuousRangeSliderWithCustomTheme": "ቀጣይ የክልል ተንሸራታች ከብጁ ገጽታ ጋር", "demoSlidersContinuous": "ተከታታይ", "placePondicherry": "ፖንዲቼሪ", "demoMenuTitle": "ምናሌ", "demoContextMenuTitle": "የዓውድ ምናሌ", "demoSectionedMenuTitle": "በክፍል የተከፋፈለ ምናሌ", "demoSimpleMenuTitle": "ቀላል ምናሌ", "demoChecklistMenuTitle": "የማረጋገጫ ዝርዝር ምናሌ", "demoMenuSubtitle": "የምናሌ አዝራሮች እና ቀላል ምናሌዎች", "demoMenuDescription": "ምናሌ በጊዜያዊ ቦታ ላይ የምርጫዎችን ዝርዝር ያሳያል። ተጠቃሚዎች ከአዝራር፣ ከድርጊት ወይም ሌላ መቆጣጠሪያ ጋር መስተጋብር ሲፈጽሙ ብቅ ይላሉ።", "demoMenuItemValueOne": "ምናሌ ንጥል አንድ", "demoMenuItemValueTwo": "ምናሌ ንጥል ሁለት", "demoMenuItemValueThree": "ምናሌ ንጥል ሦስት", "demoMenuOne": "አንድ", "demoMenuTwo": "ሁለት", "demoMenuThree": "ሦስት", "demoMenuContextMenuItemThree": "የዓውድ ምናሌ ንጥል ሦስት", "demoCupertinoSwitchSubtitle": "iOS-ቅጥ ማብሪያ/ማጥፊያ", "demoSnackbarsText": "ይህ ቁርስ ቤት ነው።", "demoCupertinoSliderSubtitle": "የiOS-ቅጥ ተንሸራታች", "demoCupertinoSliderDescription": "ተንሸራታች ተጠቅመው ወይም ቀጣይነት ካለው ወይም ከውሱን የእሴቶች ስብስብ አንዱን መምረጥ ይቻላል።", "demoCupertinoSliderContinuous": "ቀጣይነት ያለው፦ {value}", "demoCupertinoSliderDiscrete": "ውሱን፦ {value}", "demoSnackbarsAction": "እርስዎ የቅሩስ ቤት ድርጊቱን ተጭነዋል።", "backToGallery": "ወደ ማዕከለ-ስዕላት ተመለስ", "demoCupertinoTabBarTitle": "የትር አሞሌ", "demoCupertinoSwitchDescription": "ማብሪያ/ማጥፊያ አንድ ነጠላ ቅንብርን ለማብራት/ለማጥፋት ስራ ላይ ይውላል።", "demoSnackbarsActionButtonLabel": "ድርጊት", "cupertinoTabBarProfileTab": "መገለጫ", "demoSnackbarsButtonLabel": "ቁርስ ቤት አሳይ", "demoSnackbarsDescription": "ቁርስ ቤቶች አንድ መተግበሪያ ስላከናወነው ወይም ስለሚያከናውነው ሂደት ለተጠቃሚዎች ያሳውቃል። በማያ ገጹ ግርጌ አካባቢ ለጊዜው ይታያሉ። የተጠቃሚውን ተሞክሮ ማቋረጥ የለባቸውም፣ እና ለመጥፋት የተጠቃሚው ግቤት አያስፈልጋቸውም።", "demoSnackbarsSubtitle": "ቁርስ ቤት በማያ ገጹ ግርጌ ላይ መልዕክቶችን ያሳያል", "demoSnackbarsTitle": "ቁርስ ቤት", "demoCupertinoSliderTitle": "ተንሸራታች", "cupertinoTabBarChatTab": "ውይይት", "cupertinoTabBarHomeTab": "መነሻ", "demoCupertinoTabBarDescription": "የiOS-ቅጥ የታች ዳሰሳ ትር አሞሌ። አንድ ትር ገቢር ሆኖ፣ በነባሪነት የመጀመሪያው ትር፣ በርካታ ትሮችን ያሳያል።", "demoCupertinoTabBarSubtitle": "የiOS-ቅጥ የታች ትር አሞሌ", "demoOptionsFeatureTitle": "አማራጮችን ይመልከቱ", "demoOptionsFeatureDescription": "ለዚህ ተግባራዊ ማሳያ ሊገኙ የሚችሉ አማራጮችን ለማየት እዚህ ላይ መታ ያድርጉ።", "demoCodeViewerCopyAll": "ሁሉንም ቅዳ", "shrineScreenReaderRemoveProductButton": "{product} አስወግድ", "shrineScreenReaderProductAddToCart": "ወደ ጋሪ አክል", "shrineScreenReaderCart": "{quantity,plural,=0{የግዢ ዕቃዎች ጋሪ፣ ምንም ንጥሎች የሉም}=1{የግዢ ዕቃዎች ጋሪ፣ 1 ንጥል}other{የግዢ ዕቃዎች ጋሪ፣ {quantity} ንጥሎች}}", "demoCodeViewerFailedToCopyToClipboardMessage": "ወደ ቅንጥብ ሰሌዳ መቅዳት አልተሳካም፦ {error}", "demoCodeViewerCopiedToClipboardMessage": "ወደ ቅንጥብ ሰሌዳ ተገልብጧል።", "craneSleep8SemanticLabel": "ከባህር ዳርቻ በላይ ባለ አምባ ላይ ያሉ የማያውያን ፍርስራሾች", "craneSleep4SemanticLabel": "ከተራራዎች ፊት ያለ የሐይቅ ዳርቻ ሆቴል", "craneSleep2SemanticLabel": "የማቹ ፒቹ ምሽግ", "craneSleep1SemanticLabel": "ሁሌ ለምለም ዛፎች ባሉት በረዷሟ መሬት ላይ ያለ ሻሌት ቤት", "craneSleep0SemanticLabel": "የውሃ ላይ ባንግሎው ቤት", "craneFly13SemanticLabel": "ዘንባባ ያሉት የባህር ጎን መዋኛ", "craneFly12SemanticLabel": "ዘንባባ ዛፎች ያለው መዋኛ", "craneFly11SemanticLabel": "ባህር ላይ ያለ ባለጡብ ፋኖ ቤት", "craneFly10SemanticLabel": "የአል-አዝሃር መስጊድ ማማዎች በጸሐይ መጥለቂያ ጊዜ", "craneFly9SemanticLabel": "አንድ አንጋፋ ሰማያዊ መኪናን ተደግፎ የቆመ ሰው", "craneFly8SemanticLabel": "ሱፐርትሪ ግሮቭ", "craneEat9SemanticLabel": "ኬኮች ያሉት የካፌ ካውንተር", "craneEat2SemanticLabel": "በርገር", "craneFly5SemanticLabel": "ከተራራዎች ፊት ያለ የሐይቅ ዳርቻ ሆቴል", "demoSelectionControlsSubtitle": "አመልካች ሳጥኖች፣ የሬዲዮ አዝራሮች እና መቀያየሪያዎች", "craneEat10SemanticLabel": "ትልቅ ፓስትራሚ ሳንድዊች የያዘች ሴት", "craneFly4SemanticLabel": "የውሃ ላይ ባንግሎው ቤት", "craneEat7SemanticLabel": "የመጋገሪያ መግቢያ", "craneEat6SemanticLabel": "ሽሪምፕ ሳህን", "craneEat5SemanticLabel": "ኪነ ጥበባዊ የምግብ ቤት መቀመጫ አካባቢ", "craneEat4SemanticLabel": "ቼኮሌት ጣፋጭ ምግብ", "craneEat3SemanticLabel": "የኮሪያ ታኮ", "craneFly3SemanticLabel": "የማቹ ፒቹ ምሽግ", "craneEat1SemanticLabel": "ባዶ መጠጥ ቤት ከመመገቢያ ዓይነት መቀመጫዎች ጋር", "craneEat0SemanticLabel": "በእንጨት በሚነድድ ምድጃ ውስጥ ፒዛ", "craneSleep11SemanticLabel": "ታይፔይ 101 ሰማይ ጠቀስ ህንፃ", "craneSleep10SemanticLabel": "የአል-አዝሃር መስጊድ ማማዎች በጸሐይ መጥለቂያ ጊዜ", "craneSleep9SemanticLabel": "ባህር ላይ ያለ ባለጡብ ፋኖ ቤት", "craneEat8SemanticLabel": "የክሮውፊሽ ሳህን", "craneSleep7SemanticLabel": "በሪቤሪያ አደባባይ ላይ ያሉ ባለቀለም አፓርታማዎች", "craneSleep6SemanticLabel": "ዘንባባ ዛፎች ያለው መዋኛ", "craneSleep5SemanticLabel": "በአንድ ሜዳ ላይ ድንኳን", "settingsButtonCloseLabel": "ቅንብሮችን ዝጋ", "demoSelectionControlsCheckboxDescription": "አመልካች ሳጥኖች ተጠቃሚው ከአንድ ስብስብ በርካታ አማራጮችን እንዲሰበስብ ያስችለዋል። የአንድ መደበኛ አመልካች ሳጥኑ እሴት እውነት ወይም ሐሰት ነው፣ እና የአንድ ባለሶስት-ሁኔታ እሴት እንዲሁም አልቦ መሆን ይችላል።", "settingsButtonLabel": "ቅንብሮች", "demoListsTitle": "ዝርዝሮች", "demoListsSubtitle": "የዝርዝር አቀማመጦችን በመሸብለል ላይ", "demoListsDescription": "በተለምዶ የተወሰነ ጽሑፍና እንዲሁም መሪ ወይም ተከታይ አዶ የያዘ አንድ ባለነጠላ ቋሚ ረድፍ።", "demoOneLineListsTitle": "አንድ መስመር", "demoTwoLineListsTitle": "ሁለት መስመሮች", "demoListsSecondary": "ሁለተኛ ጽሁፍ", "demoSelectionControlsTitle": "የምርጫ መቆጣጠሪያዎች", "craneFly7SemanticLabel": "ራሽሞር ተራራ", "demoSelectionControlsCheckboxTitle": "አመልካች ሳጥን", "craneSleep3SemanticLabel": "አንድ አንጋፋ ሰማያዊ መኪናን ተደግፎ የቆመ ሰው", "demoSelectionControlsRadioTitle": "ሬዲዮ", "demoSelectionControlsRadioDescription": "የሬዲዮ ዝራሮች ተጠቃሚው ከአንድ ስብስብ ውስጥ አንድ አማራጭ እንዲፈጥር ያስችለዋል። ተጠቃሚው ሁሉንም የሚገኙ አማራጮች ጎን ለጎን ማየት አለበት ብለው የሚያስቡ ከሆነ የሬዲዮ አዝራሮችን የሚመለከተውን ብቻ ለመምረጥ ይጠቀሙባቸው።", "demoSelectionControlsSwitchTitle": "ቀይር", "demoSelectionControlsSwitchDescription": "የማብሪያ/ማጥፊያ መቀያየሪያዎች የነጠላ ቅንብሮች አማራጭ ሁኔታን ይቀያይራሉ። መቀያየሪያው የሚቆጣጠረውን አማራጭና እንዲሁም ያለበትን ሁኔታ ከተጓዳኙ የውስጠ-መስመር መሰየሚያው ግልፅ መሆን አለበት።", "craneFly0SemanticLabel": "ሁሌ ለምለም ዛፎች ባሉት በረዷሟ መሬት ላይ ያለ ሻሌት ቤት", "craneFly1SemanticLabel": "በአንድ ሜዳ ላይ ድንኳን", "craneFly2SemanticLabel": "ከበረዷማ ተራራ ፊት ያሉ የጸሎት ባንዲራዎች", "craneFly6SemanticLabel": "የፓላሲዮ ደ ቤያ አርቴስ የአየር ላይ እይታ", "rallySeeAllAccounts": "ሁሉንም መለያዎች ይመልከቱ", "rallyBillAmount": "የ{billName} {amount} መክፈያ ጊዜ {date} ደርሷል።", "shrineTooltipCloseCart": "ጋሪን ዝጋ", "shrineTooltipCloseMenu": "ምናሌን ዝጋ", "shrineTooltipOpenMenu": "ምናሌ ክፈት", "shrineTooltipSettings": "ቅንብሮች", "shrineTooltipSearch": "ፍለጋ", "demoTabsDescription": "ትሮች በተለያዩ ማያ ገጾች፣ የውሂብ ስብስቦች እና ሌሎች መስተጋብሮች ዙሪያ ይዘትን ያደራጃል", "demoTabsSubtitle": "ትሮች ራሳቸውን ከቻሉ ተሸብላይ ዕይታዎች ጋር", "demoTabsTitle": "ትሮች", "rallyBudgetAmount": "{budgetName} በጀት {amountUsed} ከ{amountTotal} ጥቅም ላይ ውሏል፣ {amountLeft} ይቀራል", "shrineTooltipRemoveItem": "ንጥል ያስወግዱ", "rallyAccountAmount": "{accountName} መለያ {accountNumber} በ {amount}።", "rallySeeAllBudgets": "ሁሉንም በጀቶች ይመልከቱ", "rallySeeAllBills": "ሁሉንም ክፍያ መጠየቂያዎች ይመልከቱ", "craneFormDate": "ቀን ይምረጡ", "craneFormOrigin": "ምንጭ ይምረጡ", "craneFly2": "ኩምቡ ሸለቆ፣ ኔፓል", "craneFly3": "ማቹ ፒቹ፣ ፔሩ", "craneFly4": "ማሌ፣ ማልዲቭስ", "craneFly5": "ቪትዝናው፣ ስዊዘርላንድ", "craneFly6": "ሜክሲኮ ሲቲ፣ ሜክሲኮ", "craneFly7": "ራሽሞር ተራራ፣ አሜሪካ", "settingsTextDirectionLocaleBased": "በአካባቢ ላይ በመመርኮዝ", "craneFly9": "ሃቫና፣ ኩባ", "craneFly10": "ካይሮ፣ ግብጽ", "craneFly11": "ሊዝበን፣ ፖርቱጋል", "craneFly12": "ናፓ፣ አሜሪካ", "craneFly13": "ባሊ፣ ኢንዶኔዥያ", "craneSleep0": "ማሌ፣ ማልዲቭስ", "craneSleep1": "አስፐን፣ አሜሪካ", "craneSleep2": "ማቹ ፒቹ፣ ፔሩ", "demoCupertinoSegmentedControlTitle": "የተከፋፈለ መቆጣጠሪያ", "craneSleep4": "ቪትዝናው፣ ስዊዘርላንድ", "craneSleep5": "ቢግ ሱር፣ አሜሪካ", "craneSleep6": "ናፓ፣ አሜሪካ", "craneSleep7": "ፖርቶ፣ ፖርቱጋል", "craneSleep8": "ቱሉም፣ ሜክሲኮ", "craneEat5": "ሲዮል፣ ደቡብ ኮሪያ", "demoChipTitle": "ቺፖች", "demoChipSubtitle": "አንድ ግቤት፣ ዓይነት ወይም እርምጃ የሚወክሉ እምቅ ክፍለ-አባላት", "demoActionChipTitle": "የእርምጃ ቺፕ", "demoActionChipDescription": "የእርምጃ ቺፖች ከዋና ይዘት ጋር በተገናኘት አንድ እርምጃን የሚቀሰቅሱ የአማራጮች ስብስብ ናቸው። የእርምጃ ቺፖች በአንድ ዩአይ ላይ በተለዋዋጭ እና አውዳዊ በሆነ መልኩ መታየት አለባቸው።", "demoChoiceChipTitle": "የምርጫ ቺፕ", "demoChoiceChipDescription": "የምርጫ ቺፖች ከአንድ ስብስብ ውስጥ አንድ ነጠላ ምርጫን ይወክላሉ። የምርጫ ቺፖች ገላጭ ጽሁፍ ወይም ምድቦችን ይይዛሉ።", "demoFilterChipTitle": "የማጣሪያ ቺፕ", "demoFilterChipDescription": "የማጣሪያ ቺፖች መለያዎችን ወይም ገላጭ ቃላት እንደ ይዘት የሚያጣሩበት መንገድ ይጠቀሙባቸዋል።", "demoInputChipTitle": "የግቤት ቺፕ", "demoInputChipDescription": "የግቤት ቺፖች እንደ ህጋዊ አካል (ሰው፣ ቦታ ወይም ነገር) ውስብስብ ወይም የውይይት ጽሁፍ ያለ በእምቅ መልኩ ያለ ውስብስብ የመረጃ ክፍልን ይወክላሉ።", "craneSleep9": "ሊዝበን፣ ፖርቱጋል", "craneEat10": "ሊዝበን፣ ፖርቱጋል", "demoCupertinoSegmentedControlDescription": "በአንድ ላይ በልዩ ሁኔታ ከሚታዩ አማራጮች ቁጥር መካከል ለመምረጥ ጥቅም ላይ ይውላል። በተከፋፈለው መቆጣጠሪያ ውስጥ አንድ አማራጭ ሲመረጥ፣ በተከፋፈለው መቆጣጠሪያ ውስጥ ያሉት ሌሎች አማራጮች መመረጥ ያቆማሉ።", "chipTurnOnLights": "መብራቶቹን አብራ", "chipSmall": "ትንሽ", "chipMedium": "መካከለኛ", "chipLarge": "ትልቅ", "chipElevator": "ሊፍት", "chipWasher": "ማጠቢያ ማሽን", "chipFireplace": "የእሳት ቦታ", "chipBiking": "ቢስክሌት መንዳት", "craneFormDiners": "መመገቢያዎች", "rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{የእርስዎን ሊቀነስ የሚችል ግብር ይጨምሩ! ወደ 1 ያልተመደበ ግብይት ምድቦችን ይመድቡ።}other{የእርስዎን ሊቀነስ የሚችል ግብር ይጨምሩ! ወደ {count} ያልተመደቡ ግብይቶች ምድቦችን ይመድቡ።}}", "craneFormTime": "ጊዜ ምረጥ", "craneFormLocation": "አካባቢ ምረጥ", "craneFormTravelers": "ተጓዦች", "craneEat8": "አትላንታ፣ አሜሪካ", "craneFormDestination": "መድረሻ ይምረጡ", "craneFormDates": "ቀኖችን ይምረጡ", "craneFly": "FLY", "craneSleep": "እንቅልፍ", "craneEat": "EAT", "craneFlySubhead": "በረራዎችን በመድረሻ ያስሱ", "craneSleepSubhead": "ንብረቶችን በመድረሻ ያስሱ", "craneEatSubhead": "ምግብ ቤቶችን በመድረሻ ያስሱ", "craneFlyStops": "{numberOfStops,plural,=0{ያለማቋረጥ}=1{1 ማቆሚያ}other{{numberOfStops} ማቆሚያዎች}}", "craneSleepProperties": "{totalProperties,plural,=0{ምንም የሚገኙ ንብረቶች የሉም}=1{1 የሚገኙ ንብረቶች}other{{totalProperties} የሚገኙ ንብረቶች}}", "craneEatRestaurants": "{totalRestaurants,plural,=0{ምግብ ቤቶች የሉም}=1{1 ምግብ ቤት}other{{totalRestaurants} ምግብ ቤቶች}}", "craneFly0": "አስፐን፣ አሜሪካ", "demoCupertinoSegmentedControlSubtitle": "በiOS-ቅጥ የተከፋፈለ መቆጣጠሪያ", "craneSleep10": "ካይሮ፣ ግብጽ", "craneEat9": "ማድሪድ፣ ስፔን", "craneFly1": "ቢግ ሱር፣ አሜሪካ", "craneEat7": "ናሽቪል፣ አሜሪካ", "craneEat6": "ሲያትል፣ አሜሪካ", "craneFly8": "ሲንጋፖር", "craneEat4": "ፓሪስ፣ ፈረንሳይ", "craneEat3": "ፖርትላንድ፣ አሜሪካ", "craneEat2": "ኮርዶባ፣ አርጀንቲና", "craneEat1": "ዳላስ፣ አሜሪካ", "craneEat0": "ኔፕልስ፣ ጣልያን", "craneSleep11": "ታይፔይ፣ ታይዋን", "craneSleep3": "ሃቫና፣ ኩባ", "shrineLogoutButtonCaption": "ዘግተህ ውጣ", "rallyTitleBills": "ሒሳብ መጠየቂያዎች", "rallyTitleAccounts": "መለያዎች", "shrineProductVagabondSack": "Vagabond ጆንያ", "rallyAccountDetailDataInterestYtd": "የወለድ ዓመት እስከ ቀን", "shrineProductWhitneyBelt": "Whitney ቀበቶ", "shrineProductGardenStrand": "Garden strand", "shrineProductStrutEarrings": "ደረቅ ጆሮ ጌጦች", "shrineProductVarsitySocks": "Varsity ካልሲዎች", "shrineProductWeaveKeyring": "የቁልፍ ቀለበትን ይሸምኑ", "shrineProductGatsbyHat": "Gatsby ኮፍያ", "shrineProductShrugBag": "ቦርሳዎች", "shrineProductGiltDeskTrio": "ባለሶስት ጠረጴዛ", "shrineProductCopperWireRack": "የመዳብ ገመድ መደርደሪያ", "shrineProductSootheCeramicSet": "Soothe ሴራሚክ ስብስብ", "shrineProductHurrahsTeaSet": "ሁራህ ሻይ ዕቃዎች", "shrineProductBlueStoneMug": "ሰማያዊ የድንጋይ ኩባያ", "shrineProductRainwaterTray": "የዝናብ ውሃ መያዣ", "shrineProductChambrayNapkins": "Chambray ሶፍት", "shrineProductSucculentPlanters": "ውሃማ ተካዮች", "shrineProductQuartetTable": "ባለአራት ጠረጴዛ", "shrineProductKitchenQuattro": "የወጥ ቤት ኳትሮ", "shrineProductClaySweater": "የሸክላ ሹራብ", "shrineProductSeaTunic": "የባህር ሸማ", "shrineProductPlasterTunic": "ፕላስተር ሸማ", "rallyBudgetCategoryRestaurants": "ምግብ ቤቶች", "shrineProductChambrayShirt": "Chambray ሸሚዝ", "shrineProductSeabreezeSweater": "Seabreeze ሹራብ", "shrineProductGentryJacket": "Gentry ጃኬት", "shrineProductNavyTrousers": "ኔቪ ሱሪ", "shrineProductWalterHenleyWhite": "Walter henley (ነጭ)", "shrineProductSurfAndPerfShirt": "Surf and perf ቲሸርት", "shrineProductGingerScarf": "Ginger ሻርብ", "shrineProductRamonaCrossover": "የራሞና ተሻጋሪ ስራ", "shrineProductClassicWhiteCollar": "የሚታወቅ ነጭ ኮሌታ", "shrineProductSunshirtDress": "የጸሐይ ሸሚዝ ቀሚስ", "rallyAccountDetailDataInterestRate": "የወለድ ተመን", "rallyAccountDetailDataAnnualPercentageYield": "ዓመታዊ የመቶኛ ትርፍ", "rallyAccountDataVacation": "ሽርሽር", "shrineProductFineLinesTee": "ፋይን ላይንስ ቲሸርት", "rallyAccountDataHomeSavings": "የቤት ቁጠባ", "rallyAccountDataChecking": "ተንቀሳቃሽ", "rallyAccountDetailDataInterestPaidLastYear": "ወለድ ባለፈው ዓመት ተከፍሎበታል", "rallyAccountDetailDataNextStatement": "ቀጣይ መግለጫ", "rallyAccountDetailDataAccountOwner": "የመለያ ባለቤት", "rallyBudgetCategoryCoffeeShops": "ቡና ቤቶች", "rallyBudgetCategoryGroceries": "ሸቀጣሸቀጦች", "shrineProductCeriseScallopTee": "Cerise ስካሎፕ ቲ", "rallyBudgetCategoryClothing": "አልባሳት", "rallySettingsManageAccounts": "መለያዎችን ያስተዳድሩ", "rallyAccountDataCarSavings": "የመኪና ቁጠባ", "rallySettingsTaxDocuments": "የግብር ሰነዶች", "rallySettingsPasscodeAndTouchId": "የይለፍ ኮድ እና የንክኪ መታወቂያ", "rallySettingsNotifications": "ማሳወቂያዎች", "rallySettingsPersonalInformation": "የግል ሁኔታ", "rallySettingsPaperlessSettings": "ወረቀት-አልባ ቅንብሮች", "rallySettingsFindAtms": "ኤቲኤሞችን አግኝ", "rallySettingsHelp": "እገዛ", "rallySettingsSignOut": "ዘግተህ ውጣ", "rallyAccountTotal": "ጠቅላላ", "rallyBillsDue": "የሚደርሰው", "rallyBudgetLeft": "ግራ", "rallyAccounts": "መለያዎች", "rallyBills": "ሒሳብ መጠየቂያዎች", "rallyBudgets": "ባጀቶች", "rallyAlerts": "ማንቂያዎች", "rallySeeAll": "ሁሉንም ይመልከቱ", "rallyFinanceLeft": "ግራ", "rallyTitleOverview": "አጠቃላይ ዕይታ", "shrineProductShoulderRollsTee": "ክፍት ትከሻ ቲሸርት", "shrineNextButtonCaption": "ቀጣይ", "rallyTitleBudgets": "ባጀቶች", "rallyTitleSettings": "ቅንብሮች", "rallyLoginLoginToRally": "ወደ Rally ይግቡ", "rallyLoginNoAccount": "መለያ የለዎትም?", "rallyLoginSignUp": "ተመዝገብ", "rallyLoginUsername": "የተጠቃሚ ስም", "rallyLoginPassword": "የይለፍ ቃል", "rallyLoginLabelLogin": "ግባ", "rallyLoginRememberMe": "አስታውሰኝ", "rallyLoginButtonLogin": "ግባ", "rallyAlertsMessageHeadsUpShopping": "ማሳሰቢያ፣ ለዚህ ወር ከታሰበው የእርስዎ የግዢ በጀት {percent} ያህል ተጠቅመዋል።", "rallyAlertsMessageSpentOnRestaurants": "በዚህ ሳምንት ምግብ ቤቶች ሂደው {amount} አውጥተዋል።", "rallyAlertsMessageATMFees": "በዚህ ወር ለኤቲኤም ክፍያዎች {amount} አውጥተዋል", "rallyAlertsMessageCheckingAccount": "ጥሩ ስራ! የእርስዎ ተንቀሳቃሽ ሒሳብ ከባለፈው ወር በ{percent} ጨምሯል።", "shrineMenuCaption": "ምናሌ", "shrineCategoryNameAll": "ሁሉም", "shrineCategoryNameAccessories": "ተቀጥላዎች", "shrineCategoryNameClothing": "አልባሳት", "shrineCategoryNameHome": "መነሻ", "shrineLoginUsernameLabel": "የተጠቃሚ ስም", "shrineLoginPasswordLabel": "የይለፍ ቃል", "shrineCancelButtonCaption": "ይቅር", "shrineCartTaxCaption": "ግብር፦", "shrineCartPageCaption": "ጋሪ", "shrineProductQuantity": "መጠን፦ {quantity}", "shrineProductPrice": "x {price}", "shrineCartItemCount": "{quantity,plural,=0{ምንም ንጥሎች የሉም}=1{1 ንጥል}other{{quantity} ንጥሎች}}", "shrineCartClearButtonCaption": "ጋሪን አጽዳ", "shrineCartTotalCaption": "ጠቅላላ", "shrineCartSubtotalCaption": "ንዑስ ድምር፦", "shrineCartShippingCaption": "መላኪያ፦", "shrineProductGreySlouchTank": "ግራጫ የወረደ ጉርድ ቲሸርት", "shrineProductStellaSunglasses": "ስቴላ የጸሐይ መነጽሮች", "shrineProductWhitePinstripeShirt": "ነጭ ባለቀጭን መስመር ሸሚዝ", "demoTextFieldWhereCanWeReachYou": "የት ልናገኝዎ እንችላለን?", "settingsTextDirectionLTR": "ግራ-ወደ-ቀኝ", "settingsTextScalingLarge": "ትልቅ", "demoBottomSheetHeader": "ራስጌ", "demoBottomSheetItem": "ንጥል {value}", "demoBottomTextFieldsTitle": "የጽሑፍ መስኮች", "demoTextFieldTitle": "የጽሑፍ መስኮች", "demoTextFieldSubtitle": "አርትዖት ሊደረግባቸው የሚችሉ የጽሑፍ እና ቁጥሮች ነጠላ መስመር", "demoTextFieldDescription": "የጽሑፍ መስኮች ተጠቃሚዎች ቃላትን ወደ ዩአይ እንዲያስገቡ ያስችላቸዋል። በተለምዶ በቅጾች እና በመገናኛዎች ውስጥ ይታያሉ።", "demoTextFieldShowPasswordLabel": "የይለፍ ቃል አሳይ", "demoTextFieldHidePasswordLabel": "የይለፍ ቃል ደብቅ", "demoTextFieldFormErrors": "ከማስገባትዎ በፊት እባክዎ በቀይ ያሉትን ስህተቶች ያስተካክሉ።", "demoTextFieldNameRequired": "ስም ያስፈልጋል።", "demoTextFieldOnlyAlphabeticalChars": "እባክዎ ፊደል-ቁጥራዊ ቁምፊዎችን ብቻ ያስገቡ።", "demoTextFieldEnterUSPhoneNumber": "(###) ###-#### - የአሜሪካ ስልክ ቁጥር ያስገቡ።", "demoTextFieldEnterPassword": "እባክዎ የይለፍ ቃል ያስገቡ።", "demoTextFieldPasswordsDoNotMatch": "የይለፍ ቃላቱ አይዛመዱም", "demoTextFieldWhatDoPeopleCallYou": "ሰዎች እርስዎን ምን ብለው ነው የሚጠሩዎት?", "demoTextFieldNameField": "ስም*", "demoBottomSheetButtonText": "የግርጌ ሉህን አሳይ", "demoTextFieldPhoneNumber": "ስልክ ቁጥር*", "demoBottomSheetTitle": "የግርጌ ሉህ", "demoTextFieldEmail": "ኢሜይል", "demoTextFieldTellUsAboutYourself": "ስለራስዎ ይንገሩን (ለምሳሌ፡0 ምን እንደሚያደርጉ ወይም ምን ዝንባሌዎች እንዳለዎት)", "demoTextFieldKeepItShort": "ያሳጥሩት፣ ይህ ማሳያ ብቻ ነው።", "starterAppGenericButton": "አዝራር", "demoTextFieldLifeStory": "የህይወት ታሪክ", "demoTextFieldSalary": "ደመወዝ", "demoTextFieldUSD": "የአሜሪካ ዶላር", "demoTextFieldNoMoreThan": "ከ8 ቁምፊዎች ያልበለጠ።", "demoTextFieldPassword": "የይለፍ ቃል*", "demoTextFieldRetypePassword": "የይለፍ ቃል እንደገና ይተይቡ*", "demoTextFieldSubmit": "አስገባ", "demoBottomNavigationSubtitle": "የግርጌ ዳሰሳ ከተሻጋሪ የሚደበዝዙ እይታዎች ጋር", "demoBottomSheetAddLabel": "አክል", "demoBottomSheetModalDescription": "የሞዳል ግርጌ ሉህ ለአንድ ምናሌ ወይም መገናኛ ተለዋጭ ሲሆን ተጠቃሚው ከተቀረው መተግበሪያ ጋር መስተጋብር እንዳይፈጥር ይከለክላል።", "demoBottomSheetModalTitle": "የሞዳል አዝራር ሉህ", "demoBottomSheetPersistentDescription": "ጽኑ የሆነ የግርጌ ሉህ የመተግበሪያውን ዋና ይዘት የሚያሟላ መረጃ ያሳያል። ጽኑ የግርጌ ሉህ ተጠቃሚው የመተግበሪያው ሌሎች ክፍሎች ጋር መስተጋብር ቢፈጥርም እንኳ የሚታይ እንደሆነ ይቆያል።", "demoBottomSheetPersistentTitle": "ጽኑ የግርጌ ሉህ", "demoBottomSheetSubtitle": "ጽኑ እና ሞዳል የግርጌ ሉሆች", "demoTextFieldNameHasPhoneNumber": "የ{name} ስልክ ቁጥር {phoneNumber} ነው", "buttonText": "አዝራር", "demoTypographyDescription": "በቁሳዊ ንድፍ ላይ የሚገኙ የተለያዩ ታይፖግራፊያዊ ቅጦች ፍቺዎች።", "demoTypographySubtitle": "ሁሉም ቅድሚያ የተገለጹ የጽሑፍ ቅጦች", "demoTypographyTitle": "ታይፖግራፊ", "demoFullscreenDialogDescription": "የ fullscreenDialog ባህሪ መጪው ገፅ ባለ ሙሉ ማያ ገፅ ሞዳል ንግግር መሆን አለመሆኑን ይጠቅሳል", "demoFlatButtonDescription": "ዝርግ አዝራር የቀለም መርጫ በመጫን ወቅት ያሳያል ሆኖም ግን አያነሳም። ከመደገፍ ጋር በንግግሮች እና በውስጠ መስመር ውስጥ በመሣሪያ አሞሌዎች ላይ ዝርግ አዝራሮችን ይጠቀሙ", "demoBottomNavigationDescription": "የግርጌ ዳሰሳ አሞሌዎች በአንድ ማያ ግርጌ ላይ ከሶስት እስከ አምስት መድረሻዎች ድረስ ያሳያሉ። እያንዳንዱ መድረሻ በአዶ እና በአማራጭ የጽሑፍ መሰየሚያ ይወከላል። የግርጌ ዳሰሳ አዶ መታ ሲደረግ ተጠቃሚው ከዚያ አዶ ጋር የተጎዳኘ የከፍተኛ ደረጃ የዳሰሳ መድረሻ ይወሰዳል።", "demoBottomNavigationSelectedLabel": "መሰየሚያ ተመርጧል", "demoBottomNavigationPersistentLabels": "ጽኑ መሰየሚያዎች", "starterAppDrawerItem": "ንጥል {value}", "demoTextFieldRequiredField": "* የሚያስፈልግ መስክ መሆኑን ያመለክታል", "demoBottomNavigationTitle": "የታች ዳሰሳ", "settingsLightTheme": "ብርሃን", "settingsTheme": "ገጽታ", "settingsPlatformIOS": "iOS", "settingsPlatformAndroid": "Android", "settingsTextDirectionRTL": "ቀኝ-ወደ-ግራ", "settingsTextScalingHuge": "ግዙፍ", "cupertinoButton": "አዝራር", "settingsTextScalingNormal": "መደበኛ", "settingsTextScalingSmall": "ትንሽ", "settingsSystemDefault": "ሥርዓት", "settingsTitle": "ቅንብሮች", "rallyDescription": "የግል የፋይናንስ መተግበሪያ", "aboutDialogDescription": "የዚህ መተግበሪያ ኮድ ምንጭ ኮድን ለማየት እባክዎ {repoLink}ን ይጎብኙ።", "bottomNavigationCommentsTab": "አስተያየቶች", "starterAppGenericBody": "አካል", "starterAppGenericHeadline": "አርዕስተ ዜና", "starterAppGenericSubtitle": "የግርጌ ጽሁፍ", "starterAppGenericTitle": "ርዕስ", "starterAppTooltipSearch": "ፍለጋ", "starterAppTooltipShare": "አጋራ", "starterAppTooltipFavorite": "ተወዳጅ", "starterAppTooltipAdd": "አክል", "bottomNavigationCalendarTab": "የቀን መቁጠሪያ", "starterAppDescription": "ምላሽ የሚሰጥ የጀማር አቀማመጥ", "starterAppTitle": "አስጀማሪ መተግበሪያ", "aboutFlutterSamplesRepo": "የFlutter ናሙናዎች የGitHub ማከማቻ", "bottomNavigationContentPlaceholder": "የ{title} ትር ቦታ ያዥ", "bottomNavigationCameraTab": "ካሜራ", "bottomNavigationAlarmTab": "ማንቂያ", "bottomNavigationAccountTab": "መለያ", "demoTextFieldYourEmailAddress": "የእርስዎ ኢሜል አድራሻ", "demoToggleButtonDescription": "ተዛማጅ አማራጮችን ለመቦደን የቀያይር አዝራሮች ጥቅም ላይ ሊውሉ ይችላሉ። ተዛማጅነት ያላቸው መቀያየሪያ አዝራሮችን ቡድኖች አጽዕኖት ለመስጠት፣ ቡድን የጋራ መያዣን ማጋራት አለበት።", "colorsGrey": "ግራጫ", "colorsBrown": "ቡናማ", "colorsDeepOrange": "ደማቅ ብርቱካናማ", "colorsOrange": "ብርቱካናማ", "colorsAmber": "አምበር", "colorsYellow": "ቢጫ", "colorsLime": "ሎሚ ቀለም", "colorsLightGreen": "ፈካ ያለ አረንጓዴ", "colorsGreen": "አረንጓዴ", "homeHeaderGallery": "የሥነ ጥበብ ማዕከል", "homeHeaderCategories": "ምድቦች", "shrineDescription": "የዘነጠ የችርቻሮ መተግበሪያ", "craneDescription": "ግላዊነት የተላበሰ የጉዞ መተግበሪያ", "homeCategoryReference": "ቅጦች እና ሌላ", "demoInvalidURL": "ዩአርኤልን ማሳየት አልተቻለም፦", "demoOptionsTooltip": "አማራጮች", "demoInfoTooltip": "መረጃ", "demoCodeTooltip": "የማሳያ ኮድ", "demoDocumentationTooltip": "የኤፒአይ ስነዳ", "demoFullscreenTooltip": "የሙሉ ገፅ ዕይታ", "settingsTextScaling": "ጽሑፍን ማመጣጠን", "settingsTextDirection": "የጽሑፍ አቅጣጫ", "settingsLocale": "የአካባቢ", "settingsPlatformMechanics": "የመሣሪያ ስርዓት ሜካኒክ አሰራር", "settingsDarkTheme": "ጨለማ", "settingsSlowMotion": "የዝግታ እንቅስቃሴ", "settingsAbout": "ስለ ፍላተር ማዕከለ ስዕላት", "settingsFeedback": "ግብረመልስ ላክ", "settingsAttribution": "ለንደን ውስጥ በTOASTER የተነደፈ", "demoButtonTitle": "አዝራሮች", "demoButtonSubtitle": "ጽሁፍ፣ ከፍ ያለ፣ ባለቢጋር፣ እና ተጨማሪ", "demoFlatButtonTitle": "ዝርግ አዝራር", "demoRaisedButtonDescription": "ከፍ ያሉ አዝራሮች ብዙውን ጊዜ ለዝርግ አቀማመጦች ስፋት ያክላሉ። በባተሌ ወይም ሰፊ ቦታዎች ላይ ተግባራት ላይ አጽዕኖት ይሰጣሉ።", "demoRaisedButtonTitle": "ከፍ ያለ አዝራር", "demoOutlineButtonTitle": "የቢጋር አዝራር", "demoOutlineButtonDescription": "የቢጋር አዝራሮች የማይታዩ ይሆኑና በሚጫኑበት ጊዜ ከፍ ይላሉ። አማራጭን፣ ሁለተኛ እርምጃን ለመጠቆም ብዙውን ጊዜ ከፍ ካሉ አዝራሮች ጋር ይጣመራሉ።", "demoToggleButtonTitle": "መቀያየሪያ አዝራሮች", "colorsTeal": "ደማቅ አረንጓዴ-ሰማያዊ", "demoFloatingButtonTitle": "የተንሳፋፊ እርምጃ አዝራር", "demoFloatingButtonDescription": "ተንሳፋፊ የድርጊት አዝራር በመተግበሪያው ላይ ተቀዳሚ ድርጊትን ለማበረታታት በይዘት ላይ የሚያንዣብብ ክብ አዶ አዝራር ነው።", "demoDialogTitle": "ንግግሮች", "demoDialogSubtitle": "ቀላል፣ ማንቂያ እና ሙሉ ማያ ገፅ", "demoAlertDialogTitle": "ማንቂያ", "demoAlertDialogDescription": "የማንቂያ ንግግር ተጠቃሚውን ስለ ዕውቅና መስጠት የሚያስፈልጋቸው ሁኔታዎች በተመለከተ መረጃ ይሰጣል። የማንቂያ ንግግር አማራጭ አርዕስት እና የድርጊቶች አማራጭ ዝርዝር አለው።", "demoAlertTitleDialogTitle": "ከአርእስት ጋር ማስጠንቀቂያ ስጥ", "demoSimpleDialogTitle": "ቀላል", "demoSimpleDialogDescription": "ቀላል ንግግር ለተጠቃሚው በበርካታ አማራጮች መካከል ምርጫን ያቀርባል። ቀላል ንግግር ከምርጫዎ በላይ የሚታይ አማራጭ አርዕስት አለው።", "demoFullscreenDialogTitle": "ሙሉ ማያ ገፅ", "demoCupertinoButtonsTitle": "አዝራሮች", "demoCupertinoButtonsSubtitle": "iOS-ቅጥ አዝራሮች", "demoCupertinoButtonsDescription": "የ iOS-ቅጥ አዝራር። ሲነካ የሚደበዝዝ እና የሚደምቅ የጽሑፍ ውስጥ እና/ወይም አዶ ይወስዳል። በአማራጭነት በስተጀርባ ሊኖረው ይችል ይሆናል።", "demoCupertinoAlertsTitle": "ማንቂያዎች", "demoCupertinoAlertsSubtitle": "iOS-ቅጥ ማንቂያ ንግግሮች", "demoCupertinoAlertTitle": "ማንቂያ", "demoCupertinoAlertDescription": "የማንቂያ ንግግር ተጠቃሚውን ስለ ዕውቅና መስጠት የሚያስፈልጋቸው ሁኔታዎች በተመለከተ መረጃ ይሰጣል። የማንቂያ ንግግር አማራጭ አርዕስት፣ አማራጭ ይዘት እና የድርጊቶች አማራጭ ዝርዝር አለው። አርእስቱ ከይዘቱ በላይ ይታያል እና እርምጃዎቹ ከይዘቱ ሥር ይታያሉ።", "demoCupertinoAlertWithTitleTitle": "ከርዕስ ጋር ማንቂያ", "demoCupertinoAlertButtonsTitle": "ከአዝራሮች ጋር ማንቂያዎች", "demoCupertinoAlertButtonsOnlyTitle": "የማንቂያ አዝራሮች ብቻ", "demoCupertinoActionSheetTitle": "የእርምጃ ሉህ", "demoCupertinoActionSheetDescription": "የእርምጃ ሉህ ከሁለት ወይም ከዚያ በላይ አሁን ካለው ዓውድ ጋር ግንኙነት ያላቸው ምርጫዎች ጋር የምርጫ ስብስብ ለተጠቃሚው የሚያቀርብ የተወሰነ የማንቂያ ቅጥ ነው። የእርምጃ ሉህ አርዕስት፣ ተጨማሪ መልዕክት፣ እና የእርምጃዎች ዝርዝር ሊኖረው ይችላል።", "demoColorsTitle": "ቀለማት", "demoColorsSubtitle": "ሁሉም አስቀድመው የተገለጹ ቀለማት", "demoColorsDescription": "የቁስ ንድፍ ቀለም ቤተ ሥዕልን የሚወክሉ የቀለም እና የቀለም መደብ ቋሚዎች።", "buttonTextEnabled": "ENABLED", "buttonTextDisabled": "DISABLED", "buttonTextCreate": "ይፍጠሩ", "dialogSelectedOption": "እርስዎ ይህን መርጠዋል፦ «{value}»", "dialogDiscardTitle": "ረቂቅ ይጣል?", "dialogLocationTitle": "የGoogle አካባቢ አገልግሎትን ይጠቀም?", "dialogLocationDescription": "መተግበሪያዎች አካባቢ እንዲያውቁ Google ያግዛቸው። ይሄ ማለት ስም-አልባ የአካባቢ ውሂብ ለGoogle መላክ ማለት ነው፣ ምንም እያሄዱ ያሉ መተግበሪያዎች ባይኖሩም እንኳ።", "dialogCancel": "ተወው", "dialogDiscard": "አስወግድ", "dialogDisagree": "አትስማማ", "dialogAgree": "እስማማለሁ", "dialogSetBackup": "የምትኬ መለያ አቀናብር", "colorsBlueGrey": "ሰማያዊ ግራጫ", "dialogShow": "ንግግርን አሳይ", "dialogFullscreenTitle": "የሙሉ ማያ ገፅ ንግግር", "dialogFullscreenSave": "አስቀምጥ", "dialogFullscreenDescription": "የሙሉ ማያ ገፅ ንግግር ተግባራዊ ማሳያ", "cupertinoButtonEnabled": "Enabled", "cupertinoButtonDisabled": "Disabled", "cupertinoButtonWithBackground": "ከበስተጀርባ ጋር", "cupertinoAlertCancel": "ተወው", "cupertinoAlertDiscard": "አስወግድ", "cupertinoAlertLocationTitle": "የእርስዎ መገኛ አካባቢ እርስዎ መተግበሪያውን እየተጠቀሙ እንዳሉ እንዲደርስበት ለ \"ካርታዎች\" ይፈቀድ?", "cupertinoAlertLocationDescription": "የእርስዎ አሁን ያሉበት መገኛ አካባቢ በካርታው ላይ ይታያል እንዲሁም ለአቅጣጫዎች፣ በአቅራቢያ ያሉ ፍለጋ ውጤቶች እና የሚገመቱ የጉዞ ጊዜያት ጥቅም ላይ ይውላል።", "cupertinoAlertAllow": "ፍቀድ", "cupertinoAlertDontAllow": "አትፍቀድ", "cupertinoAlertFavoriteDessert": "ተወዳጅ ጣፋጭ ምግብን ይምረጡ", "cupertinoAlertDessertDescription": "ከዚህ በታች ካለው ዝርዝር እባክዎ የእርስዎን ተወዳጅ ጣፋጭ ምግብ ዓይነት ይምረጡ። የእርስዎ ምርጫ በእርስዎ አካባቢ ያሉትን የሚጠቆሙ መመገቢያ ቦታዎችን ዝርዝር ብጁ ለማድረግ ጥቅም ላይ ሊውል ይችላል።", "cupertinoAlertCheesecake": "ቺዝ ኬክ", "cupertinoAlertTiramisu": "ቴራሚሶ", "cupertinoAlertApplePie": "የፖም ፓይ", "cupertinoAlertChocolateBrownie": "ቸኮሌት ብራውኒ", "cupertinoShowAlert": "ማንቂያን አሳይ", "colorsRed": "ቀይ", "colorsPink": "ሮዝ", "colorsPurple": "ሐምራዊ", "colorsDeepPurple": "ደማቅ ሐምራዊ", "colorsIndigo": "ወይን ጠጅ", "colorsBlue": "ሰማያዊ", "colorsLightBlue": "ፈካ ያለ ሰማያዊ", "colorsCyan": "አረንጓዴ-ሰማያዊ", "dialogAddAccount": "መለያ አክል", "Gallery": "የሥነ ጥበብ ማዕከል", "Categories": "ምድቦች", "SHRINE": "ቅዱስ ቦታ", "Basic shopping app": "መሠረታዊ የግዢ መተግበሪያ", "RALLY": "ውድድር", "CRANE": "ክሬን", "Travel app": "የጉዞ መተግበሪያ", "MATERIAL": "ቁስ", "CUPERTINO": "CUPERTINO", "REFERENCE STYLES & MEDIA": "የማጣቀሻ ቅጦች እና መገናኛ ብዙኃን" }
gallery/lib/l10n/intl_am.arb/0
{ "file_path": "gallery/lib/l10n/intl_am.arb", "repo_id": "gallery", "token_count": 48029 }
812
{ "loading": "Učitavanje", "deselect": "Poništi odabir", "select": "Odaberi", "selectable": "Može se odabrati (dugi pritisak)", "selected": "Odabrano", "demo": "Demo", "bottomAppBar": "Donja traka aplikacije", "notSelected": "Nije odabrano", "demoCupertinoSearchTextFieldTitle": "Pretraži tekstno polje", "demoCupertinoPicker": "Alat za odabir", "demoCupertinoSearchTextFieldSubtitle": "Tekstno polje za pretraživanje u iOS-ovom stilu", "demoCupertinoSearchTextFieldDescription": "Tekstno polje pretraživanja koje korisniku omogućuje pretraživanje unosom teksta i koje može nuditi i filtrirati prijedloge.", "demoCupertinoSearchTextFieldPlaceholder": "Unesite tekst", "demoCupertinoScrollbarTitle": "Klizač", "demoCupertinoScrollbarSubtitle": "Klizač u iOS-ovom stilu", "demoCupertinoScrollbarDescription": "Klizač koji obuhvaća podređeno", "demoTwoPaneItem": "Stavka {value}", "demoTwoPaneList": "Popis", "demoTwoPaneFoldableLabel": "Sklopiv", "demoTwoPaneSmallScreenLabel": "Mali zaslon", "demoTwoPaneSmallScreenDescription": "Tako se TwoPane ponaša na uređaju s malim zaslonom.", "demoTwoPaneTabletLabel": "Tablet/računalo", "demoTwoPaneTabletDescription": "Tako se TwoPane ponaša na većem zaslonu kao što je tablet ili računalo.", "demoTwoPaneTitle": "TwoPane", "demoTwoPaneSubtitle": "Responzivna oblikovanja na sklopivim, velikim i malim zaslonima", "splashSelectDemo": "Odaberite pokaznu verziju", "demoTwoPaneFoldableDescription": "Tako se TwoPane ponaša na sklopivom uređaju.", "demoTwoPaneDetails": "Pojedinosti", "demoTwoPaneSelectItem": "Odaberite stavku", "demoTwoPaneItemDetails": "Pojedinosti o stavci {value}", "demoCupertinoContextMenuActionText": "Dodirnite i zadržite logotip Fluttera da biste vidjeli kontekstni izbornik.", "demoCupertinoContextMenuDescription": "Kontekstni izbornik u iOS-ovom stilu na cijelom zaslonu koji se prikazuje kad se neki element dugo pritisne.", "demoAppBarTitle": "Traka aplikacije", "demoAppBarDescription": "Na traci aplikacije navodi se sadržaj i radnje povezane s trenutačnim zaslonom. Koristi se za robnu marku, naslove zaslona, navigaciju i radnje.", "demoDividerTitle": "Razdjelnik", "demoDividerSubtitle": "Razdjelnik je tanka crta koja grupira sadržaj na popisima i prijelomima.", "demoDividerDescription": "Razdjelnici se mogu koristiti na popisima, u ladicama i drugdje za razdvajanje sadržaja.", "demoVerticalDividerTitle": "Okomiti razdjelnik", "demoCupertinoContextMenuTitle": "Kontekstni izbornik", "demoCupertinoContextMenuSubtitle": "Kontekstni izbornik u iOS-ovom stilu", "demoAppBarSubtitle": "Prikazuje informacije i radnje povezane s trenutačnim zaslonom", "demoCupertinoContextMenuActionOne": "Prva radnja", "demoCupertinoContextMenuActionTwo": "Druga radnja", "demoDateRangePickerDescription": "Prikazuje dijalog koji sadrži alat za odabir datumskog raspona u materijalnom dizajnu.", "demoDateRangePickerTitle": "Alat za odabir datumskog raspona", "demoNavigationDrawerUserName": "Korisničko ime", "demoNavigationDrawerUserEmail": "[email protected]", "demoNavigationDrawerText": "Prijeđite prstom od ruba ili dodirnite ikonu u gornjem lijevom kutu da bi se prikazala ladica", "demoNavigationRailTitle": "Pruga za navigaciju", "demoNavigationRailSubtitle": "Prikaz pruge za navigaciju u aplikaciji", "demoNavigationRailDescription": "Widget materijalnog dizajna koji bi se trebao prikazivati lijevo ili desno u aplikaciji radi navigacije između malog broja prikaza, obično od tri do pet.", "demoNavigationRailFirst": "Prvo", "demoNavigationDrawerTitle": "Ladica za navigaciju", "demoNavigationRailThird": "Treće", "replyStarredLabel": "Sa zvjezdicom", "demoTextButtonDescription": "Tekstni gumb prikazuje mrlju boje prilikom pritiska, ali se ne podiže. Tekstne gumbe koristite na alatnim trakama, u dijalozima i ugrađene u ispunu", "demoElevatedButtonTitle": "Izdignuti gumb", "demoElevatedButtonDescription": "Izdignuti gumbi dodaju dimenziju uglavnom ravnim rasporedima. Naglašavaju funkcije na prostorima koji su prostrani ili imaju mnogo sadržaja.", "demoOutlinedButtonTitle": "Ocrtani gumb", "demoOutlinedButtonDescription": "Ocrtani gumbi postaju neprozirni i izdižu se kad se pritisnu. Obično se uparuju s izdignutim gumbima da bi naznačili alternativnu, sekundarnu radnju.", "demoContainerTransformDemoInstructions": "Kartice, popisi i FAB", "demoNavigationDrawerSubtitle": "Prikaz ladice u traci aplikacije", "replyDescription": "Učinkovita i fokusirana aplikacija za e-poštu", "demoNavigationDrawerDescription": "Ploča materijalnog dizajna koja na zaslon klizne vodoravno od ruba kako bi se prikazale veze za navigaciju u aplikaciji.", "replyDraftsLabel": "Skice", "demoNavigationDrawerToPageOne": "Prva stavka", "replyInboxLabel": "Pristigla pošta", "demoSharedXAxisDemoInstructions": "Gumbi za dalje i natrag", "replySpamLabel": "Neželjena pošta", "replyTrashLabel": "Otpad", "replySentLabel": "Poslano", "demoNavigationRailSecond": "Drugo", "demoNavigationDrawerToPageTwo": "Druga stavka", "demoFadeScaleDemoInstructions": "Modalni i FAB", "demoFadeThroughDemoInstructions": "Donja navigacija", "demoSharedZAxisDemoInstructions": "Gumb s ikonom postavki", "demoSharedYAxisDemoInstructions": "Razvrstaj po kriteriju \"Nedavno slušano\"", "demoTextButtonTitle": "Tekstni gumb", "demoSharedZAxisBeefSandwichRecipeTitle": "Sendvič s govedinom", "demoSharedZAxisDessertRecipeDescription": "Recept za desert", "demoSharedYAxisAlbumTileSubtitle": "Izvođač", "demoSharedYAxisAlbumTileTitle": "Album", "demoSharedYAxisRecentSortTitle": "Nedavno slušano", "demoSharedYAxisAlphabeticalSortTitle": "A – Ž", "demoSharedYAxisAlbumCount": "268 albuma", "demoSharedYAxisTitle": "Dijeljena os y", "demoSharedXAxisCreateAccountButtonText": "IZRADA RAČUNA", "demoFadeScaleAlertDialogDiscardButton": "ODBACI", "demoSharedXAxisSignInTextFieldLabel": "E-adresa ili telefonski broj", "demoSharedXAxisSignInSubtitleText": "Prijavite se pomoću računa", "demoSharedXAxisSignInWelcomeText": "Pozdrav, David Park", "demoSharedXAxisIndividualCourseSubtitle": "Prikazuje se pojedinačno", "demoSharedXAxisBundledCourseSubtitle": "U paketu", "demoFadeThroughAlbumsDestination": "Albumi", "demoSharedXAxisDesignCourseTitle": "Dizajn", "demoSharedXAxisIllustrationCourseTitle": "Ilustracija", "demoSharedXAxisBusinessCourseTitle": "Posao", "demoSharedXAxisArtsAndCraftsCourseTitle": "Rukotvorine", "demoMotionPlaceholderSubtitle": "Sekundarni tekst", "demoFadeScaleAlertDialogCancelButton": "ODUSTANI", "demoFadeScaleAlertDialogHeader": "Dijaloški okvir upozorenja", "demoFadeScaleHideFabButton": "FAB ZA SAKRIVANJE", "demoFadeScaleShowFabButton": "FAB ZA PRIKAZIVANJE", "demoFadeScaleShowAlertDialogButton": "MODAL ZA PRIKAZIVANJE", "demoFadeScaleDescription": "Uzorak postupnog pojavljivanja i nestajanja koristi se za elemente korisničkog sučelja koji se pojavljuju ili nestaju u okvirima zaslona, na primjer dijaloški okvir koji se pojavljuje i nestaje na sredini zaslona.", "demoFadeScaleTitle": "Postupno pojavljivanje i nestajanje", "demoFadeThroughTextPlaceholder": "123 fotografije", "demoFadeThroughSearchDestination": "Pretraži", "demoFadeThroughPhotosDestination": "Fotografije", "demoSharedXAxisCoursePageSubtitle": "Kategorije u paketu prikazuju se kao skupine u vašem feedu. Kasnije se možete predomisliti.", "demoFadeThroughDescription": "Uzorak postupnog prijelaza koristi se za prijelaze između elemenata korisničkog sučelja koji nemaju snažnu međusobnu vezu.", "demoFadeThroughTitle": "Postupni prijelaz", "demoSharedZAxisHelpSettingLabel": "Pomoć", "demoMotionSubtitle": "Svi unaprijed definirani uzorci prijelaza", "demoSharedZAxisNotificationSettingLabel": "Obavijesti", "demoSharedZAxisProfileSettingLabel": "Profil", "demoSharedZAxisSavedRecipesListTitle": "Spremljeni recepti", "demoSharedZAxisBeefSandwichRecipeDescription": "Recept za sendvič s govedinom", "demoSharedZAxisCrabPlateRecipeDescription": "Recept za jelo od raka", "demoSharedXAxisCoursePageTitle": "Poboljšajte organizaciju tečajeva", "demoSharedZAxisCrabPlateRecipeTitle": "Rak", "demoSharedZAxisShrimpPlateRecipeDescription": "Recept za jelo od škampa", "demoSharedZAxisShrimpPlateRecipeTitle": "Škamp", "demoContainerTransformTypeFadeThrough": "POSTUPNI PRIJELAZ", "demoSharedZAxisDessertRecipeTitle": "Desert", "demoSharedZAxisSandwichRecipeDescription": "Recept za sendvič", "demoSharedZAxisSandwichRecipeTitle": "Sendvič", "demoSharedZAxisBurgerRecipeDescription": "Recept za hamburger", "demoSharedZAxisBurgerRecipeTitle": "Hamburger", "demoSharedZAxisSettingsPageTitle": "Postavke", "demoSharedZAxisTitle": "Dijeljena os z", "demoSharedZAxisPrivacySettingLabel": "Privatnost", "demoMotionTitle": "Animacija", "demoContainerTransformTitle": "Preobrazba spremnika", "demoContainerTransformDescription": "Uzorak za preobrazbu spremnika dizajnira se za prijelaze između elemenata korisničkog sučelja koji sadrže spremnik Uzorak stvara vidljivu vezu između dvaju elemenata korisničkog sučelja", "demoContainerTransformModalBottomSheetTitle": "Način postupnog pojavljivanja i nestajanja", "demoContainerTransformTypeFade": "POSTUPNO POJAVLJIVANJE I NESTAJANJE", "demoSharedYAxisAlbumTileDurationUnit": "min", "demoMotionPlaceholderTitle": "Naslov", "demoSharedXAxisForgotEmailButtonText": "ZABORAVILI STE E-ADRESU?", "demoMotionSmallPlaceholderSubtitle": "Sekundarno", "demoMotionDetailsPageTitle": "Stranica s pojedinostima", "demoMotionListTileTitle": "Stavka popisa", "demoSharedAxisDescription": "Uzorak dijeljene osi koristi se za prijelaze između elemenata korisničkog sučelja koji su u međusobnom prostornom ili navigacijskom odnosu. Taj uzorak koristi dijeljenu preobrazbu na osima x, y ili z kako bi se naglasio odnos među elementima.", "demoSharedXAxisTitle": "Dijeljena os x", "demoSharedXAxisBackButtonText": "NATRAG", "demoSharedXAxisNextButtonText": "DALJE", "demoSharedXAxisCulinaryCourseTitle": "Kulinarski", "githubRepo": "GitHub spremište {repoName}", "fortnightlyMenuUS": "SAD", "fortnightlyMenuBusiness": "Biznis", "fortnightlyMenuScience": "Znanost", "fortnightlyMenuSports": "Sport", "fortnightlyMenuTravel": "Putovanja", "fortnightlyMenuCulture": "Kultura", "fortnightlyTrendingTechDesign": "TechDesign", "rallyBudgetDetailAmountLeft": "Preostali iznos", "fortnightlyHeadlineArmy": "Reforma programa The Green Army iznutra", "fortnightlyDescription": "Aplikacija vijesti sa sadržajem", "rallyBillDetailAmountDue": "Iznos duga", "rallyBudgetDetailTotalCap": "Ukupna kapitalizacija", "rallyBudgetDetailAmountUsed": "Iskorišteni iznos", "fortnightlyTrendingHealthcareRevolution": "HealthcareRevolution", "fortnightlyMenuFrontPage": "Naslovnica", "fortnightlyMenuWorld": "Svijet", "rallyBillDetailAmountPaid": "Plaćeni iznos", "fortnightlyMenuPolitics": "Politika", "fortnightlyHeadlineBees": "Domaćim pčelama nedostaje izvora", "fortnightlyHeadlineGasoline": "Budućnost goriva", "fortnightlyTrendingGreenArmy": "GreenArmy", "fortnightlyHeadlineFeminists": "Feministički pogled na stranačje", "fortnightlyHeadlineFabrics": "Dizajneri koriste tehnologiju za izradu futurističkih materijala", "fortnightlyHeadlineStocks": "Dok dionice stagniraju, mnogi se okreću valutama", "fortnightlyTrendingReform": "Reform", "fortnightlyMenuTech": "Tehnologija", "fortnightlyHeadlineWar": "Podijeljeni američki životi tijekom rata", "fortnightlyHeadlineHealthcare": "Tiha, ali moćna revolucija zdravstva", "fortnightlyLatestUpdates": "Posljednje novosti", "fortnightlyTrendingStocks": "Stocks", "rallyBillDetailTotalAmount": "Ukupni iznos", "demoCupertinoPickerDateTime": "Datum i vrijeme", "signIn": "PRIJAVA", "dataTableRowWithSugar": "{value} sa šećerom", "dataTableRowApplePie": "Pita od jabuka", "dataTableRowDonut": "Krafna", "dataTableRowHoneycomb": "Saće", "dataTableRowLollipop": "Lizalica", "dataTableRowJellyBean": "Žele bomboni", "dataTableRowGingerbread": "Paprenjak", "dataTableRowCupcake": "Cupcake", "dataTableRowEclair": "Ekler", "dataTableRowIceCreamSandwich": "Sladoledni sendvič", "dataTableRowFrozenYogurt": "Zamrznuti jogurt", "dataTableColumnIron": "Željezo (%)", "dataTableColumnCalcium": "Kalcij (%)", "dataTableColumnSodium": "Natrij (mg)", "demoTimePickerTitle": "Alat za odabir vremena", "demo2dTransformationsResetTooltip": "Poništavanje transformacija", "dataTableColumnFat": "Masti (g)", "dataTableColumnCalories": "Kalorije", "dataTableColumnDessert": "Desert (1 porcija)", "cardsDemoTravelDestinationLocation1": "Thanjavur, Tamil Nadu", "demoTimePickerDescription": "Prikazuje dijalog koji sadrži alat za odabir vremena u materijalnom dizajnu.", "demoPickersShowPicker": "PRIKAŽI ALAT ZA ODABIR", "demoTabsScrollingTitle": "Pomicanje", "demoTabsNonScrollingTitle": "Bez pomicanja", "craneHours": "{hours,plural,=1{1 h}few{{hours} h}other{{hours} h}}", "craneMinutes": "{minutes,plural,=1{1 min}few{{minutes} min}other{{minutes} min}}", "craneFlightDuration": "{hoursShortForm} {minutesShortForm}", "dataTableHeader": "Prehrana", "demoDatePickerTitle": "Alat za odabir datuma", "demoPickersSubtitle": "Odabir datuma i vremena", "demoPickersTitle": "Alati za odabir", "demo2dTransformationsEditTooltip": "Uređivanje pločice", "demoDataTableDescription": "Podatkovne tablice prikazuju informacije u rešetki redaka i stupaca. Informacije su organizirane tako da ih je lako pregledavati kako bi korisnici mogli tražiti uzorke i uvide.", "demo2dTransformationsDescription": "Dodirnite da biste uređivali pločice i koristite pokrete da biste premještali scenu. Povucite da biste pomicali, spojite prste da biste zumirali i rotirajte pomoću dva prsta. Pritisnite gumb za poništavanje da biste se vratili na početno usmjerenje.", "demo2dTransformationsSubtitle": "Pomicanje, zumiranje i rotacija", "demo2dTransformationsTitle": "2D transformacije", "demoCupertinoTextFieldPIN": "PIN", "demoCupertinoTextFieldDescription": "Tekstno polje omogućuje korisniku da unese tekst, bilo pomoću hardverske ili pomoću tipkovnice na zaslonu.", "demoCupertinoTextFieldSubtitle": "Tekstna polja u iOS-ovom stilu", "demoCupertinoTextFieldTitle": "Tekstna polja", "demoDatePickerDescription": "Prikazuje dijalog koji sadrži alat za odabir datuma u materijalnom dizajnu.", "demoCupertinoPickerTime": "Vrijeme", "demoCupertinoPickerDate": "Datum", "demoCupertinoPickerTimer": "Odbrojavanje", "demoCupertinoPickerDescription": "Widget alata za odabir u iOS-ovom stilu koji se može koristiti za odabir nizova, datuma, vremena ili i datuma i vremena.", "demoCupertinoPickerSubtitle": "Alati za odabir u iOS-ovom stilu", "demoCupertinoPickerTitle": "Alati za odabir", "dataTableRowWithHoney": "{value} s medom", "cardsDemoTravelDestinationCity2": "Chettinad", "bannerDemoResetText": "Poništi natpis", "bannerDemoMultipleText": "Više radnji", "bannerDemoLeadingText": "Početna ikona", "dismiss": "ODBACI", "cardsDemoTappable": "Reagira na dodir", "cardsDemoSelectable": "Može se odabrati (dugi pritisak)", "cardsDemoExplore": "Istražite", "cardsDemoExploreSemantics": "Istražite: {destinationName}", "cardsDemoShareSemantics": "Podijelite: {destinationName}", "cardsDemoTravelDestinationTitle1": "Deset gradova koje trebate posjetiti u Tamil Naduu", "cardsDemoTravelDestinationDescription1": "Broj 10", "cardsDemoTravelDestinationCity1": "Thanjavur", "dataTableColumnProtein": "Bjelančevine (g)", "cardsDemoTravelDestinationTitle2": "Obrtnici južne Indije", "cardsDemoTravelDestinationDescription2": "Prelci svile", "bannerDemoText": "Vaša je zaporka ažurirana na vašem drugom uređaju. Prijavite se ponovo.", "cardsDemoTravelDestinationLocation2": "Sivaganga, Tamil Nadu", "cardsDemoTravelDestinationTitle3": "Hram Brihadisvara", "cardsDemoTravelDestinationDescription3": "Hramovi", "demoBannerTitle": "Natpis", "demoBannerSubtitle": "Prikazivanje natpisa na popisu", "demoBannerDescription": "Natpis prikazuje važnu, jezgrovitu poruku i navodi radnje koje korisnici trebaju izvršiti (mogu i odbaciti natpis). Odbacivanje nije moguće bez korisničke radnje.", "demoCardTitle": "Kartice", "demoCardSubtitle": "Osnovne kartice sa zaobljenim uglovima", "demoCardDescription": "Kartica je list materijala na kojem se pružaju neke povezane informacije, na primjer album, geografska lokacija, jelo, podaci za kontakt itd.", "demoDataTableTitle": "Podatkovne tablice", "demoDataTableSubtitle": "Redci i stupci informacija", "dataTableColumnCarbs": "Ugljikohidrati (g)", "placeTanjore": "Tanjore", "demoGridListsTitle": "Popisi u rešetki", "placeFlowerMarket": "Cvjećarnica na tržnici", "placeBronzeWorks": "Radionica za izradu bronce", "placeMarket": "Tržnica", "placeThanjavurTemple": "Hram Thanjavur", "placeSaltFarm": "Solana", "placeScooters": "Skuteri", "placeSilkMaker": "Proizvođači svile", "placeLunchPrep": "Priprema ručka", "placeBeach": "Plaža", "placeFisherman": "Ribar", "demoMenuSelected": "Odabrano: {value}", "demoMenuRemove": "Ukloni", "demoMenuGetLink": "Dohvati vezu", "demoMenuShare": "Udio", "demoBottomAppBarSubtitle": "Prikazuje ladicu za navigaciju i radnje pri dnu", "demoMenuAnItemWithASectionedMenu": "Stavka s izbornikom po odjeljcima", "demoMenuADisabledMenuItem": "Onemogućena stavka izbornika", "demoLinearProgressIndicatorTitle": "Linearni pokazivač napretka", "demoMenuContextMenuItemOne": "Prva stavka kontekstnog izbornika", "demoMenuAnItemWithASimpleMenu": "Stavka s jednostavnim izbornikom", "demoCustomSlidersTitle": "Prilagođeni klizači", "demoMenuAnItemWithAChecklistMenu": "Stavka s izbornikom s kontrolnim popisom", "demoCupertinoActivityIndicatorTitle": "Pokazivač aktivnosti", "demoCupertinoActivityIndicatorSubtitle": "Pokazivači aktivnosti u iOS-ovom stilu", "demoCupertinoActivityIndicatorDescription": "Pokazivač aktivnosti u iOS-ovom stilu koji se okreće u smjeru kazaljke na satu.", "demoCupertinoNavigationBarTitle": "Navigacijska traka", "demoCupertinoNavigationBarSubtitle": "Navigacijska traka u iOS-ovom stilu", "demoCupertinoNavigationBarDescription": "Navigacijska traka u iOS-ovom stilu. Navigacijska traka jest alatna traka koja se sastoji barem od naslova stranice u središtu alatne trake.", "demoCupertinoPullToRefreshTitle": "Povucite za osvježavanje", "demoCupertinoPullToRefreshSubtitle": "Kontrola povuci za osvježavanje u iOS-ovom stilu", "demoCupertinoPullToRefreshDescription": "Widget na kojem je implementirana kontrola povuci za osvježavanje sadržaja u iOS-ovom stilu.", "demoProgressIndicatorTitle": "Pokazivači napretka", "demoProgressIndicatorSubtitle": "Linearni, kružni, neodređeni", "demoCircularProgressIndicatorTitle": "Kružni pokazivač napretka", "demoCircularProgressIndicatorDescription": "Kružni pokazivač napretka u materijalnom dizajnu koji okretanjem pokazuje da je aplikacija zauzeta.", "demoMenuFour": "Četiri", "demoLinearProgressIndicatorDescription": "Linearni pokazivač napretka u materijalnom dizajnu poznat i kao traka napretka.", "demoTooltipTitle": "Opisi", "demoTooltipSubtitle": "Kratka poruka prikazana kod dugog pritiska ili zadržavanja iznad elementa", "demoTooltipDescription": "Opisi pružaju tekstne oznake koje pomažu objasniti funkciju gumba ili druge radnje korisničkog sučelja. Opisi prikazuju informativni tekst kada se korisnik zadrži iznad elementa, fokusira se na njega ili ga dugo pritisne.", "demoTooltipInstructions": "Koristite dugi pritisak ili se zadržite iznad elementa za prikazivanje opisa.", "placeChennai": "Chennai", "demoMenuChecked": "Označeno: {value}", "placeChettinad": "Chettinad", "demoMenuPreview": "Pregled", "demoBottomAppBarTitle": "Donja traka aplikacije", "demoBottomAppBarDescription": "Donja traka aplikacije omogućuje pristup donjoj ladici za navigaciju i najviše četirima radnjama, uključujući plutajući gumb za radnju.", "bottomAppBarNotch": "Urez", "bottomAppBarPosition": "Položaj plutajućeg gumba za radnju", "bottomAppBarPositionDockedEnd": "Usidren – na kraju", "bottomAppBarPositionDockedCenter": "Usidren – u sredini", "bottomAppBarPositionFloatingEnd": "Plutajući – na kraju", "bottomAppBarPositionFloatingCenter": "Plutajući – u sredini", "demoSlidersEditableNumericalValue": "Numerička vrijednost s mogućnošću uređivanja", "demoGridListsSubtitle": "Izgled redaka i stupaca", "demoGridListsDescription": "Popisi u rešetki najprikladniji su za predstavljanje homogenih podataka, uglavnom slika. Svaka stavka na popisu u rešetki naziva se pločica.", "demoGridListsImageOnlyTitle": "Samo slika", "demoGridListsHeaderTitle": "Sa zaglavljem", "demoGridListsFooterTitle": "S podnožjem", "demoSlidersTitle": "Klizači", "demoSlidersSubtitle": "Widgeti za odabir vrijednosti klizanjem", "demoSlidersDescription": "Klizači odražavaju raspon vrijednosti duž trake na kojoj korisnici mogu odabrati pojedinačnu vrijednost. Idealni su za podešavanje postavki kao što su glasnoća, svjetlina ili primjena filtara za slike.", "demoRangeSlidersTitle": "Klizači raspona", "demoRangeSlidersDescription": "Klizači odražavaju raspon vrijednost duž trake. Mogu imati ikone na oba kraja trake koji odražavaju raspon vrijednosti. Idealni su za podešavanje postavki kao što su glasnoća, svjetlina ili primjena filtara za slike.", "demoMenuAnItemWithAContextMenuButton": "Stavka s kontekstnim izbornikom", "demoCustomSlidersDescription": "Klizači odražavaju raspon vrijednosti duž trake na kojoj korisnici mogu odabrati pojedinačnu vrijednost ili raspon vrijednosti. Klizači mogu biti tematski ili prilagođeni.", "demoSlidersContinuousWithEditableNumericalValue": "Kontinuirani s numeričkom vrijednošću koju je moguće urediti", "demoSlidersDiscrete": "Diskretni", "demoSlidersDiscreteSliderWithCustomTheme": "Diskretni klizač s prilagođenom temom", "demoSlidersContinuousRangeSliderWithCustomTheme": "Kontinuirani klizač raspona s prilagođenom temom", "demoSlidersContinuous": "Kontinuirani", "placePondicherry": "Pondicherry", "demoMenuTitle": "Izbornik", "demoContextMenuTitle": "Kontekstni izbornik", "demoSectionedMenuTitle": "Izbornik po odjeljcima", "demoSimpleMenuTitle": "Jednostavan izbornik", "demoChecklistMenuTitle": "Izbornik s kontrolnim popisom", "demoMenuSubtitle": "Gumbi izbornika i jednostavni izbornici", "demoMenuDescription": "Izbornik prikazuje popis izbora na privremenoj površini. Pojavljuju se prilikom korisnikove interakcije s gumbom, radnjom i ostalim kontrolama.", "demoMenuItemValueOne": "Prva stavka izbornika", "demoMenuItemValueTwo": "Druga stavka izbornika", "demoMenuItemValueThree": "Treća stavka izbornika", "demoMenuOne": "Jedan", "demoMenuTwo": "Dva", "demoMenuThree": "Tri", "demoMenuContextMenuItemThree": "Treća stavka kontekstnog izbornika", "demoCupertinoSwitchSubtitle": "Prekidač u iOS-ovom stilu", "demoSnackbarsText": "Ovo je kratka interaktivna obavijest.", "demoCupertinoSliderSubtitle": "Klizač u iOS-ovom stilu", "demoCupertinoSliderDescription": "Klizač se može koristiti za odabir kontinuiranog ili diskretnog skupa vrijednosti.", "demoCupertinoSliderContinuous": "Kontinuirano: {value}", "demoCupertinoSliderDiscrete": "Diskretno: {value}", "demoSnackbarsAction": "Pritisnuli ste radnju za kratku interaktivnu obavijest.", "backToGallery": "Natrag u galeriju", "demoCupertinoTabBarTitle": "Traka kartica", "demoCupertinoSwitchDescription": "Prekidač se koristi za uključivanje/isključivanje stanja jedne postavke.", "demoSnackbarsActionButtonLabel": "RADNJA", "cupertinoTabBarProfileTab": "Profil", "demoSnackbarsButtonLabel": "PRIKAŽITE KRATKU INTERAKTIVNU OBAVIJEST", "demoSnackbarsDescription": "Kratke interaktivne obavijesti obavještavaju korisnike o postupku koji je aplikacija izvela ili će izvesti. One se pojavljuju privremeno prema dnu zaslona. Ne bi trebale ometati korisnički doživljaj i nije potreban korisnički unos da bi nestale.", "demoSnackbarsSubtitle": "Kratke interaktivne obavijesti prikazuju poruke na dnu zaslona", "demoSnackbarsTitle": "Kratke interaktivne obavijesti", "demoCupertinoSliderTitle": "Klizač", "cupertinoTabBarChatTab": "Chat", "cupertinoTabBarHomeTab": "Početna", "demoCupertinoTabBarDescription": "Donja navigacijska traka kartica u iOS-ovom stilu. Prikazuje više kartica dok je jedna kartica aktivna (prema zadanim postavkama to je prva kartica).", "demoCupertinoTabBarSubtitle": "Donja traka kartica u iOS-ovom stilu", "demoOptionsFeatureTitle": "Opcije prikaza", "demoOptionsFeatureDescription": "Dodirnite ovdje da biste vidjeli dostupne opcije za ovaj demo.", "demoCodeViewerCopyAll": "KOPIRAJ SVE", "shrineScreenReaderRemoveProductButton": "Uklonite {product}", "shrineScreenReaderProductAddToCart": "Dodavanje u košaricu", "shrineScreenReaderCart": "{quantity,plural,=0{Košarica, nema artikala}=1{Košarica, jedan artikl}few{Košarica, {quantity} artikla}other{Košarica, {quantity} artikala}}", "demoCodeViewerFailedToCopyToClipboardMessage": "Kopiranje u međuspremnik nije uspjelo: {error}", "demoCodeViewerCopiedToClipboardMessage": "Kopirano u međuspremnik.", "craneSleep8SemanticLabel": "Majanske ruševine na litici iznad plaže", "craneSleep4SemanticLabel": "Hotel na obali jezera ispred planina", "craneSleep2SemanticLabel": "Citadela Machu Picchu", "craneSleep1SemanticLabel": "Planinska kuća u snježnom krajoliku sa zimzelenim drvećem", "craneSleep0SemanticLabel": "Bungalovi iznad vode", "craneFly13SemanticLabel": "Bazen uz more s palmama", "craneFly12SemanticLabel": "Bazen s palmama", "craneFly11SemanticLabel": "Cigleni svjetionik na moru", "craneFly10SemanticLabel": "Minareti džamije Al-Azhar za vrijeme zalaska sunca", "craneFly9SemanticLabel": "Muškarac se naslanja na antikni plavi automobil", "craneFly8SemanticLabel": "Supertree Grove", "craneEat9SemanticLabel": "Šank u kafiću sa slasticama", "craneEat2SemanticLabel": "Hamburger", "craneFly5SemanticLabel": "Hotel na obali jezera ispred planina", "demoSelectionControlsSubtitle": "Potvrdni okviri, izborni gumbi i prekidači", "craneEat10SemanticLabel": "Žena drži ogroman sendvič s dimljenom govedinom", "craneFly4SemanticLabel": "Bungalovi iznad vode", "craneEat7SemanticLabel": "Ulaz u pekarnicu", "craneEat6SemanticLabel": "Jelo od škampa", "craneEat5SemanticLabel": "Područje za sjedenje u umjetničkom restoranu", "craneEat4SemanticLabel": "Čokoladni desert", "craneEat3SemanticLabel": "Korejski taco", "craneFly3SemanticLabel": "Citadela Machu Picchu", "craneEat1SemanticLabel": "Prazan bar sa stolicama u stilu zalogajnice", "craneEat0SemanticLabel": "Pizza u krušnoj peći", "craneSleep11SemanticLabel": "Neboder Taipei 101", "craneSleep10SemanticLabel": "Minareti džamije Al-Azhar za vrijeme zalaska sunca", "craneSleep9SemanticLabel": "Cigleni svjetionik na moru", "craneEat8SemanticLabel": "Tanjur s riječnim rakovima", "craneSleep7SemanticLabel": "Šareni stanovi na trgu Ribeira", "craneSleep6SemanticLabel": "Bazen s palmama", "craneSleep5SemanticLabel": "Šator u polju", "settingsButtonCloseLabel": "Zatvori postavke", "demoSelectionControlsCheckboxDescription": "Potvrdni okviri omogućavaju korisniku odabir više opcija iz skupa. Vrijednost normalnog potvrdnog okvira točna je ili netočna, a vrijednost potvrdnog okvira s tri stanja može biti i nula.", "settingsButtonLabel": "Postavke", "demoListsTitle": "Popisi", "demoListsSubtitle": "Pomicanje po izgledu popisa", "demoListsDescription": "Jedan redak fiksne visine koji uglavnom sadrži tekst te ikonu na početku ili na kraju.", "demoOneLineListsTitle": "Jedan redak", "demoTwoLineListsTitle": "Dva retka", "demoListsSecondary": "Dodatni tekst", "demoSelectionControlsTitle": "Kontrole odabira", "craneFly7SemanticLabel": "Planina Rushmore", "demoSelectionControlsCheckboxTitle": "Potvrdni okvir", "craneSleep3SemanticLabel": "Muškarac se naslanja na antikni plavi automobil", "demoSelectionControlsRadioTitle": "Radio", "demoSelectionControlsRadioDescription": "Izborni gumbi omogućavaju korisniku odabir jedne opcije iz skupa. Upotrebljavajte izborne gumbe da biste omogućili ekskluzivni odabir ako mislite da korisnik treba vidjeti sve dostupne opcije istodobno.", "demoSelectionControlsSwitchTitle": "Prekidač", "demoSelectionControlsSwitchDescription": "Prekidači za uključivanje/isključivanje mijenjaju stanje jedne opcije postavki. Opcija kojom upravlja prekidač, kao i njezino stanje, trebali bi biti jasni iz odgovarajuće ugrađene oznake.", "craneFly0SemanticLabel": "Planinska kuća u snježnom krajoliku sa zimzelenim drvećem", "craneFly1SemanticLabel": "Šator u polju", "craneFly2SemanticLabel": "Molitvene zastave ispred snježne planine", "craneFly6SemanticLabel": "Pogled na Palaču lijepe umjetnosti iz zraka", "rallySeeAllAccounts": "Prikaži sve račune", "rallyBillAmount": "Račun {billName} na iznos {amount} dospijeva {date}.", "shrineTooltipCloseCart": "Zatvorite košaricu", "shrineTooltipCloseMenu": "Zatvorite izbornik", "shrineTooltipOpenMenu": "Otvorite izbornik", "shrineTooltipSettings": "Postavke", "shrineTooltipSearch": "Pretražite", "demoTabsDescription": "Kartice organiziraju sadržaj s različitih zaslona, iz različitih skupova podataka i drugih interakcija.", "demoTabsSubtitle": "Kartice s prikazima koji se mogu pomicati neovisno", "demoTabsTitle": "Kartice", "rallyBudgetAmount": "{budgetName} proračun, iskorišteno: {amountUsed} od {amountTotal}, preostalo: {amountLeft}", "shrineTooltipRemoveItem": "Uklonite stavku", "rallyAccountAmount": "{accountName} račun {accountNumber} s iznosom od {amount}.", "rallySeeAllBudgets": "Prikaži sve proračune", "rallySeeAllBills": "Prikaži sve račune", "craneFormDate": "Odaberite datum", "craneFormOrigin": "Odaberite polazište", "craneFly2": "Dolina Khumbu, Nepal", "craneFly3": "Machu Picchu, Peru", "craneFly4": "Malé, Maldivi", "craneFly5": "Vitznau, Švicarska", "craneFly6": "Ciudad de Mexico, Meksiko", "craneFly7": "Mount Rushmore, Sjedinjene Američke Države", "settingsTextDirectionLocaleBased": "Na temelju oznake zemlje/jezika", "craneFly9": "Havana, Kuba", "craneFly10": "Kairo, Egipat", "craneFly11": "Lisabon, Portugal", "craneFly12": "Napa, Sjedinjene Američke Države", "craneFly13": "Bali, Indonezija", "craneSleep0": "Malé, Maldivi", "craneSleep1": "Aspen, Sjedinjene Američke Države", "craneSleep2": "Machu Picchu, Peru", "demoCupertinoSegmentedControlTitle": "Segmentirano upravljanje", "craneSleep4": "Vitznau, Švicarska", "craneSleep5": "Big Sur, Sjedinjene Američke Države", "craneSleep6": "Napa, Sjedinjene Američke Države", "craneSleep7": "Porto, Portugal", "craneSleep8": "Tulum, Meksiko", "craneEat5": "Seoul, Južna Koreja", "demoChipTitle": "Čipovi", "demoChipSubtitle": "Kompaktni elementi koji predstavljaju unos, atribut ili radnju", "demoActionChipTitle": "Čip radnji", "demoActionChipDescription": "Čipovi radnje skup su opcija koji pokreću radnju povezanu s primarnim sadržajem. Čipovi radnje trebali bi se prikazivati dinamički i kontekstualno na korisničkom sučelju.", "demoChoiceChipTitle": "Čip odabira", "demoChoiceChipDescription": "Čipovi odabira predstavljaju jedan odabir iz skupa. Čipovi odabira sadrže povezani opisni tekst ili kategorije.", "demoFilterChipTitle": "Element filtriranja", "demoFilterChipDescription": "Elementi filtriranja koriste oznake ili opisne riječi kao način filtriranja sadržaja.", "demoInputChipTitle": "Čip unosa", "demoInputChipDescription": "Čipovi unosa predstavljaju kompleksne informacije, na primjer entitete (osobe, mjesta ili predmete) ili tekst razgovora, u kompaktnom obliku.", "craneSleep9": "Lisabon, Portugal", "craneEat10": "Lisabon, Portugal", "demoCupertinoSegmentedControlDescription": "Koristi se za odabir između nekoliko opcija koje se međusobno isključuju. Kad se u segmentiranom upravljanju odabere jedna opcija, poništava se odabir ostalih opcija.", "chipTurnOnLights": "Uključivanje svjetla", "chipSmall": "Malo", "chipMedium": "Srednje", "chipLarge": "Veliko", "chipElevator": "Dizalo", "chipWasher": "Perilica", "chipFireplace": "Kamin", "chipBiking": "Vožnja biciklom", "craneFormDiners": "Zalogajnice", "rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Možda možete dobiti veći povrat poreza! Dodijelite kategorije jednoj nedodijeljenoj transakciji.}few{Možda možete dobiti veći povrat poreza! Dodijelite kategorije za {count} nedodijeljene transakcije.}other{Možda možete dobiti veći povrat poreza! Dodijelite kategorije za {count} nedodijeljenih transakcija.}}", "craneFormTime": "Odaberite vrijeme", "craneFormLocation": "Odaberite lokaciju", "craneFormTravelers": "Putnici", "craneEat8": "Atlanta, Sjedinjene Američke Države", "craneFormDestination": "Odaberite odredište", "craneFormDates": "Odaberite datume", "craneFly": "LET", "craneSleep": "SPAVANJE", "craneEat": "PREHRANA", "craneFlySubhead": "Istražite letove po odredištu", "craneSleepSubhead": "Istražite smještajne objekte po odredištu", "craneEatSubhead": "Istražite restorane po odredištu", "craneFlyStops": "{numberOfStops,plural,=0{Direktni}=1{Jedna stanica}few{{numberOfStops} stanice}other{{numberOfStops} stanica}}", "craneSleepProperties": "{totalProperties,plural,=0{Nema dostupnih entiteta}=1{Jedan dostupan entitet}few{{totalProperties} dostupna entita}other{{totalProperties} dostupnih entiteta}}", "craneEatRestaurants": "{totalRestaurants,plural,=0{Nema restorana}=1{Jedan restoran}few{{totalRestaurants} restorana}other{{totalRestaurants} restorana}}", "craneFly0": "Aspen, Sjedinjene Američke Države", "demoCupertinoSegmentedControlSubtitle": "Segmentirano upravljanje u stilu iOS-a", "craneSleep10": "Kairo, Egipat", "craneEat9": "Madrid, Španjolska", "craneFly1": "Big Sur, Sjedinjene Američke Države", "craneEat7": "Nashville, Sjedinjene Američke Države", "craneEat6": "Seattle, Sjedinjene Američke Države", "craneFly8": "Singapur", "craneEat4": "Pariz, Francuska", "craneEat3": "Portland, Sjedinjene Američke Države", "craneEat2": "Córdoba, Argentina", "craneEat1": "Dallas, Sjedinjene Američke Države", "craneEat0": "Napulj, Italija", "craneSleep11": "Taipei, Tajvan", "craneSleep3": "Havana, Kuba", "shrineLogoutButtonCaption": "ODJAVA", "rallyTitleBills": "RAČUNI", "rallyTitleAccounts": "RAČUNI", "shrineProductVagabondSack": "Vrećasta torba", "rallyAccountDetailDataInterestYtd": "Kamate od početka godine do danas", "shrineProductWhitneyBelt": "Pojas Whitney", "shrineProductGardenStrand": "Vrtni konop", "shrineProductStrutEarrings": "Strut naušnice", "shrineProductVarsitySocks": "Čarape s prugama", "shrineProductWeaveKeyring": "Pleteni privjesak za ključeve", "shrineProductGatsbyHat": "Kačket", "shrineProductShrugBag": "Torba s kratkom ručkom za nošenje na ramenu", "shrineProductGiltDeskTrio": "Trio pozlaćenih stolića", "shrineProductCopperWireRack": "Bakrena vješalica", "shrineProductSootheCeramicSet": "Keramički set Soothe", "shrineProductHurrahsTeaSet": "Čajni set Hurrahs", "shrineProductBlueStoneMug": "Plava kamena šalica", "shrineProductRainwaterTray": "Posuda za kišnicu", "shrineProductChambrayNapkins": "Ubrusi od chambraya", "shrineProductSucculentPlanters": "Posude za sukulentne biljke", "shrineProductQuartetTable": "Četiri stolića", "shrineProductKitchenQuattro": "Četverodijelni kuhinjski set", "shrineProductClaySweater": "Džemper u boji gline", "shrineProductSeaTunic": "Tunika morskoplave boje", "shrineProductPlasterTunic": "Tunika u boji gipsa", "rallyBudgetCategoryRestaurants": "Restorani", "shrineProductChambrayShirt": "Košulja od chambraya", "shrineProductSeabreezeSweater": "Džemper s nautičkim uzorkom", "shrineProductGentryJacket": "Gentry jakna", "shrineProductNavyTrousers": "Mornarskoplave hlače", "shrineProductWalterHenleyWhite": "Walter Henley (bijele boje)", "shrineProductSurfAndPerfShirt": "Surf and perf majica", "shrineProductGingerScarf": "Šal u boji đumbira", "shrineProductRamonaCrossover": "Ramona crossover", "shrineProductClassicWhiteCollar": "Klasična bijela košulja", "shrineProductSunshirtDress": "Haljina za zaštitu od sunca", "rallyAccountDetailDataInterestRate": "Kamatna stopa", "rallyAccountDetailDataAnnualPercentageYield": "Godišnji postotak prinosa", "rallyAccountDataVacation": "Odmor", "shrineProductFineLinesTee": "Majica s tankim crtama", "rallyAccountDataHomeSavings": "Štednja za kupnju doma", "rallyAccountDataChecking": "Tekući", "rallyAccountDetailDataInterestPaidLastYear": "Kamate plaćene prošle godine", "rallyAccountDetailDataNextStatement": "Sljedeća izjava", "rallyAccountDetailDataAccountOwner": "Vlasnik računa", "rallyBudgetCategoryCoffeeShops": "Kafići", "rallyBudgetCategoryGroceries": "Namirnice", "shrineProductCeriseScallopTee": "Tamnoružičasta majica s valovitim rubom", "rallyBudgetCategoryClothing": "Odjeća", "rallySettingsManageAccounts": "Upravljajte računima", "rallyAccountDataCarSavings": "Štednja za automobil", "rallySettingsTaxDocuments": "Porezni dokumenti", "rallySettingsPasscodeAndTouchId": "Šifra i Touch ID", "rallySettingsNotifications": "Obavijesti", "rallySettingsPersonalInformation": "Osobni podaci", "rallySettingsPaperlessSettings": "Postavke bez papira", "rallySettingsFindAtms": "Pronađite bankomate", "rallySettingsHelp": "Pomoć", "rallySettingsSignOut": "Odjava", "rallyAccountTotal": "Ukupno", "rallyBillsDue": "Rok", "rallyBudgetLeft": "Preostalo", "rallyAccounts": "Računi", "rallyBills": "Računi", "rallyBudgets": "Proračuni", "rallyAlerts": "Upozorenja", "rallySeeAll": "PRIKAŽI SVE", "rallyFinanceLeft": "PREOSTALO", "rallyTitleOverview": "PREGLED", "shrineProductShoulderRollsTee": "Majica s podvrnutim rukavima", "shrineNextButtonCaption": "SLJEDEĆE", "rallyTitleBudgets": "PRORAČUNI", "rallyTitleSettings": "POSTAVKE", "rallyLoginLoginToRally": "Prijavite se na Rally", "rallyLoginNoAccount": "Nemate račun?", "rallyLoginSignUp": "REGISTRACIJA", "rallyLoginUsername": "Korisničko ime", "rallyLoginPassword": "Zaporka", "rallyLoginLabelLogin": "Prijava", "rallyLoginRememberMe": "Zapamti me", "rallyLoginButtonLogin": "PRIJAVA", "rallyAlertsMessageHeadsUpShopping": "Upozorenje! Iskoristili ste {percent} proračuna za kupnju ovaj mjesec.", "rallyAlertsMessageSpentOnRestaurants": "Ovaj ste tjedan potrošili {amount} u restoranima.", "rallyAlertsMessageATMFees": "Ovaj ste mjesec potrošili {amount} za naknade za bankomate", "rallyAlertsMessageCheckingAccount": "Bravo! Na tekućem računu imate {percent} više nego prošli mjesec.", "shrineMenuCaption": "IZBORNIK", "shrineCategoryNameAll": "SVE", "shrineCategoryNameAccessories": "DODACI", "shrineCategoryNameClothing": "ODJEĆA", "shrineCategoryNameHome": "DOM", "shrineLoginUsernameLabel": "Korisničko ime", "shrineLoginPasswordLabel": "Zaporka", "shrineCancelButtonCaption": "ODUSTANI", "shrineCartTaxCaption": "Porez:", "shrineCartPageCaption": "KOŠARICA", "shrineProductQuantity": "Količina: {quantity}", "shrineProductPrice": "x {price}", "shrineCartItemCount": "{quantity,plural,=0{NEMA STAVKI}=1{JEDNA STAVKA}few{{quantity} STAVKE}other{{quantity} STAVKI}}", "shrineCartClearButtonCaption": "ISPRAZNI KOŠARICU", "shrineCartTotalCaption": "UKUPNO", "shrineCartSubtotalCaption": "Međuzbroj:", "shrineCartShippingCaption": "Dostava:", "shrineProductGreySlouchTank": "Siva majica bez rukava", "shrineProductStellaSunglasses": "Sunčane naočale Stella", "shrineProductWhitePinstripeShirt": "Prugasta bijela košulja", "demoTextFieldWhereCanWeReachYou": "Na kojem vas broju možemo dobiti?", "settingsTextDirectionLTR": "Slijeva udesno", "settingsTextScalingLarge": "Veliki", "demoBottomSheetHeader": "Zaglavlje", "demoBottomSheetItem": "Stavka {value}", "demoBottomTextFieldsTitle": "Tekstualna polja", "demoTextFieldTitle": "Tekstualna polja", "demoTextFieldSubtitle": "Jedan redak teksta i brojeva koji se mogu uređivati", "demoTextFieldDescription": "Tekstualna polja omogućuju korisnicima da unesu tekst u korisničko sučelje. Obično su u obliku obrazaca i dijaloga.", "demoTextFieldShowPasswordLabel": "Prikaži zaporku", "demoTextFieldHidePasswordLabel": "Sakrij zaporku", "demoTextFieldFormErrors": "Prije slanja ispravite pogreške označene crvenom bojom.", "demoTextFieldNameRequired": "Ime je obavezno.", "demoTextFieldOnlyAlphabeticalChars": "Unesite samo slova abecede.", "demoTextFieldEnterUSPhoneNumber": "(###) ###-#### – unesite telefonski broj u SAD-u.", "demoTextFieldEnterPassword": "Unesite zaporku.", "demoTextFieldPasswordsDoNotMatch": "Zaporke se ne podudaraju", "demoTextFieldWhatDoPeopleCallYou": "Kako vas zovu?", "demoTextFieldNameField": "Ime*", "demoBottomSheetButtonText": "PRIKAŽI DONJU TABLICU", "demoTextFieldPhoneNumber": "Telefonski broj*", "demoBottomSheetTitle": "Donja tablica", "demoTextFieldEmail": "E-adresa", "demoTextFieldTellUsAboutYourself": "Recite nam nešto o sebi (na primjer napišite što radite ili koji su vam hobiji)", "demoTextFieldKeepItShort": "Neka bude kratko, ovo je samo demonstracija.", "starterAppGenericButton": "GUMB", "demoTextFieldLifeStory": "Biografija", "demoTextFieldSalary": "Plaća", "demoTextFieldUSD": "USD", "demoTextFieldNoMoreThan": "Ne možete unijeti više od osam znakova.", "demoTextFieldPassword": "Zaporka*", "demoTextFieldRetypePassword": "Ponovo unesite zaporku*", "demoTextFieldSubmit": "POŠALJI", "demoBottomNavigationSubtitle": "Donja navigacija koja se postupno prikazuje i nestaje", "demoBottomSheetAddLabel": "Dodavanje", "demoBottomSheetModalDescription": "Modalna donja tablica alternativa je izborniku ili dijalogu i onemogućuje korisnicima interakciju s ostatkom aplikacije.", "demoBottomSheetModalTitle": "Modalna donja tablica", "demoBottomSheetPersistentDescription": "Fiksna donja tablica prikazuje informacije koje nadopunjuju primarni sadržaj aplikacije. Ostaje vidljiva čak i tijekom korisnikove interakcije s drugim dijelovima aplikacije.", "demoBottomSheetPersistentTitle": "Fiksna donja tablica", "demoBottomSheetSubtitle": "Fiksne i modalne donje tablice", "demoTextFieldNameHasPhoneNumber": "{name} ima telefonski broj {phoneNumber}", "buttonText": "GUMB", "demoTypographyDescription": "Definicije raznih tipografskih stilova u materijalnom dizajnu.", "demoTypographySubtitle": "Svi unaprijed definirani stilovi teksta", "demoTypographyTitle": "Tipografija", "demoFullscreenDialogDescription": "Svojstvo fullscreenDialog određuje je li dolazna stranica modalni dijalog na cijelom zaslonu", "demoFlatButtonDescription": "Ravni gumb prikazuje mrlju boje prilikom pritiska, ali se ne podiže. Ravne gumbe koristite na alatnim trakama, u dijalozima i ugrađene u ispunu", "demoBottomNavigationDescription": "Donja navigacijska traka prikazuje tri do pet odredišta pri dnu zaslona. Svako odredište predstavlja ikona i tekstna oznaka koja nije obavezna. Kad korisnik dodirne ikonu na donjoj navigacijskoj traci, otvara se odredište navigacije na najvišoj razini povezano s tom ikonom.", "demoBottomNavigationSelectedLabel": "Odabrana oznaka", "demoBottomNavigationPersistentLabels": "Fiksne oznake", "starterAppDrawerItem": "Stavka {value}", "demoTextFieldRequiredField": "* označava obavezno polje", "demoBottomNavigationTitle": "Donja navigacija", "settingsLightTheme": "Svijetlo", "settingsTheme": "Tema", "settingsPlatformIOS": "iOS", "settingsPlatformAndroid": "Android", "settingsTextDirectionRTL": "Zdesna ulijevo", "settingsTextScalingHuge": "Ogroman", "cupertinoButton": "Gumb", "settingsTextScalingNormal": "Uobičajeni", "settingsTextScalingSmall": "Mali", "settingsSystemDefault": "Sustav", "settingsTitle": "Postavke", "rallyDescription": "Aplikacija za osobne financije", "aboutDialogDescription": "Da biste vidjeli izvorni kôd za ovu aplikaciju, posjetite {repoLink}.", "bottomNavigationCommentsTab": "Komentari", "starterAppGenericBody": "Glavni tekst", "starterAppGenericHeadline": "Naslov", "starterAppGenericSubtitle": "Titlovi", "starterAppGenericTitle": "Naslov", "starterAppTooltipSearch": "Pretraživanje", "starterAppTooltipShare": "Dijeljenje", "starterAppTooltipFavorite": "Favorit", "starterAppTooltipAdd": "Dodavanje", "bottomNavigationCalendarTab": "Kalendar", "starterAppDescription": "Responzivni izgled aplikacije za pokretanje", "starterAppTitle": "Aplikacija za pokretanje", "aboutFlutterSamplesRepo": "GitHub repozitorij primjera za Flutter", "bottomNavigationContentPlaceholder": "Rezervirano mjesto za karticu {title}", "bottomNavigationCameraTab": "Fotoaparat", "bottomNavigationAlarmTab": "Alarm", "bottomNavigationAccountTab": "Račun", "demoTextFieldYourEmailAddress": "Vaša e-adresa", "demoToggleButtonDescription": "Prekidači se mogu upotrebljavati za grupiranje povezanih opcija. Da bi se naglasile grupe povezanih prekidača, grupa bi trebala dijeliti zajednički spremnik", "colorsGrey": "SIVA", "colorsBrown": "SMEĐA", "colorsDeepOrange": "TAMNONARANČASTA", "colorsOrange": "NARANČASTA", "colorsAmber": "JANTARNA", "colorsYellow": "ŽUTA", "colorsLime": "ŽUTOZELENA", "colorsLightGreen": "SVIJETLOZELENA", "colorsGreen": "ZELENA", "homeHeaderGallery": "Galerija", "homeHeaderCategories": "Kategorije", "shrineDescription": "Moderna aplikacija za maloprodaju", "craneDescription": "Prilagođena aplikacija za putovanja", "homeCategoryReference": "STILOVI I DRUGO", "demoInvalidURL": "Prikazivanje URL-a nije uspjelo:", "demoOptionsTooltip": "Opcije", "demoInfoTooltip": "Informacije", "demoCodeTooltip": "Kôd demonstracije", "demoDocumentationTooltip": "Dokumentacija API-ja", "demoFullscreenTooltip": "Cijeli zaslon", "settingsTextScaling": "Skaliranje teksta", "settingsTextDirection": "Smjer teksta", "settingsLocale": "Oznaka zemlje/jezika", "settingsPlatformMechanics": "Mehanika platforme", "settingsDarkTheme": "Tamno", "settingsSlowMotion": "Usporena snimka", "settingsAbout": "O usluzi Flutter Gallery", "settingsFeedback": "Pošaljite komentare", "settingsAttribution": "Dizajnirala agencija TOASTER iz Londona", "demoButtonTitle": "Gumbi", "demoButtonSubtitle": "Tekstni, izdignuti, ocrtani i brojni drugi", "demoFlatButtonTitle": "Ravni gumb", "demoRaisedButtonDescription": "Izdignuti gumbi dodaju dimenziju većini ravnih rasporeda. Naglašavaju funkcije na prostorima koji su prostrani ili imaju mnogo sadržaja.", "demoRaisedButtonTitle": "Izdignuti gumb", "demoOutlineButtonTitle": "Ocrtani gumb", "demoOutlineButtonDescription": "Ocrtani gumbi postaju neprozirni i izdižu se kad se pritisnu. Obično se uparuju s izdignutim gumbima da bi naznačili alternativnu, sekundarnu radnju.", "demoToggleButtonTitle": "Prekidači", "colorsTeal": "TIRKIZNOPLAVA", "demoFloatingButtonTitle": "Plutajući gumb za radnju", "demoFloatingButtonDescription": "Plutajući gumb za radnju okrugla je ikona gumba koja lebdi iznad sadržaja u svrhu promocije primarne radnje u aplikaciji.", "demoDialogTitle": "Dijalozi", "demoDialogSubtitle": "Jednostavni, upozorenje i na cijelom zaslonu", "demoAlertDialogTitle": "Upozorenje", "demoAlertDialogDescription": "Dijalog upozorenja informira korisnika o situacijama koje je potrebno potvrditi. Dijalog upozorenja ima naslov i popis radnji, no te stavke nisu obavezne.", "demoAlertTitleDialogTitle": "Upozorenje s naslovom", "demoSimpleDialogTitle": "Jednostavni", "demoSimpleDialogDescription": "Jednostavni dijalog nudi korisnicima odabir između nekoliko opcija. Jednostavni dijalog ima naslov koji nije obavezan i prikazuje se iznad opcija odabira.", "demoFullscreenDialogTitle": "Na cijelom zaslonu", "demoCupertinoButtonsTitle": "Gumbi", "demoCupertinoButtonsSubtitle": "Gumbi u iOS-ovom stilu", "demoCupertinoButtonsDescription": "Gumb u iOS-ovom stilu. Na njemu su tekst i/ili ikona koji se postupno prikazuju ili nestaju na dodir. Može imati pozadinu, no to nije obavezno.", "demoCupertinoAlertsTitle": "Upozorenja", "demoCupertinoAlertsSubtitle": "Dijalozi upozorenja u iOS-ovom stilu", "demoCupertinoAlertTitle": "Upozorenje", "demoCupertinoAlertDescription": "Dijalog upozorenja informira korisnika o situacijama koje je potrebno potvrditi. Dijalog upozorenja ima naslov, sadržaj i popis radnji, no te stavke nisu obavezne. Naslov se prikazuje iznad sadržaja, a radnje ispod sadržaja.", "demoCupertinoAlertWithTitleTitle": "Upozorenje s naslovom", "demoCupertinoAlertButtonsTitle": "Upozorenje s gumbima", "demoCupertinoAlertButtonsOnlyTitle": "Samo gumbi upozorenja", "demoCupertinoActionSheetTitle": "Tablica radnji", "demoCupertinoActionSheetDescription": "Tablica radnji poseban je stil upozorenja koje korisniku nudi barem dvije opcije na izbor u vezi s trenutačnim kontekstom. Tablica radnji može imati naslov, dodatnu poruku i popis radnji.", "demoColorsTitle": "Boje", "demoColorsSubtitle": "Sve unaprijed definirane boje", "demoColorsDescription": "Boje i konstante uzoraka boja koje predstavljaju paletu boja materijalnog dizajna.", "buttonTextEnabled": "ENABLED", "buttonTextDisabled": "DISABLED", "buttonTextCreate": "Izradite", "dialogSelectedOption": "Odabrali ste vrijednost: \"{value}\"", "dialogDiscardTitle": "Želite li odbaciti skicu?", "dialogLocationTitle": "Želite li upotrebljavati Googleovu uslugu lokacije?", "dialogLocationDescription": "Dopustite Googleu da pomogne aplikacijama odrediti lokaciju. To znači da će se anonimni podaci o lokaciji slati Googleu, čak i kada se ne izvodi nijedna aplikacija.", "dialogCancel": "ODUSTANI", "dialogDiscard": "ODBACI", "dialogDisagree": "NE SLAŽEM SE", "dialogAgree": "PRIHVAĆAM", "dialogSetBackup": "Postavljanje računa za sigurnosno kopiranje", "colorsBlueGrey": "PLAVOSIVA", "dialogShow": "PRIKAŽI DIJALOG", "dialogFullscreenTitle": "Dijalog na cijelom zaslonu", "dialogFullscreenSave": "SPREMI", "dialogFullscreenDescription": "Demonstracija dijaloga na cijelom zaslonu", "cupertinoButtonEnabled": "Enabled", "cupertinoButtonDisabled": "Disabled", "cupertinoButtonWithBackground": "S pozadinom", "cupertinoAlertCancel": "Odustani", "cupertinoAlertDiscard": "Odbaci", "cupertinoAlertLocationTitle": "Želite li dopustiti da aplikacija \"Karte pristupa vašoj lokaciji dok je upotrebljavate?", "cupertinoAlertLocationDescription": "Vaša trenutačna lokacija prikazivat će se na karti i koristiti za upute, rezultate pretraživanja u blizini i procjenu vremena putovanja.", "cupertinoAlertAllow": "Dopusti", "cupertinoAlertDontAllow": "Ne dopusti", "cupertinoAlertFavoriteDessert": "Odaberite omiljeni desert", "cupertinoAlertDessertDescription": "Odaberite svoju omiljenu vrstu deserta na popisu u nastavku. Vaš će se odabir koristiti za prilagodbu predloženog popisa zalogajnica u vašem području.", "cupertinoAlertCheesecake": "Torta od sira", "cupertinoAlertTiramisu": "Tiramisu", "cupertinoAlertApplePie": "Pita od jabuka", "cupertinoAlertChocolateBrownie": "Čokoladni kolač", "cupertinoShowAlert": "Prikaži upozorenje", "colorsRed": "CRVENA", "colorsPink": "RUŽIČASTA", "colorsPurple": "LJUBIČASTA", "colorsDeepPurple": "TAMNOLJUBIČASTA", "colorsIndigo": "MODROLJUBIČASTA", "colorsBlue": "PLAVA", "colorsLightBlue": "SVIJETLOPLAVA", "colorsCyan": "CIJAN", "dialogAddAccount": "Dodavanje računa", "Gallery": "Galerija", "Categories": "Kategorije", "SHRINE": "HRAM", "Basic shopping app": "Osnovna aplikacija za kupnju", "RALLY": "RELI", "CRANE": "CRANE", "Travel app": "Aplikacija za putovanja", "MATERIAL": "MATERIJAL", "CUPERTINO": "CUPERTINO", "REFERENCE STYLES & MEDIA": "REFERENTNI STILOVI I MEDIJI" }
gallery/lib/l10n/intl_hr.arb/0
{ "file_path": "gallery/lib/l10n/intl_hr.arb", "repo_id": "gallery", "token_count": 21556 }
813
{ "loading": "Се вчитува", "deselect": "Поништи го изборот", "select": "Избери", "selectable": "Може да се избере (со долго притискање)", "selected": "Избрано", "demo": "Демо", "bottomAppBar": "Долна лента со апликации", "notSelected": "Не е избрано", "demoCupertinoSearchTextFieldTitle": "Поле за пребарување текст", "demoCupertinoPicker": "Виџет за избор", "demoCupertinoSearchTextFieldSubtitle": "Поле за пребарување текст во iOS-стил", "demoCupertinoSearchTextFieldDescription": "Поле за пребарување текст што му овозможува на корисникот да пребарува со внесување текст и што може да понудува и филтрира предлози.", "demoCupertinoSearchTextFieldPlaceholder": "Внесете некој текст", "demoCupertinoScrollbarTitle": "Лента за лизгање", "demoCupertinoScrollbarSubtitle": "Лента за лизгање во iOS-стил", "demoCupertinoScrollbarDescription": "Лента за лизгање што се обвиткува околу подредената ставка", "demoTwoPaneItem": "Ставка {value}", "demoTwoPaneList": "Список", "demoTwoPaneFoldableLabel": "Преклопувачки", "demoTwoPaneSmallScreenLabel": "Мал екран", "demoTwoPaneSmallScreenDescription": "Вака се однесува TwoPane на уред со мал екран.", "demoTwoPaneTabletLabel": "Таблет/компјутер", "demoTwoPaneTabletDescription": "Вака се однесува TwoPane на поголем екран како таблет или компјутер.", "demoTwoPaneTitle": "TwoPane", "demoTwoPaneSubtitle": "Приспособливи распореди на преклопувачки, големи и мали екрани", "splashSelectDemo": "Изберете демо", "demoTwoPaneFoldableDescription": "Вака се однесува TwoPane на преклопувачки уред.", "demoTwoPaneDetails": "Детали", "demoTwoPaneSelectItem": "Изберете ставка", "demoTwoPaneItemDetails": "Детали за ставка {value}", "demoCupertinoContextMenuActionText": "Допрете го и задржете го логото на Flutter за да се прикаже контекстуалното мени.", "demoCupertinoContextMenuDescription": "Контекстуално мени со iOS-стил на цел екран што се појавува кога ќе се притисне долго на некој елемент.", "demoAppBarTitle": "Лента за апликацијата", "demoAppBarDescription": "Лентата за апликацијата обезбедува содржини и дејства поврзани со тековниот екран. Се користи за брендирање, наслови на екранот, навигација и дејства.", "demoDividerTitle": "Разделувач", "demoDividerSubtitle": "Разделувачот е тенка линија што групира содржини во списоци и распореди.", "demoDividerDescription": "Разделувачите може да се користат во списоци, фиоки и на други места за да се одделат содржини.", "demoVerticalDividerTitle": "Вертикален разделувач", "demoCupertinoContextMenuTitle": "Контекстуално мени", "demoCupertinoContextMenuSubtitle": "Контекстуално мени со iOS-стил", "demoAppBarSubtitle": "Прикажува информации и дејства поврзани со тековниот екран", "demoCupertinoContextMenuActionOne": "Прво дејство", "demoCupertinoContextMenuActionTwo": "Второ дејство", "demoDateRangePickerDescription": "Прикажува дијалог што содржи избирач на временски период во Material Design.", "demoDateRangePickerTitle": "Избирач на временски период", "demoNavigationDrawerUserName": "Корисничко име", "demoNavigationDrawerUserEmail": "[email protected]", "demoNavigationDrawerText": "Лизгајте од работ или допрете ја иконата горе лево за да ја погледнете фиоката", "demoNavigationRailTitle": "Шина за навигација", "demoNavigationRailSubtitle": "Се прикажува шина за навигација во апликацијата", "demoNavigationRailDescription": "Материјален виџет што се прикажува одлево или оддесно од апликацијата и служи за навигација помеѓу мал број на прикази, обично од три до пет.", "demoNavigationRailFirst": "Прва", "demoNavigationDrawerTitle": "Фиока за навигација", "demoNavigationRailThird": "Трета", "replyStarredLabel": "Означено со ѕвезда", "demoTextButtonDescription": "Копчето за текст прикажува дамка од мастило при притискање, но не се подига. Користете копчиња за текст во алатници, во дијалози и во линија со дополнување", "demoElevatedButtonTitle": "Подигнато копче", "demoElevatedButtonDescription": "Подигнатите копчиња додаваат димензионалност во распоредите што се претежно рамни. Ги нагласуваат функциите во збиените или широките простори.", "demoOutlinedButtonTitle": "Копче со контура", "demoOutlinedButtonDescription": "Копчињата со контура стануваат непроѕирни и се подигнуваат кога ќе ги притиснете. Честопати се спаруваат со подигнатите копчиња за да означат алтернативно секундарно дејство.", "demoContainerTransformDemoInstructions": "Картички, списоци и лебдечко копче за дејство", "demoNavigationDrawerSubtitle": "Се прикажува фиока во лента за апликации", "replyDescription": "Ефикасна и насочена апликација за е-пошта", "demoNavigationDrawerDescription": "Табла на Material Design што се отвора хоризонтално со лизгање од работ на екранот за да ви ги прикаже линковите за навиигација во апликацијата.", "replyDraftsLabel": "Нацрти", "demoNavigationDrawerToPageOne": "Ставка еден", "replyInboxLabel": "Приемно сандаче", "demoSharedXAxisDemoInstructions": "Копчиња за следно и назад", "replySpamLabel": "Спам", "replyTrashLabel": "Корпа", "replySentLabel": "Испратено", "demoNavigationRailSecond": "Втора", "demoNavigationDrawerToPageTwo": "Ставка два", "demoFadeScaleDemoInstructions": "Модален и лебдечко копче за дејство", "demoFadeThroughDemoInstructions": "Долна навигација", "demoSharedZAxisDemoInstructions": "Копче за иконата за „Поставки“", "demoSharedYAxisDemoInstructions": "Подреди според „Неодамна слушани“", "demoTextButtonTitle": "Копче за текст", "demoSharedZAxisBeefSandwichRecipeTitle": "Сендвич со телешко", "demoSharedZAxisDessertRecipeDescription": "Рецепт за десерт", "demoSharedYAxisAlbumTileSubtitle": "Изведувач", "demoSharedYAxisAlbumTileTitle": "Албум", "demoSharedYAxisRecentSortTitle": "Неодамна пуштени", "demoSharedYAxisAlphabeticalSortTitle": "A-Ш", "demoSharedYAxisAlbumCount": "268 албуми", "demoSharedYAxisTitle": "Споделена y-оска", "demoSharedXAxisCreateAccountButtonText": "СОЗДАЈ СМЕТКА", "demoFadeScaleAlertDialogDiscardButton": "ОТФРЛИ", "demoSharedXAxisSignInTextFieldLabel": "Е-пошта или телефонски број", "demoSharedXAxisSignInSubtitleText": "Најавете се со вашата сметка", "demoSharedXAxisSignInWelcomeText": "Здраво David Park", "demoSharedXAxisIndividualCourseSubtitle": "Прикажани засебно", "demoSharedXAxisBundledCourseSubtitle": "Во пакет", "demoFadeThroughAlbumsDestination": "Албуми", "demoSharedXAxisDesignCourseTitle": "Дизајн", "demoSharedXAxisIllustrationCourseTitle": "Илустрација", "demoSharedXAxisBusinessCourseTitle": "Бизнис", "demoSharedXAxisArtsAndCraftsCourseTitle": "Уметност и ракотворби", "demoMotionPlaceholderSubtitle": "Секундарен текст", "demoFadeScaleAlertDialogCancelButton": "ОТКАЖИ", "demoFadeScaleAlertDialogHeader": "Дијалог на предупредување", "demoFadeScaleHideFabButton": "СОКРИЈ ЛЕБДЕЧКО КОПЧЕ ЗА ДЕЈСТВО", "demoFadeScaleShowFabButton": "ПРИКАЖИ ЛЕБДЕЧКО КОПЧЕ ЗА ДЕЈСТВО", "demoFadeScaleShowAlertDialogButton": "ПРИКАЖИ МОДАЛНИ", "demoFadeScaleDescription": "Шемата на избледување се користи за елементи на корисничкиот интерфејс што влегуваат или излегуваат од границите на екранот, како дијалог што избледува во центарот на екранот.", "demoFadeScaleTitle": "Избледување", "demoFadeThroughTextPlaceholder": "123 фотографии", "demoFadeThroughSearchDestination": "Пребарување", "demoFadeThroughPhotosDestination": "Фотографии", "demoSharedXAxisCoursePageSubtitle": "Категориите во пакет се појавуваат како групи во вашата активност. Секогаш можете да го промените ова подоцна.", "demoFadeThroughDescription": "Шемата на избледување низ сите се користи за транзиции меѓу елементи на корисничкиот интерфејс што не се цврсто поврзани.", "demoFadeThroughTitle": "Избледување низ сите", "demoSharedZAxisHelpSettingLabel": "Помош", "demoMotionSubtitle": "Сите однапред дефинирани шеми на транзиција", "demoSharedZAxisNotificationSettingLabel": "Известувања", "demoSharedZAxisProfileSettingLabel": "Профил", "demoSharedZAxisSavedRecipesListTitle": "Зачувани рецепти", "demoSharedZAxisBeefSandwichRecipeDescription": "Рецепт за сендвич со телешко", "demoSharedZAxisCrabPlateRecipeDescription": "Рецепт за порција рак", "demoSharedXAxisCoursePageTitle": "Насочете ги вашите курсеви", "demoSharedZAxisCrabPlateRecipeTitle": "Рак", "demoSharedZAxisShrimpPlateRecipeDescription": "Рецепт за порција ракчиња", "demoSharedZAxisShrimpPlateRecipeTitle": "Ракчиња", "demoContainerTransformTypeFadeThrough": "ИЗБЛЕДУВАЊЕ НИЗ СИТЕ", "demoSharedZAxisDessertRecipeTitle": "Десерт", "demoSharedZAxisSandwichRecipeDescription": "Рецепт за сендвич", "demoSharedZAxisSandwichRecipeTitle": "Сендвич", "demoSharedZAxisBurgerRecipeDescription": "Рецепт за хамбургер", "demoSharedZAxisBurgerRecipeTitle": "Хамбургер", "demoSharedZAxisSettingsPageTitle": "Поставки", "demoSharedZAxisTitle": "Споделена z-оска", "demoSharedZAxisPrivacySettingLabel": "Приватност", "demoMotionTitle": "Движење", "demoContainerTransformTitle": "Трансформирање контејнер", "demoContainerTransformDescription": "Шемата за траснформирање контајнер е дизајнирана за транзиции меѓу елементи на корисничкиот интерфејс што вклучуваат контејнер. Шемава создава видлива врска помеѓу два елемента на корисничкиот интерфејс", "demoContainerTransformModalBottomSheetTitle": "Режим на избледување", "demoContainerTransformTypeFade": "ИЗБЛЕДУВАЊЕ", "demoSharedYAxisAlbumTileDurationUnit": "мин.", "demoMotionPlaceholderTitle": "Наслов", "demoSharedXAxisForgotEmailButtonText": "ЈА ЗАБОРАВИВТЕ ЛИ Е-ПОШТАТА?", "demoMotionSmallPlaceholderSubtitle": "Секундарен", "demoMotionDetailsPageTitle": "Страница со детали", "demoMotionListTileTitle": "Ставка во список", "demoSharedAxisDescription": "Шемата на споделена оска се користи за транзиции меѓу елементи на корисничкиот интерфејс што имаат просторна или навигациска врска. Шемава користи споделена трансформација на оските x, y или z за да ја засили врската помеѓу елементите.", "demoSharedXAxisTitle": "Споделена x-оска", "demoSharedXAxisBackButtonText": "НАЗАД", "demoSharedXAxisNextButtonText": "СЛЕДНО", "demoSharedXAxisCulinaryCourseTitle": "Кулинарство", "githubRepo": "Складиште на GitHub {repoName}", "fortnightlyMenuUS": "САД", "fortnightlyMenuBusiness": "Бизнис", "fortnightlyMenuScience": "Наука", "fortnightlyMenuSports": "Спорт", "fortnightlyMenuTravel": "Патувања", "fortnightlyMenuCulture": "Култура", "fortnightlyTrendingTechDesign": "TechDesign", "rallyBudgetDetailAmountLeft": "Преостанат износ", "fortnightlyHeadlineArmy": "Реформирање на зелената армија однатре", "fortnightlyDescription": "Апликација за вести фокусирана на содржини", "rallyBillDetailAmountDue": "Износ за наплата", "rallyBudgetDetailTotalCap": "Вкупно", "rallyBudgetDetailAmountUsed": "Искористен износ", "fortnightlyTrendingHealthcareRevolution": "HealthcareRevolution", "fortnightlyMenuFrontPage": "Насловна страница", "fortnightlyMenuWorld": "Свет", "rallyBillDetailAmountPaid": "Платен износ", "fortnightlyMenuPolitics": "Политика", "fortnightlyHeadlineBees": "Недостаток на пчели за фармите", "fortnightlyHeadlineGasoline": "Иднината на бензинот", "fortnightlyTrendingGreenArmy": "GreenArmy", "fortnightlyHeadlineFeminists": "Феминистките напаѓаат во политиката", "fortnightlyHeadlineFabrics": "Дизајнерите ја користат технологијата за да изработат футуристички платна", "fortnightlyHeadlineStocks": "Со стагнирањето на акциите, многумина се вртат кон валутата", "fortnightlyTrendingReform": "Reform", "fortnightlyMenuTech": "Техника", "fortnightlyHeadlineWar": "Разделени животи на Американците за време на војната", "fortnightlyHeadlineHealthcare": "Тивката, но моќна револуција во здравството", "fortnightlyLatestUpdates": "Најнови вести", "fortnightlyTrendingStocks": "Stocks", "rallyBillDetailTotalAmount": "Вкупен износ", "demoCupertinoPickerDateTime": "Датум и време", "signIn": "НАЈАВИ СЕ", "dataTableRowWithSugar": "{value} со шеќер", "dataTableRowApplePie": "Пита со јаболка", "dataTableRowDonut": "Крофна", "dataTableRowHoneycomb": "Саќе", "dataTableRowLollipop": "Лижавче", "dataTableRowJellyBean": "Желе-бонбонче", "dataTableRowGingerbread": "Колачиња со ѓумбир", "dataTableRowCupcake": "Тортичка", "dataTableRowEclair": "Еклер", "dataTableRowIceCreamSandwich": "Сендвич-сладолед", "dataTableRowFrozenYogurt": "Замрзнат јогурт", "dataTableColumnIron": "Железо (%)", "dataTableColumnCalcium": "Калциум (%)", "dataTableColumnSodium": "Натриум (мг)", "demoTimePickerTitle": "Избирач на време", "demo2dTransformationsResetTooltip": "Ресетирајте ги трансформациите", "dataTableColumnFat": "Масти (гр.)", "dataTableColumnCalories": "Калории", "dataTableColumnDessert": "Десерт (1 порција)", "cardsDemoTravelDestinationLocation1": "Танџавур, Тамил Наду", "demoTimePickerDescription": "Прикажува дијалог што содржи избирач на време во Material Design.", "demoPickersShowPicker": "ПРИКАЖИ ИЗБИРАЧ", "demoTabsScrollingTitle": "Лизгање", "demoTabsNonScrollingTitle": "Без лизгање", "craneHours": "{hours,plural,=1{1 ч.}other{{hours} ч.}}", "craneMinutes": "{minutes,plural,=1{1 м.}other{{minutes} м.}}", "craneFlightDuration": "{hoursShortForm} {minutesShortForm}", "dataTableHeader": "Исхрана", "demoDatePickerTitle": "Избирач на датум", "demoPickersSubtitle": "Избор на датум и време", "demoPickersTitle": "Избирачи", "demo2dTransformationsEditTooltip": "Изменете го насловот", "demoDataTableDescription": "Табелите со податоци прикажуваат податоци во формат во вид на мрежа од редови и колони. Тие ги организираат податоците да бидат лесни за скенирање, така што корисниците може да бараат шеми и увид.", "demo2dTransformationsDescription": "Допрете за да изменувате наслови и да користите движења за движење низ сцената. Повлечете за движење, штипнете за зумирање, ротирајте со два прста. Притиснете го копчето за ресетирање за да се вратите на стартната ориентација.", "demo2dTransformationsSubtitle": "Движење, зумирање, ротирање", "demo2dTransformationsTitle": "2D-трансформации", "demoCupertinoTextFieldPIN": "PIN", "demoCupertinoTextFieldDescription": "Полето за текст му овозможува на корисникот внесување текст или со хардверска тастатура или со тастатура на екран.", "demoCupertinoTextFieldSubtitle": "Полиња за текст во iOS-стил", "demoCupertinoTextFieldTitle": "Полиња за текст", "demoDatePickerDescription": "Прикажува дијалог што содржи избирач на датум во Material Design.", "demoCupertinoPickerTime": "Време", "demoCupertinoPickerDate": "Датум", "demoCupertinoPickerTimer": "Тајмер", "demoCupertinoPickerDescription": "Виџет за избор во iOS-стил што може да се користи за избирање низи, датуми, времиња или датум и време заедно.", "demoCupertinoPickerSubtitle": "Виџети за избор во iOS-стил", "demoCupertinoPickerTitle": "Избирачи", "dataTableRowWithHoney": "{value} со мед", "cardsDemoTravelDestinationCity2": "Четинад", "bannerDemoResetText": "Ресетирај го рекламниот натпис", "bannerDemoMultipleText": "Повеќе дејства", "bannerDemoLeadingText": "Икона на почетокот", "dismiss": "ОТФРЛИ", "cardsDemoTappable": "Може да се допре", "cardsDemoSelectable": "Може да се избере (со долго притискање)", "cardsDemoExplore": "Истражете", "cardsDemoExploreSemantics": "Истражете го местото {destinationName}", "cardsDemoShareSemantics": "Споделете го местото {destinationName}", "cardsDemoTravelDestinationTitle1": "10 најдобри града што може да ги посетите во Тамил Наду", "cardsDemoTravelDestinationDescription1": "Број 10", "cardsDemoTravelDestinationCity1": "Танџавур", "dataTableColumnProtein": "Протеини (гр.)", "cardsDemoTravelDestinationTitle2": "Занаетчии од јужна Индија", "cardsDemoTravelDestinationDescription2": "Предачи на свила", "bannerDemoText": "Лозинката беше ажурирана на другиот уред. Најавете се повторно.", "cardsDemoTravelDestinationLocation2": "Сиваганга, Тамил Наду", "cardsDemoTravelDestinationTitle3": "Храмот Брихадисвара", "cardsDemoTravelDestinationDescription3": "Храмови", "demoBannerTitle": "Рекламен натпис", "demoBannerSubtitle": "Се прикажува рекламен натпис во список", "demoBannerDescription": "Рекламниот натпис прикажува важна, концизна порака и им обезбедува на корисниците дејства за извршување (или отфрлање на натписот). За да се отфрли, потребно е дејство на корисникот.", "demoCardTitle": "Картички", "demoCardSubtitle": "Основни картички со заоблени агли", "demoCardDescription": "Картичката е лист од материјал што се користи за прикажување поврзани податоци како, на пр., албум, географска локација, оброк, детали за контакт итн.", "demoDataTableTitle": "Табели со податоци", "demoDataTableSubtitle": "Редови и колони со податоци", "dataTableColumnCarbs": "Јаглехидрати (гр.)", "placeTanjore": "Танџавур", "demoGridListsTitle": "Списоци на табела", "placeFlowerMarket": "Цветен пазар", "placeBronzeWorks": "Бронзени изработки", "placeMarket": "Пазар", "placeThanjavurTemple": "Храм во Танџавур", "placeSaltFarm": "Фарма за сол", "placeScooters": "Скутери", "placeSilkMaker": "Пазар за свила", "placeLunchPrep": "Подготовка за ручек", "placeBeach": "Плажа", "placeFisherman": "Рибар", "demoMenuSelected": "Избрано: {value}", "demoMenuRemove": "Отстрани", "demoMenuGetLink": "Добијте линк", "demoMenuShare": "Сподели", "demoBottomAppBarSubtitle": "Прикажува навигација и дејства во долниот дел", "demoMenuAnItemWithASectionedMenu": "Ставка со мени со секции", "demoMenuADisabledMenuItem": "Оневозможена ставка на менито", "demoLinearProgressIndicatorTitle": "Линиски индикатор на напредок", "demoMenuContextMenuItemOne": "Прва ставка на контекстуално мени", "demoMenuAnItemWithASimpleMenu": "Ставка со едноставно мени", "demoCustomSlidersTitle": "Лизгачи за приспособување", "demoMenuAnItemWithAChecklistMenu": "Ставка со мени со список за проверка", "demoCupertinoActivityIndicatorTitle": "Индикатор на активност", "demoCupertinoActivityIndicatorSubtitle": "Индикатори на активност во iOS-стил", "demoCupertinoActivityIndicatorDescription": "Индикатор на активност во iOS-стил што се врати во насока на стрелките на часовникот.", "demoCupertinoNavigationBarTitle": "Лента за навигација", "demoCupertinoNavigationBarSubtitle": "Лента за навигација во iOS-стил", "demoCupertinoNavigationBarDescription": "Лента за навигација во iOS-стил. Лентата за навигација е алатник, што содржи најмалку наслов на страницата, во средина на алатникот.", "demoCupertinoPullToRefreshTitle": "Повлечете за освежување", "demoCupertinoPullToRefreshSubtitle": "Контрола „Повлечете за освежување“ во iOS-стил", "demoCupertinoPullToRefreshDescription": "Виџет што ја користи контролата на содржини „Повлечете за освежување“ во iOS-стил.", "demoProgressIndicatorTitle": "Индикатори на напредок", "demoProgressIndicatorSubtitle": "Линиски, кружни, неодредени", "demoCircularProgressIndicatorTitle": "Кружен индикатор на напредок", "demoCircularProgressIndicatorDescription": "Кружен индикатор на напредок во Material Design, којшто се врти за да покаже дека апликацијата работи.", "demoMenuFour": "Четири", "demoLinearProgressIndicatorDescription": "Линиски индикатор на напредок во Material Design, познат и како лента за напредок.", "demoTooltipTitle": "Совети за алатки", "demoTooltipSubtitle": "Кратка порака што се прикажува при долго притискање или местење на глушецот над елементот", "demoTooltipDescription": "Советите за алатки даваат текстуални етикети што ја објаснуваат функцијата на копчето или на друго дејство на корисничкиот интерфејс. Советите за алатки прикажуваат информативен текст кога корисниците ќе го наместат глушецот над елемент, ќе фокусираат или долго ќе притиснат некој елемент.", "demoTooltipInstructions": "Долго притиснете или наместете го глушецот над елемент за да се прикаже совет за алатката.", "placeChennai": "Ченај", "demoMenuChecked": "Штиклирано: {value}", "placeChettinad": "Четинад", "demoMenuPreview": "Преглед", "demoBottomAppBarTitle": "Долна лента со апликации", "demoBottomAppBarDescription": "Долните ленти со апликации обезбедуваат пристап до една долна фиока за навигација и најмногу четири дејства, вклучувајќи го и лебдечкото копче за дејство.", "bottomAppBarNotch": "Исечок", "bottomAppBarPosition": "Позиција на лебдечкото копче за дејство", "bottomAppBarPositionDockedEnd": "Сокриено - на крај", "bottomAppBarPositionDockedCenter": "Сокриено - на средина", "bottomAppBarPositionFloatingEnd": "Лебдечко - на крај", "bottomAppBarPositionFloatingCenter": "Лебдечко - на средина", "demoSlidersEditableNumericalValue": "Нумеричка вредност што може да се изменува", "demoGridListsSubtitle": "Распоред на редови и колони", "demoGridListsDescription": "„Списоците на табела“ се најпогодни за прикажување хомогени податоци, најчесто слики. Секој елемент во списокот на табелата се вика плочка.", "demoGridListsImageOnlyTitle": "Само слика", "demoGridListsHeaderTitle": "Со заглавие", "demoGridListsFooterTitle": "Со подножје", "demoSlidersTitle": "Лизгачи", "demoSlidersSubtitle": "Виџети за избор на вредност со повлекување", "demoSlidersDescription": "Лизгачите прикажуваат голем број вредности на лента, а корисниците може да изберат една од нив. Идеални се за приспособување на поставките, како што се јачината на звукот, осветленоста или примената на филтри за слики.", "demoRangeSlidersTitle": "Лизгачи на опсег", "demoRangeSlidersDescription": "Лизгачите прикажуваат голем број вредности на лента. Може да имаат икони на двата краја на лентата со опсег на вредности. Идеални се за приспособување на поставките, како што се јачината на звукот, осветленоста или примената на филтри за слики.", "demoMenuAnItemWithAContextMenuButton": "Ставка со контекстуално мени", "demoCustomSlidersDescription": "Лизгачите прикажуваат голем број вредности на лента, а корисниците може да изберат една од тие вредности. Може да бидат со теми и приспособени.", "demoSlidersContinuousWithEditableNumericalValue": "Континуиран со нумеричка вредност што може да се изменува", "demoSlidersDiscrete": "Дискретен", "demoSlidersDiscreteSliderWithCustomTheme": "Дискретен лизгач со приспособена тема", "demoSlidersContinuousRangeSliderWithCustomTheme": "Континуиран лизгач на опсег со приспособена тема", "demoSlidersContinuous": "Континуиран", "placePondicherry": "Пудучери", "demoMenuTitle": "Мени", "demoContextMenuTitle": "Контекстуално мени", "demoSectionedMenuTitle": "Мени со секции", "demoSimpleMenuTitle": "Едноставно мени", "demoChecklistMenuTitle": "Мени со список за проверка", "demoMenuSubtitle": "Копчиња на мени и едноставни менија", "demoMenuDescription": "Менито прикажува список со избори на привремена површина. Тие се појавуваат кога корисникот ќе користи копче, дејство или друга контрола.", "demoMenuItemValueOne": "Прва ставка од менито", "demoMenuItemValueTwo": "Втора ставка од менито", "demoMenuItemValueThree": "Трета ставка од менито", "demoMenuOne": "Еден", "demoMenuTwo": "Два", "demoMenuThree": "Три", "demoMenuContextMenuItemThree": "Трета ставка на контекстуално мени", "demoCupertinoSwitchSubtitle": "Прекинувач во iOS-стил", "demoSnackbarsText": "Ова е снекбар-порака.", "demoCupertinoSliderSubtitle": "Лизгач во iOS-стил", "demoCupertinoSliderDescription": "Лизгачот може да се користи за избор од континуиран или дискретен збир на вредности.", "demoCupertinoSliderContinuous": "Континуиран: {value}", "demoCupertinoSliderDiscrete": "Дискретен: {value}", "demoSnackbarsAction": "Го притиснавте копчето за дејство на снекбар-пораката.", "backToGallery": "Назад во галеријата", "demoCupertinoTabBarTitle": "Лента со картички", "demoCupertinoSwitchDescription": "Прекинувачот се користи за менување на состојбата вклучено/исклучено на една поставка.", "demoSnackbarsActionButtonLabel": "ДЕЈСТВО", "cupertinoTabBarProfileTab": "Профил", "demoSnackbarsButtonLabel": "ПРИКАЖИ СНЕКБАР-ПОРАКА", "demoSnackbarsDescription": "Снекбар-пораките ги информираат корисниците дека некоја апликација извршила или ќе изврши некаков процес. Тие се појавуваат привремено, кон дното на екранот. Не треба да го прекинуваат корисникот и не бараат од него да внесе податоци за да исчезнат.", "demoSnackbarsSubtitle": "Снекбар-пораките се прикажуваат на дното на екранот", "demoSnackbarsTitle": "Снекбар-пораки", "demoCupertinoSliderTitle": "Лизгач", "cupertinoTabBarChatTab": "Разговор", "cupertinoTabBarHomeTab": "Почетна страница", "demoCupertinoTabBarDescription": "Долна лента за навигација со картички во iOS-стил. Прикажува повеќе картички, од коишто првата прикажана стандардно е активна.", "demoCupertinoTabBarSubtitle": "Долна лента со картички во iOS-стил", "demoOptionsFeatureTitle": "Прикажи ги опциите", "demoOptionsFeatureDescription": "Допрете тука за да се прикажат достапните опции за оваа демонстрација.", "demoCodeViewerCopyAll": "КОПИРАЈ ГИ СИТЕ", "shrineScreenReaderRemoveProductButton": "Отстранете {product}", "shrineScreenReaderProductAddToCart": "Додајте во кошничката", "shrineScreenReaderCart": "{quantity,plural,=0{Кошничка за купување, нема ставки}=1{Кошничка за купување, 1 ставка}other{Кошничка за купување, {quantity} ставки}}", "demoCodeViewerFailedToCopyToClipboardMessage": "Не успеа да се копира во привремената меморија: {error}", "demoCodeViewerCopiedToClipboardMessage": "Копирано во привремената меморија.", "craneSleep8SemanticLabel": "Урнатини на Маите на карпа над плажа", "craneSleep4SemanticLabel": "Хотел крај езеро пред планини", "craneSleep2SemanticLabel": "Тврдината Мачу Пикчу", "craneSleep1SemanticLabel": "Вила во снежен пејзаж со зимзелени дрва", "craneSleep0SemanticLabel": "Надводни бунгалови", "craneFly13SemanticLabel": "Базен крај море со палми", "craneFly12SemanticLabel": "Базен со палми", "craneFly11SemanticLabel": "Светилник од тули на море", "craneFly10SemanticLabel": "Минарињата на џамијата Ал-Азар на зајдисонце", "craneFly9SemanticLabel": "Маж се потпира на старински син автомобил", "craneFly8SemanticLabel": "Градина со супердрва", "craneEat9SemanticLabel": "Шанк во кафуле со печива", "craneEat2SemanticLabel": "Хамбургер", "craneFly5SemanticLabel": "Хотел крај езеро пред планини", "demoSelectionControlsSubtitle": "Полиња за избор, тркалезни копчиња и прекинувачи", "craneEat10SemanticLabel": "Жена држи огромен сендвич со пастрма", "craneFly4SemanticLabel": "Надводни бунгалови", "craneEat7SemanticLabel": "Влез на пекарница", "craneEat6SemanticLabel": "Порција ракчиња", "craneEat5SemanticLabel": "Простор за седење во ресторан со уметничка атмосфера", "craneEat4SemanticLabel": "Чоколаден десерт", "craneEat3SemanticLabel": "Корејско тако", "craneFly3SemanticLabel": "Тврдината Мачу Пикчу", "craneEat1SemanticLabel": "Празен шанк со столици во стилот на американските ресторани", "craneEat0SemanticLabel": "Пица во фурна на дрва", "craneSleep11SemanticLabel": "Облакодерот Тајпеј 101", "craneSleep10SemanticLabel": "Минарињата на џамијата Ал-Азар на зајдисонце", "craneSleep9SemanticLabel": "Светилник од тули на море", "craneEat8SemanticLabel": "Чинија со ракови", "craneSleep7SemanticLabel": "Живописни апартмани на плоштадот Рибеира", "craneSleep6SemanticLabel": "Базен со палми", "craneSleep5SemanticLabel": "Шатор на поле", "settingsButtonCloseLabel": "Затвори ги поставките", "demoSelectionControlsCheckboxDescription": "Полињата за избор му овозможуваат на корисникот да избере повеќе опции од еден збир. Вредноста на обичното поле за избор е „точно“ или „неточно“, а вредноста на полето со три избори може да биде и нула.", "settingsButtonLabel": "Поставки", "demoListsTitle": "Списоци", "demoListsSubtitle": "Распореди на подвижен список", "demoListsDescription": "Еден ред со фиксна висина што обично содржи текст, како и икона на почетокот или на крајот.", "demoOneLineListsTitle": "Една линија", "demoTwoLineListsTitle": "Две линии", "demoListsSecondary": "Секундарен текст", "demoSelectionControlsTitle": "Контроли за избор", "craneFly7SemanticLabel": "Маунт Рашмор", "demoSelectionControlsCheckboxTitle": "Поле за избор", "craneSleep3SemanticLabel": "Маж се потпира на старински син автомобил", "demoSelectionControlsRadioTitle": "Тркалезно копче", "demoSelectionControlsRadioDescription": "Тркалезните копчиња му овозможуваат на корисникот да избере една опција од збир опции. Користете ги за исклучителен избор доколку мислите дека корисникот треба да ги види сите достапни опции една до друга.", "demoSelectionControlsSwitchTitle": "Прекинувач", "demoSelectionControlsSwitchDescription": "Прекинувачите за вклучување/исклучување ја менуваат состојбата на опција со една поставка. Опцијата што прекинувачот ја контролира, како и нејзината состојба, треба да е јасно одредена со соодветна етикета.", "craneFly0SemanticLabel": "Вила во снежен пејзаж со зимзелени дрва", "craneFly1SemanticLabel": "Шатор на поле", "craneFly2SemanticLabel": "Молитвени знамиња пред снежна планина", "craneFly6SemanticLabel": "Поглед одозгора на Палатата на ликовни уметности", "rallySeeAllAccounts": "Прикажи ги сите сметки", "rallyBillAmount": "{billName} треба да се плати до {date} и изнесува {amount}.", "shrineTooltipCloseCart": "Затворете ја кошничката", "shrineTooltipCloseMenu": "Затворете го менито", "shrineTooltipOpenMenu": "Отворете го менито", "shrineTooltipSettings": "Поставки", "shrineTooltipSearch": "Пребарај", "demoTabsDescription": "Картичките ги организираат содржините на различни екрани, збирови податоци и други интеракции.", "demoTabsSubtitle": "Картички со прикази што се лизгаат неазависно еден од друг", "demoTabsTitle": "Картички", "rallyBudgetAmount": "{budgetName} буџет со искористени {amountUsed} од {amountTotal}, преостануваат {amountLeft}", "shrineTooltipRemoveItem": "Отстрани ја ставката", "rallyAccountAmount": "{accountName} сметка {accountNumber} со {amount}.", "rallySeeAllBudgets": "Прикажи ги сите буџети", "rallySeeAllBills": "Прикажи ги сите сметки", "craneFormDate": "Изберете датум", "craneFormOrigin": "Изберете место на поаѓање", "craneFly2": "Долина Кумбу, Непал", "craneFly3": "Мачу Пикчу, Перу", "craneFly4": "Мале, Малдиви", "craneFly5": "Вицнау, Швјцарија", "craneFly6": "Мексико Сити, Мексико", "craneFly7": "Маунт Рашмор, САД", "settingsTextDirectionLocaleBased": "Според локација", "craneFly9": "Хавана, Куба", "craneFly10": "Каиро, Египет", "craneFly11": "Лисабон, Португалија", "craneFly12": "Напа, САД", "craneFly13": "Бали, Индонезија", "craneSleep0": "Мале, Малдиви", "craneSleep1": "Аспен, САД", "craneSleep2": "Мачу Пикчу, Перу", "demoCupertinoSegmentedControlTitle": "Сегментирана контрола", "craneSleep4": "Вицнау, Швјцарија", "craneSleep5": "Биг Сур, САД", "craneSleep6": "Напа, САД", "craneSleep7": "Порто, Португалија", "craneSleep8": "Тулум, Мексико", "craneEat5": "Сеул, Јужна Кореја", "demoChipTitle": "Икони", "demoChipSubtitle": "Компактни елементи што претставуваат внес, атрибут или дејство", "demoActionChipTitle": "Икона за дејство", "demoActionChipDescription": "Иконите за дејства се збир на опции коишто активираат дејство поврзано со примарните содржини. Иконите за дејства треба да се појавуваат динамично и контекстуално во корисничкиот интерфејс.", "demoChoiceChipTitle": "Икона за избор", "demoChoiceChipDescription": "Иконите за избор прикажуваат еден избор од збир избори. Иконите за избор содржат поврзан описен текст или категории.", "demoFilterChipTitle": "Икона за филтер", "demoFilterChipDescription": "Иконите за филтри користат ознаки или описни зборови за филтрирање содржини.", "demoInputChipTitle": "Икона за внесување", "demoInputChipDescription": "Иконите за внесување прикажуваат сложени податоци, како што се ентитет (лице, место или предмет) или разговорен текст во компактна форма.", "craneSleep9": "Лисабон, Португалија", "craneEat10": "Лисабон, Португалија", "demoCupertinoSegmentedControlDescription": "Се користи за избирање помеѓу број на самостојни опции. Кога ќе се избере една опција во сегментираната контрола, ќе се поништи изборот на другите опции.", "chipTurnOnLights": "Вклучете ги светлата", "chipSmall": "Мал", "chipMedium": "Среден", "chipLarge": "Голем", "chipElevator": "Лифт", "chipWasher": "Машина за перење алишта", "chipFireplace": "Камин", "chipBiking": "Возење велосипед", "craneFormDiners": "Ресторани во американски стил", "rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Зголемете го потенцијалното одбивање данок! Назначете категории на 1 неназначена трансакција.}other{Зголемете го потенцијалното одбивање данок! Назначете категории на {count} неназначени трансакции.}}", "craneFormTime": "Изберете време", "craneFormLocation": "Изберете локација", "craneFormTravelers": "Патници", "craneEat8": "Атланта, САД", "craneFormDestination": "Изберете дестинација", "craneFormDates": "Изберете датуми", "craneFly": "ЛЕТАЊЕ", "craneSleep": "СПИЕЊЕ", "craneEat": "ЈАДЕЊЕ", "craneFlySubhead": "Истражувајте летови по дестинација", "craneSleepSubhead": "Истражувајте сместувања по дестинација", "craneEatSubhead": "Истражувајте ресторани по дестинација", "craneFlyStops": "{numberOfStops,plural,=0{Директен}=1{1 застанување}other{{numberOfStops} застанувања}}", "craneSleepProperties": "{totalProperties,plural,=0{Нема достапни сместувања}=1{1 достапно сместување}other{{totalProperties} достапни сместувања}}", "craneEatRestaurants": "{totalRestaurants,plural,=0{Нема ресторани}=1{1 ресторан}other{{totalRestaurants} ресторани}}", "craneFly0": "Аспен, САД", "demoCupertinoSegmentedControlSubtitle": "Сегментирана контрола во iOS-стил", "craneSleep10": "Каиро, Египет", "craneEat9": "Мадрид, Шпанија", "craneFly1": "Биг Сур, САД", "craneEat7": "Нешвил, САД", "craneEat6": "Сиетл, САД", "craneFly8": "Сингапур", "craneEat4": "Париз, Франција", "craneEat3": "Портланд, САД", "craneEat2": "Кордоба, Аргентина", "craneEat1": "Далас, САД", "craneEat0": "Неапол, Италија", "craneSleep11": "Тајпеј, Тајван", "craneSleep3": "Хавана, Куба", "shrineLogoutButtonCaption": "ОДЈАВЕТЕ СЕ", "rallyTitleBills": "СМЕТКИ", "rallyTitleAccounts": "СМЕТКИ", "shrineProductVagabondSack": "Ранец Vagabond", "rallyAccountDetailDataInterestYtd": "Годишна камата до денес", "shrineProductWhitneyBelt": "Ремен Whitney", "shrineProductGardenStrand": "Орнамент за во градина", "shrineProductStrutEarrings": "Обетки Strut", "shrineProductVarsitySocks": "Чорапи Varsity", "shrineProductWeaveKeyring": "Привезок за клучеви Weave", "shrineProductGatsbyHat": "Капа Gatsby", "shrineProductShrugBag": "Чанта Shrug", "shrineProductGiltDeskTrio": "Три масички Gilt", "shrineProductCopperWireRack": "Полица од бакарна жица", "shrineProductSootheCeramicSet": "Керамички сет Soothe", "shrineProductHurrahsTeaSet": "Сет за чај Hurrahs", "shrineProductBlueStoneMug": "Сина камена шолја", "shrineProductRainwaterTray": "Послужавник Rainwater", "shrineProductChambrayNapkins": "Салфети Chambray", "shrineProductSucculentPlanters": "Саксии за сукуленти", "shrineProductQuartetTable": "Маса Quartet", "shrineProductKitchenQuattro": "Кујнски сет од 4 парчиња", "shrineProductClaySweater": "Џемпер Clay", "shrineProductSeaTunic": "Туника во морски тонови", "shrineProductPlasterTunic": "Туника Plaster", "rallyBudgetCategoryRestaurants": "Ресторани", "shrineProductChambrayShirt": "Kошула Chambray", "shrineProductSeabreezeSweater": "Џемпер Seabreeze", "shrineProductGentryJacket": "Јакна Gentry", "shrineProductNavyTrousers": "Панталони во морско сина", "shrineProductWalterHenleyWhite": "Walter Henley (бела)", "shrineProductSurfAndPerfShirt": "Маица Surf and perf", "shrineProductGingerScarf": "Шал во боја на ѓумбир", "shrineProductRamonaCrossover": "Женска блуза Ramona", "shrineProductClassicWhiteCollar": "Класична бела јака", "shrineProductSunshirtDress": "Фустан за на плажа", "rallyAccountDetailDataInterestRate": "Каматна стапка", "rallyAccountDetailDataAnnualPercentageYield": "Годишен принос во процент", "rallyAccountDataVacation": "Одмор", "shrineProductFineLinesTee": "Маица Fine lines", "rallyAccountDataHomeSavings": "Штедна сметка за домот", "rallyAccountDataChecking": "Тековна сметка", "rallyAccountDetailDataInterestPaidLastYear": "Камата платена минатата година", "rallyAccountDetailDataNextStatement": "Следниот извод", "rallyAccountDetailDataAccountOwner": "Сопственик на сметка", "rallyBudgetCategoryCoffeeShops": "Кафе-барови", "rallyBudgetCategoryGroceries": "Намирници", "shrineProductCeriseScallopTee": "Порабена маица Cerise", "rallyBudgetCategoryClothing": "Облека", "rallySettingsManageAccounts": "Управувајте со сметките", "rallyAccountDataCarSavings": "Штедна сметка за автомобилот", "rallySettingsTaxDocuments": "Даночни документи", "rallySettingsPasscodeAndTouchId": "Лозинка и ID на допир", "rallySettingsNotifications": "Известувања", "rallySettingsPersonalInformation": "Лични податоци", "rallySettingsPaperlessSettings": "Поставки за пошта без хартија", "rallySettingsFindAtms": "Најдете банкомати", "rallySettingsHelp": "Помош", "rallySettingsSignOut": "Одјавете се", "rallyAccountTotal": "Вкупно", "rallyBillsDue": "Краен рок", "rallyBudgetLeft": "Преостанато", "rallyAccounts": "Сметки", "rallyBills": "Сметки", "rallyBudgets": "Буџети", "rallyAlerts": "Предупредувања", "rallySeeAll": "ПРИКАЖИ СЀ", "rallyFinanceLeft": "ПРЕОСТАНАТО", "rallyTitleOverview": "ПРЕГЛЕД", "shrineProductShoulderRollsTee": "Маица со спуштени ракави", "shrineNextButtonCaption": "СЛЕДНО", "rallyTitleBudgets": "БУЏЕТИ", "rallyTitleSettings": "ПОСТАВКИ", "rallyLoginLoginToRally": "Најавете се на Rally", "rallyLoginNoAccount": "Немате ли сметка?", "rallyLoginSignUp": "РЕГИСТРИРАЈТЕ СЕ", "rallyLoginUsername": "Корисничко име", "rallyLoginPassword": "Лозинка", "rallyLoginLabelLogin": "Најавете се", "rallyLoginRememberMe": "Запомни ме", "rallyLoginButtonLogin": "НАЈАВЕТЕ СЕ", "rallyAlertsMessageHeadsUpShopping": "Внимавајте, сте искористиле {percent} од буџетот за купување месецов.", "rallyAlertsMessageSpentOnRestaurants": "Потрошивте {amount} на ресторани седмицава.", "rallyAlertsMessageATMFees": "Потрошивте {amount} на провизија за банкомат месецов", "rallyAlertsMessageCheckingAccount": "Одлично! Салдото на сметката ви е {percent} поголемо од минатиот месец.", "shrineMenuCaption": "МЕНИ", "shrineCategoryNameAll": "СИТЕ", "shrineCategoryNameAccessories": "ДОДАТОЦИ", "shrineCategoryNameClothing": "ОБЛЕКА", "shrineCategoryNameHome": "ДОМАЌИНСТВО", "shrineLoginUsernameLabel": "Корисничко име", "shrineLoginPasswordLabel": "Лозинка", "shrineCancelButtonCaption": "ОТКАЖИ", "shrineCartTaxCaption": "Данок:", "shrineCartPageCaption": "КОШНИЧКА", "shrineProductQuantity": "Количина: {quantity}", "shrineProductPrice": "x {price}", "shrineCartItemCount": "{quantity,plural,=0{НЕМА СТАВКИ}=1{1 СТАВКА}other{{quantity} СТАВКИ}}", "shrineCartClearButtonCaption": "ИСПРАЗНИ КОШНИЧКА", "shrineCartTotalCaption": "ВКУПНО", "shrineCartSubtotalCaption": "Подзбир:", "shrineCartShippingCaption": "Испорака:", "shrineProductGreySlouchTank": "Сива маица без ракави", "shrineProductStellaSunglasses": "Очила за сонце Stella", "shrineProductWhitePinstripeShirt": "Бела кошула со риги", "demoTextFieldWhereCanWeReachYou": "Како може да стапиме во контакт со вас?", "settingsTextDirectionLTR": "Лево кон десно", "settingsTextScalingLarge": "Голем", "demoBottomSheetHeader": "Заглавие", "demoBottomSheetItem": "Ставка {value}", "demoBottomTextFieldsTitle": "Полиња за текст", "demoTextFieldTitle": "Полиња за текст", "demoTextFieldSubtitle": "Еден ред текст и броеви што може да се изменуваат", "demoTextFieldDescription": "Полињата за текст им овозможуваат на корисниците да внесуваат текст во корисничкиот интерфејс. Обично се појавуваат во формулари и дијалози.", "demoTextFieldShowPasswordLabel": "Прикажи ја лозинката", "demoTextFieldHidePasswordLabel": "Сокријте ја лозинката", "demoTextFieldFormErrors": "Поправете ги грешките означени со црвено пред да испратите.", "demoTextFieldNameRequired": "Потребно е име.", "demoTextFieldOnlyAlphabeticalChars": "Внесете само букви.", "demoTextFieldEnterUSPhoneNumber": "(###) ###-#### - Внесете телефонски број од САД.", "demoTextFieldEnterPassword": "Внесете лозинка.", "demoTextFieldPasswordsDoNotMatch": "Лозинките не се совпаѓаат", "demoTextFieldWhatDoPeopleCallYou": "Како ви се обраќаат луѓето?", "demoTextFieldNameField": "Име*", "demoBottomSheetButtonText": "ПРИКАЖИ ДОЛЕН ЛИСТ", "demoTextFieldPhoneNumber": "Телефонски број*", "demoBottomSheetTitle": "Долен лист", "demoTextFieldEmail": "Е-пошта", "demoTextFieldTellUsAboutYourself": "Кажете ни нешто за вас (на пр., напишете што работите или со кое хоби се занимавате)", "demoTextFieldKeepItShort": "Нека биде кратко, ова е само пример.", "starterAppGenericButton": "КОПЧЕ", "demoTextFieldLifeStory": "Животна приказна", "demoTextFieldSalary": "Плата", "demoTextFieldUSD": "USD", "demoTextFieldNoMoreThan": "Не повеќе од 8 знаци.", "demoTextFieldPassword": "Лозинка*", "demoTextFieldRetypePassword": "Повторно внесете лозинка*", "demoTextFieldSubmit": "ИСПРАТИ", "demoBottomNavigationSubtitle": "Долна навигација со напречно избледувачки прикази", "demoBottomSheetAddLabel": "Додајте", "demoBottomSheetModalDescription": "Модалниот долен лист е алтернатива за мени или дијалог и го спречува корисникот да комуницира со остатокот од апликацијата.", "demoBottomSheetModalTitle": "Модален долен лист", "demoBottomSheetPersistentDescription": "Постојаниот долен лист прикажува информации што ги дополнуваат примарните содржини на апликацијата. Постојаниот долен лист останува видлив дури и при интеракцијата на корисникот со другите делови на апликацијата.", "demoBottomSheetPersistentTitle": "Постојан долен лист", "demoBottomSheetSubtitle": "Постојан и модален долен лист", "demoTextFieldNameHasPhoneNumber": "Телефонскиот број на {name} е {phoneNumber}", "buttonText": "КОПЧЕ", "demoTypographyDescription": "Дефиниции за различните типографски стилови во Material Design.", "demoTypographySubtitle": "Сите однапред дефинирани стилови на текст", "demoTypographyTitle": "Типографија", "demoFullscreenDialogDescription": "Својството fullscreenDialog одредува дали дојдовната страница е во модален дијалог на цел екран", "demoFlatButtonDescription": "Рамното копче прикажува дамка од мастило при притискање, но не се подига. Користете рамни копчиња во алатници, во дијалози и во линија со дополнување", "demoBottomNavigationDescription": "Долните ленти за навигација прикажуваат три до пет дестинации најдолу на екранот. Секоја дестинација е прикажана со икона и со изборна текстуална етикета. Кога ќе допре долна икона за навигација, тоа го води корисникот до дестинацијата за навигација од највисоко ниво поврзана со таа икона.", "demoBottomNavigationSelectedLabel": "Избрана етикета", "demoBottomNavigationPersistentLabels": "Постојани етикети", "starterAppDrawerItem": "Ставка {value}", "demoTextFieldRequiredField": "* означува задолжително поле", "demoBottomNavigationTitle": "Долна навигација", "settingsLightTheme": "Светла", "settingsTheme": "Тема", "settingsPlatformIOS": "iOS", "settingsPlatformAndroid": "Android", "settingsTextDirectionRTL": "Десно кон лево", "settingsTextScalingHuge": "Огромен", "cupertinoButton": "Копче", "settingsTextScalingNormal": "Нормално", "settingsTextScalingSmall": "Мал", "settingsSystemDefault": "Систем", "settingsTitle": "Поставки", "rallyDescription": "Апликација за лични финансии", "aboutDialogDescription": "За да го видите изворниот код на апликацијава, одете на {repoLink}.", "bottomNavigationCommentsTab": "Коментари", "starterAppGenericBody": "Главен текст", "starterAppGenericHeadline": "Наслов", "starterAppGenericSubtitle": "Поднаслов", "starterAppGenericTitle": "Наслов", "starterAppTooltipSearch": "Пребарување", "starterAppTooltipShare": "Сподели", "starterAppTooltipFavorite": "Омилена", "starterAppTooltipAdd": "Додајте", "bottomNavigationCalendarTab": "Календар", "starterAppDescription": "Распоред што овозможува брзо стартување", "starterAppTitle": "Апликација за стартување", "aboutFlutterSamplesRepo": "Примери за Flutter од складиштето на GitHub", "bottomNavigationContentPlaceholder": "Резервирано место за картичката {title}", "bottomNavigationCameraTab": "Камера", "bottomNavigationAlarmTab": "Аларм", "bottomNavigationAccountTab": "Сметка", "demoTextFieldYourEmailAddress": "Вашата адреса на е-пошта", "demoToggleButtonDescription": "Копчињата за префрлање може да се користат за групирање поврзани опции. За да се нагласат групи на поврзани копчиња за префрлање, групата треба да споделува заеднички контејнер", "colorsGrey": "СИВА", "colorsBrown": "КАФЕАВА", "colorsDeepOrange": "ТЕМНОПОРТОКАЛОВА", "colorsOrange": "ПОРТОКАЛОВА", "colorsAmber": "КИЛИБАРНА", "colorsYellow": "ЖОЛТА", "colorsLime": "ЛИМЕТА", "colorsLightGreen": "СВЕТЛОЗЕЛЕНА", "colorsGreen": "ЗЕЛЕНА", "homeHeaderGallery": "Галерија", "homeHeaderCategories": "Категории", "shrineDescription": "Модерна апликација за малопродажба", "craneDescription": "Персонализирана апликација за патување", "homeCategoryReference": "СТИЛОВИ И ДРУГО", "demoInvalidURL": "URL-адресата не може да се прикаже:", "demoOptionsTooltip": "Опции", "demoInfoTooltip": "Информации", "demoCodeTooltip": "Код за демонстрација", "demoDocumentationTooltip": "Документација за API", "demoFullscreenTooltip": "Цел екран", "settingsTextScaling": "Скалирање текст", "settingsTextDirection": "Насока на текстот", "settingsLocale": "Локален стандард", "settingsPlatformMechanics": "Механика на платформа", "settingsDarkTheme": "Темна", "settingsSlowMotion": "Бавно движење", "settingsAbout": "За Flutter Gallery", "settingsFeedback": "Испратете повратни информации", "settingsAttribution": "Дизајн на TOASTER во Лондон", "demoButtonTitle": "Копчиња", "demoButtonSubtitle": "За текст, подигнато, со контура и сл.", "demoFlatButtonTitle": "Рамно копче", "demoRaisedButtonDescription": "Подигнатите копчиња додаваат димензионалност во распоредите што се претежно рамни. Ги нагласуваат функциите во збиените или широките простори.", "demoRaisedButtonTitle": "Подигнато копче", "demoOutlineButtonTitle": "Копче со контура", "demoOutlineButtonDescription": "Копчињата со контура стануваат непроѕирни и се подигнуваат кога ќе ги притиснете. Честопати се спаруваат со подигнатите копчиња за да означат алтернативно секундарно дејство.", "demoToggleButtonTitle": "Копчиња за префрлање", "colorsTeal": "ТИРКИЗНА", "demoFloatingButtonTitle": "Лебдечко копче за дејство", "demoFloatingButtonDescription": "Лебдечкото копче за дејство е копче во вид на кружна икона што лебди над содржините за да поттикне примарно дејство во апликацијата.", "demoDialogTitle": "Дијалози", "demoDialogSubtitle": "Едноставен, за предупредување и на цел екран", "demoAlertDialogTitle": "Предупредување", "demoAlertDialogDescription": "Дијалогот за предупредување го информира корисникот за ситуациите што бараат потврда. Дијалогот за предупредување има изборен наслов и изборен список со дејства.", "demoAlertTitleDialogTitle": "Предупредување со наслов", "demoSimpleDialogTitle": "Едноставен", "demoSimpleDialogDescription": "Едноставниот дијалог му нуди на корисникот избор помеѓу неколку опции. Едноставниот дијалог има изборен наслов прикажан над опциите.", "demoFullscreenDialogTitle": "Цел екран", "demoCupertinoButtonsTitle": "Копчиња", "demoCupertinoButtonsSubtitle": "Копчиња во iOS-стил", "demoCupertinoButtonsDescription": "Копче во iOS-стил. Содржи текст и/или икона што бледее и се појавува при допир. По избор, може да има и заднина.", "demoCupertinoAlertsTitle": "Предупредувања", "demoCupertinoAlertsSubtitle": "Дијалози за предупредување во iOS-стил", "demoCupertinoAlertTitle": "Предупредување", "demoCupertinoAlertDescription": "Дијалогот за предупредување го информира корисникот за ситуациите што бараат потврда. Дијалогот за предупредување има изборен наслов, изборни содржини и изборен список со дејства. Насловот е прикажан над содржините, а дејствата се прикажани под содржините.", "demoCupertinoAlertWithTitleTitle": "Предупредување со наслов", "demoCupertinoAlertButtonsTitle": "Предупредување со копчиња", "demoCupertinoAlertButtonsOnlyTitle": "Само копчиња за предупредување", "demoCupertinoActionSheetTitle": "Лист со дејства", "demoCupertinoActionSheetDescription": "Листот со дејства е посебен стил на предупредување со кое пред корисникот се претставува група од две или повеќе опции поврзани со тековниот контекст. Листот со дејства може да има наслов, дополнителна порака и список со дејства.", "demoColorsTitle": "Бои", "demoColorsSubtitle": "Сите однапред дефинирани бои", "demoColorsDescription": "Константи за бои и мостри што ја претставуваат палетата на бои на Material Design.", "buttonTextEnabled": "ENABLED", "buttonTextDisabled": "DISABLED", "buttonTextCreate": "Создајте", "dialogSelectedOption": "Избравте: „{value}“", "dialogDiscardTitle": "Да се отфрли нацртот?", "dialogLocationTitle": "Да се користи услугата според локација на Google?", "dialogLocationDescription": "Дозволете Google да им помогне на апликациите да ја утврдуваат локацијата. Тоа подразбира испраќање анонимни податоци за локација до Google, дури и кога не се извршуваат апликации.", "dialogCancel": "ОТКАЖИ", "dialogDiscard": "ОТФРЛИ", "dialogDisagree": "НЕ СЕ СОГЛАСУВАМ", "dialogAgree": "СЕ СОГЛАСУВАМ", "dialogSetBackup": "Поставете резервна сметка", "colorsBlueGrey": "СИНОСИВА", "dialogShow": "ПРИКАЖИ ГО ДИЈАЛОГОТ", "dialogFullscreenTitle": "Дијалог на цел екран", "dialogFullscreenSave": "ЗАЧУВАЈ", "dialogFullscreenDescription": "Демонстрација за дијалог на цел екран", "cupertinoButtonEnabled": "Enabled", "cupertinoButtonDisabled": "Disabled", "cupertinoButtonWithBackground": "Со заднина", "cupertinoAlertCancel": "Откажи", "cupertinoAlertDiscard": "Отфрли", "cupertinoAlertLocationTitle": "Да се дозволи „Карти“ да пристапува до вашата локација додека ја користите апликацијата?", "cupertinoAlertLocationDescription": "Вашата моментална локација ќе се прикаже на картата и ќе се користи за насоки, резултати од пребрувањето во близина и проценети времиња за патување.", "cupertinoAlertAllow": "Дозволи", "cupertinoAlertDontAllow": "Не дозволувај", "cupertinoAlertFavoriteDessert": "Изберете го омилениот десерт", "cupertinoAlertDessertDescription": "Изберете го омилениот тип десерт од списокот подолу. Вашиот избор ќе се искористи за да се приспособи предложениот список со места за јадење во вашата област.", "cupertinoAlertCheesecake": "Торта со сирење", "cupertinoAlertTiramisu": "Тирамису", "cupertinoAlertApplePie": "Пита со јаболка", "cupertinoAlertChocolateBrownie": "Чоколадно колаче", "cupertinoShowAlert": "Прикажи предупреување", "colorsRed": "ЦРВЕНА", "colorsPink": "РОЗОВА", "colorsPurple": "ВИОЛЕТОВА", "colorsDeepPurple": "ТЕМНОПУРПУРНА", "colorsIndigo": "ИНДИГО", "colorsBlue": "СИНА", "colorsLightBlue": "СВЕТЛОСИНА", "colorsCyan": "ЦИЈАН", "dialogAddAccount": "Додајте сметка", "Gallery": "Галерија", "Categories": "Категории", "SHRINE": "СВЕТИЛИШТЕ", "Basic shopping app": "Основна апликација за купување", "RALLY": "РЕЛИ", "CRANE": "КРАН", "Travel app": "Апликација за патувања", "MATERIAL": "МАТЕРИЈАЛ", "CUPERTINO": "КУПЕРТИНО", "REFERENCE STYLES & MEDIA": "РЕФЕРЕНТНИ СТИЛОВИ И АУДИОВИЗУЕЛНИ СОДРЖИНИ" }
gallery/lib/l10n/intl_mk.arb/0
{ "file_path": "gallery/lib/l10n/intl_mk.arb", "repo_id": "gallery", "token_count": 37574 }
814
{ "loading": "Загрузка", "deselect": "Отменить выбор", "select": "Выбрать", "selectable": "Можно выбрать (нажмите и удерживайте)", "selected": "Выбрано", "demo": "Демоверсия", "bottomAppBar": "Нижняя панель приложения", "notSelected": "Не выбрано", "demoCupertinoSearchTextFieldTitle": "Поле поиска", "demoCupertinoPicker": "Окно выбора", "demoCupertinoSearchTextFieldSubtitle": "Поле поиска в стиле iOS", "demoCupertinoSearchTextFieldDescription": "Поле поиска, где пользователь может вводить текстовые запросы, а также просматривать и фильтровать подсказки.", "demoCupertinoSearchTextFieldPlaceholder": "Введите текст", "demoCupertinoScrollbarTitle": "Полоса прокрутки", "demoCupertinoScrollbarSubtitle": "Полоса прокрутки в стиле iOS", "demoCupertinoScrollbarDescription": "Полоса прокрутки для просмотра дочернего элемента.", "demoTwoPaneItem": "Объект {value}", "demoTwoPaneList": "Список", "demoTwoPaneFoldableLabel": "Складное устройство", "demoTwoPaneSmallScreenLabel": "Небольшой экран", "demoTwoPaneSmallScreenDescription": "Вот так TwoPane работает на устройстве с маленьким экраном.", "demoTwoPaneTabletLabel": "Планшет или компьютер", "demoTwoPaneTabletDescription": "Вот так TwoPane работает на устройстве с большим экраном, например на планшете или компьютере.", "demoTwoPaneTitle": "TwoPane", "demoTwoPaneSubtitle": "Адаптивные макеты на складных устройствах, а также устройствах с большим или маленьким экраном.", "splashSelectDemo": "Выберите демоверсию", "demoTwoPaneFoldableDescription": "Вот так TwoPane работает на складном устройстве.", "demoTwoPaneDetails": "Сведения", "demoTwoPaneSelectItem": "Выберите объект", "demoTwoPaneItemDetails": "Сведения об объекте {value}", "demoCupertinoContextMenuActionText": "Чтобы увидеть контекстное меню, нажмите на логотип Flutter и удерживайте.", "demoCupertinoContextMenuDescription": "Полноэкранное контекстное меню в стиле iOS. Появляется после долгого нажатия на элемент интерфейса.", "demoAppBarTitle": "Панель приложения", "demoAppBarDescription": "На панели приложения представлены сведения и действия, относящиеся к текущему экрану. Она может содержать название и логотип продукта, заголовок, а также кнопки для навигации и других действий.", "demoDividerTitle": "Разделитель", "demoDividerSubtitle": "Тонкая линия, с помощью которой можно группировать контент", "demoDividerDescription": "Разделители позволяют группировать контент. Их можно использовать, например, в списках и выдвигающихся панелях.", "demoVerticalDividerTitle": "Вертикальный разделитель", "demoCupertinoContextMenuTitle": "Контекстное меню", "demoCupertinoContextMenuSubtitle": "Контекстное меню в стиле iOS", "demoAppBarSubtitle": "На ней показаны сведения и действия, относящиеся к текущему экрану", "demoCupertinoContextMenuActionOne": "Действие 1", "demoCupertinoContextMenuActionTwo": "Действие 2", "demoDateRangePickerDescription": "Диалоговое окно в стиле Material Design, в котором можно выбрать диапазон дат.", "demoDateRangePickerTitle": "Выбор диапазона дат", "demoNavigationDrawerUserName": "Имя пользователя", "demoNavigationDrawerUserEmail": "[email protected]", "demoNavigationDrawerText": "Чтобы открыть выдвигающуюся панель, нужно провести пальцем от края или коснуться значка в левом верхнем углу.", "demoNavigationRailTitle": "Боковая панель навигации", "demoNavigationRailSubtitle": "Показ боковой панели навигации в приложении", "demoNavigationRailDescription": "Виджет в стиле Material Design, который отображается слева или справа в приложении и позволяет переходить между небольшим количеством просмотров, обычно от трех до пяти.", "demoNavigationRailFirst": "Первая", "demoNavigationDrawerTitle": "Панель навигации", "demoNavigationRailThird": "Третья", "replyStarredLabel": "Помеченные", "demoTextButtonDescription": "При нажатии текстовой кнопки отображается цветовой эффект, но кнопка не поднимается. Используйте такие кнопки на панелях инструментов, в диалоговых окнах или как встроенные элементы с полями.", "demoElevatedButtonTitle": "Приподнятая кнопка", "demoElevatedButtonDescription": "Приподнятые кнопки позволяют сделать плоские макеты более объемными, а функции на насыщенных или широких страницах – более заметными.", "demoOutlinedButtonTitle": "Контурная кнопка", "demoOutlinedButtonDescription": "Контурные кнопки при нажатии становятся непрозрачными и поднимаются. Часто они используются вместе с приподнятыми кнопками, чтобы обозначить альтернативное, дополнительное действие.", "demoContainerTransformDemoInstructions": "Подсказки, списки и плавающие кнопки действия", "demoNavigationDrawerSubtitle": "Показ выдвигающейся панели на панели приложения", "replyDescription": "Почтовое приложение для эффективного общения", "demoNavigationDrawerDescription": "Горизонтальная панель в стиле Material Design, которая выдвигается от края экрана и содержит навигационные ссылки приложения.", "replyDraftsLabel": "Черновики", "demoNavigationDrawerToPageOne": "Пункт один", "replyInboxLabel": "Входящие", "demoSharedXAxisDemoInstructions": "Кнопки \"Далее\" и \"Назад\"", "replySpamLabel": "Спам", "replyTrashLabel": "Корзина", "replySentLabel": "Отправленные", "demoNavigationRailSecond": "Вторая", "demoNavigationDrawerToPageTwo": "Пункт два", "demoFadeScaleDemoInstructions": "Модальные и плавающие кнопки", "demoFadeThroughDemoInstructions": "Навигация внизу экрана", "demoSharedZAxisDemoInstructions": "Кнопка \"Настройки\"", "demoSharedYAxisDemoInstructions": "Сортировать, используя фильтр \"Слушали недавно\"", "demoTextButtonTitle": "Текстовая кнопка", "demoSharedZAxisBeefSandwichRecipeTitle": "Бутерброд с говядиной", "demoSharedZAxisDessertRecipeDescription": "Рецепт десерта", "demoSharedYAxisAlbumTileSubtitle": "Исполнитель", "demoSharedYAxisAlbumTileTitle": "Альбом", "demoSharedYAxisRecentSortTitle": "Прослушано недавно", "demoSharedYAxisAlphabeticalSortTitle": "А–Я", "demoSharedYAxisAlbumCount": "268 альбомов", "demoSharedYAxisTitle": "Общая ось Y", "demoSharedXAxisCreateAccountButtonText": "СОЗДАТЬ АККАУНТ", "demoFadeScaleAlertDialogDiscardButton": "ОТМЕНИТЬ", "demoSharedXAxisSignInTextFieldLabel": "Адрес электронной почты или номер телефона", "demoSharedXAxisSignInSubtitleText": "Войдите со своим аккаунтом", "demoSharedXAxisSignInWelcomeText": "Здравствуйте, Дэвид Парк!", "demoSharedXAxisIndividualCourseSubtitle": "Показан отдельно", "demoSharedXAxisBundledCourseSubtitle": "В наборе", "demoFadeThroughAlbumsDestination": "Альбомы", "demoSharedXAxisDesignCourseTitle": "Дизайн", "demoSharedXAxisIllustrationCourseTitle": "Иллюстрация", "demoSharedXAxisBusinessCourseTitle": "Бизнес", "demoSharedXAxisArtsAndCraftsCourseTitle": "Искусство и ремесла", "demoMotionPlaceholderSubtitle": "Дополнительный текст", "demoFadeScaleAlertDialogCancelButton": "ОТМЕНА", "demoFadeScaleAlertDialogHeader": "Диалоговое окно с оповещением", "demoFadeScaleHideFabButton": "СКРЫТЬ ПЛАВАЮЩУЮ КНОПКУ ДЕЙСТВИЯ", "demoFadeScaleShowFabButton": "ПОКАЗАТЬ ПЛАВАЮЩУЮ КНОПКУ ДЕЙСТВИЯ", "demoFadeScaleShowAlertDialogButton": "ПОКАЗАТЬ МОДАЛЬНОЕ ОКНО", "demoFadeScaleDescription": "Этот эффект используется для элементов пользовательского интерфейса, которые появляются или исчезают в пределах экрана. Пример: диалоговое окно, которое возникает, а затем пропадает в центре экрана.", "demoFadeScaleTitle": "Плавное появление или исчезновение", "demoFadeThroughTextPlaceholder": "123 фотографии", "demoFadeThroughSearchDestination": "Поиск", "demoFadeThroughPhotosDestination": "Фотографии", "demoSharedXAxisCoursePageSubtitle": "Наборы категорий появляются в фиде как группы. Это можно изменить в любое время.", "demoFadeThroughDescription": "Плавное переключение используется для переходов между элементами пользовательского интерфейса, между которыми нет тесной связи.", "demoFadeThroughTitle": "Плавное переключение", "demoSharedZAxisHelpSettingLabel": "Справка", "demoMotionSubtitle": "Все стандартные переходы", "demoSharedZAxisNotificationSettingLabel": "Уведомления", "demoSharedZAxisProfileSettingLabel": "Профиль", "demoSharedZAxisSavedRecipesListTitle": "Сохраненные рецепты", "demoSharedZAxisBeefSandwichRecipeDescription": "Рецепт бутерброда с говядиной", "demoSharedZAxisCrabPlateRecipeDescription": "Рецепт блюда с крабом", "demoSharedXAxisCoursePageTitle": "Упорядочите курсы", "demoSharedZAxisCrabPlateRecipeTitle": "Краб", "demoSharedZAxisShrimpPlateRecipeDescription": "Рецепт блюда с креветками", "demoSharedZAxisShrimpPlateRecipeTitle": "Креветка", "demoContainerTransformTypeFadeThrough": "ПЛАВНОЕ ПЕРЕКЛЮЧЕНИЕ", "demoSharedZAxisDessertRecipeTitle": "Десерт", "demoSharedZAxisSandwichRecipeDescription": "Рецепт бутерброда", "demoSharedZAxisSandwichRecipeTitle": "Бутерброд", "demoSharedZAxisBurgerRecipeDescription": "Рецепт бургера", "demoSharedZAxisBurgerRecipeTitle": "Бургер", "demoSharedZAxisSettingsPageTitle": "Настройки", "demoSharedZAxisTitle": "Общая ось Z", "demoSharedZAxisPrivacySettingLabel": "Конфиденциальность", "demoMotionTitle": "Движение", "demoContainerTransformTitle": "Преобразование с контейнером", "demoContainerTransformDescription": "Преобразование с контейнером предназначено для переходов между элементами пользовательского интерфейса, содержащими контейнер. Этот эффект устанавливает видимую связь между двумя элементами интерфейса.", "demoContainerTransformModalBottomSheetTitle": "Режим плавного появления или исчезновения", "demoContainerTransformTypeFade": "ПЛАВНОЕ ПОЯВЛЕНИЕ ИЛИ ИСЧЕЗНОВЕНИЕ", "demoSharedYAxisAlbumTileDurationUnit": "мин.", "demoMotionPlaceholderTitle": "Название", "demoSharedXAxisForgotEmailButtonText": "ЗАБЫЛИ ЭЛЕКТРОННУЮ ПОЧТУ?", "demoMotionSmallPlaceholderSubtitle": "Дополнительно", "demoMotionDetailsPageTitle": "Страница сведений", "demoMotionListTileTitle": "Пункт списка", "demoSharedAxisDescription": "Эффект общей оси применяется для переходов между элементами пользовательского интерфейса, которые расположены как бы на одной оси. Для укрепления связи между элементами используется совместное преобразование по оси X, Y или Z.", "demoSharedXAxisTitle": "Общая ось X", "demoSharedXAxisBackButtonText": "НАЗАД", "demoSharedXAxisNextButtonText": "ДАЛЕЕ", "demoSharedXAxisCulinaryCourseTitle": "Кулинария", "githubRepo": "репозиторий GitHub {repoName}", "fortnightlyMenuUS": "США", "fortnightlyMenuBusiness": "Бизнес", "fortnightlyMenuScience": "Наука", "fortnightlyMenuSports": "Спорт", "fortnightlyMenuTravel": "Путешествия", "fortnightlyMenuCulture": "Культура", "fortnightlyTrendingTechDesign": "TechDesign", "rallyBudgetDetailAmountLeft": "Осталось", "fortnightlyHeadlineArmy": "Зеленая армия: реформирование изнутри", "fortnightlyDescription": "Новостное приложение, в котором главное – контент", "rallyBillDetailAmountDue": "К оплате", "rallyBudgetDetailTotalCap": "Верхний предел", "rallyBudgetDetailAmountUsed": "Израсходовано", "fortnightlyTrendingHealthcareRevolution": "HealthcareRevolution", "fortnightlyMenuFrontPage": "Главная страница", "fortnightlyMenuWorld": "Весь мир", "rallyBillDetailAmountPaid": "Оплачено", "fortnightlyMenuPolitics": "Политика", "fortnightlyHeadlineBees": "Дефицит пчел в сельском хозяйстве", "fortnightlyHeadlineGasoline": "Будущее бензина", "fortnightlyTrendingGreenArmy": "GreenArmy", "fortnightlyHeadlineFeminists": "Феминистки выходят на путь партизанской войны", "fortnightlyHeadlineFabrics": "Дизайнеры используют новые технологии для производства футуристичных тканей", "fortnightlyHeadlineStocks": "Из-за стагнации курса акций инвесторы присматриваются к валюте", "fortnightlyTrendingReform": "Reform", "fortnightlyMenuTech": "Технологии", "fortnightlyHeadlineWar": "Жизни американцев, разделенные войной", "fortnightlyHeadlineHealthcare": "Тихая революция с большими последствиями в сфере здравоохранения", "fortnightlyLatestUpdates": "Последние новости", "fortnightlyTrendingStocks": "Stocks", "rallyBillDetailTotalAmount": "Общая сумма", "demoCupertinoPickerDateTime": "Дата и время", "signIn": "ВОЙТИ", "dataTableRowWithSugar": "{value} с сахаром", "dataTableRowApplePie": "Яблочный пирог", "dataTableRowDonut": "Пончик", "dataTableRowHoneycomb": "Мед в сотах", "dataTableRowLollipop": "Леденец", "dataTableRowJellyBean": "Мармеладное драже", "dataTableRowGingerbread": "Имбирный пряник", "dataTableRowCupcake": "Кекс", "dataTableRowEclair": "Эклер", "dataTableRowIceCreamSandwich": "Брикет мороженого", "dataTableRowFrozenYogurt": "Замороженный йогурт", "dataTableColumnIron": "Железо (%)", "dataTableColumnCalcium": "Кальций (%)", "dataTableColumnSodium": "Натрий (мг)", "demoTimePickerTitle": "Окно выбора времени", "demo2dTransformationsResetTooltip": "Сбросить трансформации", "dataTableColumnFat": "Жиры (г)", "dataTableColumnCalories": "Калории", "dataTableColumnDessert": "Десерт (одна порция)", "cardsDemoTravelDestinationLocation1": "Танджавур, штат Тамилнад", "demoTimePickerDescription": "Диалоговое окно в стиле Material Design, в котором можно выбрать время.", "demoPickersShowPicker": "ПОКАЗАТЬ ОКНО ВЫБОРА", "demoTabsScrollingTitle": "Прокрутка", "demoTabsNonScrollingTitle": "Без прокрутки", "craneHours": "{hours,plural,=1{1 ч.}few{{hours} ч.}many{{hours} ч.}other{{hours} ч.}}", "craneMinutes": "{minutes,plural,=1{1 мин.}few{{minutes} мин.}many{{minutes} мин.}other{{minutes} мин.}}", "craneFlightDuration": "{hoursShortForm} {minutesShortForm}", "dataTableHeader": "Питание", "demoDatePickerTitle": "Окно выбора даты", "demoPickersSubtitle": "Выбор даты и времени", "demoPickersTitle": "Окна выбора", "demo2dTransformationsEditTooltip": "Изменить элемент", "demoDataTableDescription": "В таблицах данные распределены по строкам и столбцам, чтобы пользователь мог легко находить нужную информацию и быстро сравнивать представленные варианты.", "demo2dTransformationsDescription": "Нажмите, чтобы изменить элементы. Для панорамирования используйте перетаскивание. Чтобы настроить масштаб, сведите или разведите пальцы. Вы также можете поворачивать объект двумя пальцами. Чтобы вернуться к исходным параметрам, нажмите кнопку сброса.", "demo2dTransformationsSubtitle": "Панорамирование, масштабирование и поворот", "demo2dTransformationsTitle": "2D-трансформации", "demoCupertinoTextFieldPIN": "PIN-код", "demoCupertinoTextFieldDescription": "Поле, в которое можно ввести текст с помощью аппаратной или экранной клавиатуры.", "demoCupertinoTextFieldSubtitle": "Текстовые поля в стиле iOS", "demoCupertinoTextFieldTitle": "Текстовые поля", "demoDatePickerDescription": "Диалоговое окно в стиле Material Design, в котором можно выбрать дату.", "demoCupertinoPickerTime": "Время", "demoCupertinoPickerDate": "Дата", "demoCupertinoPickerTimer": "Таймер", "demoCupertinoPickerDescription": "Окно выбора в стиле iOS, которое можно использовать, чтобы указать строку, дату или время.", "demoCupertinoPickerSubtitle": "Окна выбора в стиле iOS", "demoCupertinoPickerTitle": "Окна выбора", "dataTableRowWithHoney": "{value} с медом", "cardsDemoTravelDestinationCity2": "Четтинад", "bannerDemoResetText": "Показать баннер ещё раз", "bannerDemoMultipleText": "Несколько действий", "bannerDemoLeadingText": "Значок перед текстом", "dismiss": "ЗАКРЫТЬ", "cardsDemoTappable": "Нажмите", "cardsDemoSelectable": "Нажмите и удерживайте", "cardsDemoExplore": "Обзор", "cardsDemoExploreSemantics": "Посмотреть: {destinationName}", "cardsDemoShareSemantics": "Поделиться: {destinationName}", "cardsDemoTravelDestinationTitle1": "10 городов в штате Тамилнад, которые стоит посетить", "cardsDemoTravelDestinationDescription1": "Номер 10", "cardsDemoTravelDestinationCity1": "Танджавур", "dataTableColumnProtein": "Белки (г)", "cardsDemoTravelDestinationTitle2": "Мастера Южной Индии", "cardsDemoTravelDestinationDescription2": "Прядильщики шелка", "bannerDemoText": "Пароль был изменен на другом устройстве. Повторите вход.", "cardsDemoTravelDestinationLocation2": "Шиваганга, штат Тамилнад", "cardsDemoTravelDestinationTitle3": "Храм Брахадисвара", "cardsDemoTravelDestinationDescription3": "Храмы", "demoBannerTitle": "Баннер", "demoBannerSubtitle": "Показ баннера в списке", "demoBannerDescription": "Баннер содержит короткое, но важное сообщение, а также доступные пользователю действия. Убрать баннер с экрана можно только вручную.", "demoCardTitle": "Карточки", "demoCardSubtitle": "Расположенные внизу карточки со скругленными углами", "demoCardDescription": "На карточке можно разместить дополнительную информацию, например сведения об альбоме, блюде, географическом местоположении, контактных данных и т. д.", "demoDataTableTitle": "Таблицы с данными", "demoDataTableSubtitle": "Информация, организованная в виде таблицы", "dataTableColumnCarbs": "Углеводы (г)", "placeTanjore": "Танджор", "demoGridListsTitle": "Табличные списки", "placeFlowerMarket": "Цветочный рынок", "placeBronzeWorks": "Завод по производству изделий из бронзы", "placeMarket": "Рынок", "placeThanjavurTemple": "Храм в Танджавуре", "placeSaltFarm": "Соляная ферма", "placeScooters": "Скутеристы", "placeSilkMaker": "Рабочий на шелковой фабрике", "placeLunchPrep": "Приготовление обеда", "placeBeach": "Пляж", "placeFisherman": "Рыбак", "demoMenuSelected": "Выбранное значение: {value}", "demoMenuRemove": "Удалить", "demoMenuGetLink": "Получить ссылку", "demoMenuShare": "Поделиться", "demoBottomAppBarSubtitle": "На панели в нижней части экрана располагаются элементы навигации и доступные действия", "demoMenuAnItemWithASectionedMenu": "Объект, у которого есть меню с разделами", "demoMenuADisabledMenuItem": "Недоступный пункт меню", "demoLinearProgressIndicatorTitle": "Линейный индикатор прогресса", "demoMenuContextMenuItemOne": "Первый пункт контекстного меню", "demoMenuAnItemWithASimpleMenu": "Объект, у которого есть простое меню", "demoCustomSlidersTitle": "Настраиваемые ползунки", "demoMenuAnItemWithAChecklistMenu": "Объект, у которого есть меню с контрольным списком", "demoCupertinoActivityIndicatorTitle": "Индикатор выполнения", "demoCupertinoActivityIndicatorSubtitle": "Индикаторы выполнения в стиле iOS", "demoCupertinoActivityIndicatorDescription": "Вращающийся по часовой стрелке индикатор выполнения в стиле iOS.", "demoCupertinoNavigationBarTitle": "Панель навигации", "demoCupertinoNavigationBarSubtitle": "Панель навигации в стиле iOS", "demoCupertinoNavigationBarDescription": "Панель навигации в стиле iOS – это панель инструментов, обязательным атрибутом которой является название страницы, расположенное посередине.", "demoCupertinoPullToRefreshTitle": "Обновление страницы с помощью движения сверху вниз", "demoCupertinoPullToRefreshSubtitle": "Элемент управления в стиле iOS для обновления страницы", "demoCupertinoPullToRefreshDescription": "Элемент управления в стиле iOS для обновления страницы с помощью движения сверху вниз.", "demoProgressIndicatorTitle": "Индикаторы прогресса", "demoProgressIndicatorSubtitle": "Линейные, кольцевые и неопределенные", "demoCircularProgressIndicatorTitle": "Кольцевой индикатор прогресса", "demoCircularProgressIndicatorDescription": "Кольцевой индикатор прогресса в стиле Material Design показывает, что приложение обрабатывает запрос пользователя.", "demoMenuFour": "4", "demoLinearProgressIndicatorDescription": "Линейный индикатор прогресса в стиле Material Design, который также называют индикатором выполнения.", "demoTooltipTitle": "Подсказки", "demoTooltipSubtitle": "Короткое сообщение, которое появляется при долгом нажатии или наведении указателя", "demoTooltipDescription": "Подсказки помогают понять, как работают кнопки и другие элементы интерфейса. Они появляются при долгом нажатии на элемент, переходе к нему или наведении на него указателя.", "demoTooltipInstructions": "Чтобы увидеть подсказку, наведите указатель на элемент или нажмите на него и удерживайте.", "placeChennai": "Ченнай", "demoMenuChecked": "Отмеченное значение: {value}", "placeChettinad": "Четтинад", "demoMenuPreview": "Предпросмотр", "demoBottomAppBarTitle": "Нижняя панель приложения", "demoBottomAppBarDescription": "На нижней панели приложения можно разместить панель навигации и до четырех действий, включая плавающую командную кнопку.", "bottomAppBarNotch": "Выемка", "bottomAppBarPosition": "Положение плавающей командной кнопки", "bottomAppBarPositionDockedEnd": "На панели с краю", "bottomAppBarPositionDockedCenter": "На панели в центре", "bottomAppBarPositionFloatingEnd": "Над панелью с краю", "bottomAppBarPositionFloatingCenter": "Над панелью в центре", "demoSlidersEditableNumericalValue": "Числовое значение", "demoGridListsSubtitle": "Макет строк и столбцов", "demoGridListsDescription": "Табличные списки больше всего подходят для показа однотипных данных, например изображений. Объекты, включенные в такие списки, называются элементами.", "demoGridListsImageOnlyTitle": "Только изображение", "demoGridListsHeaderTitle": "С верхним колонтитулом", "demoGridListsFooterTitle": "С нижним колонтитулом", "demoSlidersTitle": "Ползунки", "demoSlidersSubtitle": "Чтобы выбрать определенное значение, пользователю нужно провести пальцем по экрану", "demoSlidersDescription": "Ползунки позволяют выбрать нужное значение в заданном диапазоне. С помощью ползунков удобно регулировать уровень громкости, настраивать яркость и фильтры изображений.", "demoRangeSlidersTitle": "Ползунки диапазона", "demoRangeSlidersDescription": "Ползунки позволяют выбрать нужное значение в заданном диапазоне. Для понятности по краям диапазона можно расположить значки. С помощью ползунков удобно регулировать уровень громкости, настраивать яркость и фильтры изображений.", "demoMenuAnItemWithAContextMenuButton": "Объект, у которого есть контекстное меню", "demoCustomSlidersDescription": "Ползунки позволяют выбрать одно из значений или указать диапазон значений. К ползункам также можно применить тему и собственные настройки.", "demoSlidersContinuousWithEditableNumericalValue": "Непрерывный ползунок с возможностью редактировать числовое значение", "demoSlidersDiscrete": "Дискретный", "demoSlidersDiscreteSliderWithCustomTheme": "Дискретный ползунок с пользовательской темой", "demoSlidersContinuousRangeSliderWithCustomTheme": "Непрерывный ползунок диапазона с пользовательской темой", "demoSlidersContinuous": "Непрерывный", "placePondicherry": "Пондичерри", "demoMenuTitle": "Меню", "demoContextMenuTitle": "Контекстное меню", "demoSectionedMenuTitle": "Меню с разделами", "demoSimpleMenuTitle": "Простое меню", "demoChecklistMenuTitle": "Меню с контрольным списком", "demoMenuSubtitle": "Кнопки меню и простые меню", "demoMenuDescription": "Меню содержит список вариантов, которые располагаются в отдельном блоке. Список появляется, когда пользователь нажимает кнопку, выполняет действие или взаимодействует с другим элементом управления.", "demoMenuItemValueOne": "Первый пункт меню", "demoMenuItemValueTwo": "Второй пункт меню", "demoMenuItemValueThree": "Третий пункт меню", "demoMenuOne": "1", "demoMenuTwo": "2", "demoMenuThree": "3", "demoMenuContextMenuItemThree": "Третий пункт контекстного меню", "demoCupertinoSwitchSubtitle": "Переключатель в стиле iOS", "demoSnackbarsText": "Это снэк-панель.", "demoCupertinoSliderSubtitle": "Ползунок в стиле iOS", "demoCupertinoSliderDescription": "Ползунок можно использовать для выбора определенного значения в указанном диапазоне.", "demoCupertinoSliderContinuous": "Непрерывный ползунок: {value}", "demoCupertinoSliderDiscrete": "Дискретный ползунок: {value}", "demoSnackbarsAction": "Вы нажали кнопку на снэк-панели.", "backToGallery": "Назад на главную", "demoCupertinoTabBarTitle": "Панель вкладок", "demoCupertinoSwitchDescription": "С помощью переключателя можно включить или отключить отдельную настройку.", "demoSnackbarsActionButtonLabel": "КНОПКА", "cupertinoTabBarProfileTab": "Профиль", "demoSnackbarsButtonLabel": "ПОКАЗАТЬ СНЭК-ПАНЕЛЬ", "demoSnackbarsDescription": "Снэк-панели – это уведомления, которые на некоторое время появляются в нижней части экрана. Они сообщают о действии, которое было или будет выполнено в приложении. Снэк-панели не требуется закрывать вручную, и они не должны отвлекать пользователя.", "demoSnackbarsSubtitle": "Снэк-панели – это уведомления, которые появляются в нижней части экрана", "demoSnackbarsTitle": "Cнэк-панели", "demoCupertinoSliderTitle": "Ползунок", "cupertinoTabBarChatTab": "Чат", "cupertinoTabBarHomeTab": "Главная", "demoCupertinoTabBarDescription": "Нижняя навигационная панель вкладок в стиле iOS. Содержит несколько вкладок, одна из которых активна. По умолчанию активной считается первая вкладка.", "demoCupertinoTabBarSubtitle": "Нижняя панель вкладок в стиле iOS", "demoOptionsFeatureTitle": "Показ параметров", "demoOptionsFeatureDescription": "Нажмите, чтобы посмотреть доступные параметры для этой демоверсии.", "demoCodeViewerCopyAll": "КОПИРОВАТЬ ВСЕ", "shrineScreenReaderRemoveProductButton": "{product}: удалить товар", "shrineScreenReaderProductAddToCart": "Добавить в корзину", "shrineScreenReaderCart": "{quantity,plural,=0{Нет товаров в корзине}=1{1 товар в корзине}few{{quantity} товара в корзине}many{{quantity} товаров в корзине}other{{quantity} товара в корзине}}", "demoCodeViewerFailedToCopyToClipboardMessage": "Не удалось скопировать текст: {error}", "demoCodeViewerCopiedToClipboardMessage": "Текст скопирован в буфер обмена.", "craneSleep8SemanticLabel": "Руины майя на утесе над пляжем", "craneSleep4SemanticLabel": "Гостиница у озера на фоне гор", "craneSleep2SemanticLabel": "Крепость Мачу-Пикчу", "craneSleep1SemanticLabel": "Шале на фоне заснеженного пейзажа с хвойными деревьями", "craneSleep0SemanticLabel": "Бунгало над водой", "craneFly13SemanticLabel": "Бассейн у моря, окруженный пальмами", "craneFly12SemanticLabel": "Бассейн, окруженный пальмами", "craneFly11SemanticLabel": "Кирпичный маяк на фоне моря", "craneFly10SemanticLabel": "Минареты мечети аль-Азхар на закате", "craneFly9SemanticLabel": "Мужчина, который опирается на синий ретроавтомобиль", "craneFly8SemanticLabel": "Роща сверхдеревьев", "craneEat9SemanticLabel": "Прилавок с пирожными в кафе", "craneEat2SemanticLabel": "Бургер", "craneFly5SemanticLabel": "Гостиница у озера на фоне гор", "demoSelectionControlsSubtitle": "Флажки, радиокнопки и переключатели", "craneEat10SemanticLabel": "Женщина, которая держит огромный сэндвич с пастромой", "craneFly4SemanticLabel": "Бунгало над водой", "craneEat7SemanticLabel": "Вход в пекарню", "craneEat6SemanticLabel": "Блюдо с креветками", "craneEat5SemanticLabel": "Стильный зал ресторана", "craneEat4SemanticLabel": "Шоколадный десерт", "craneEat3SemanticLabel": "Тако по-корейски", "craneFly3SemanticLabel": "Крепость Мачу-Пикчу", "craneEat1SemanticLabel": "Пустой бар с высокими стульями", "craneEat0SemanticLabel": "Пицца в дровяной печи", "craneSleep11SemanticLabel": "Небоскреб Тайбэй 101", "craneSleep10SemanticLabel": "Минареты мечети аль-Азхар на закате", "craneSleep9SemanticLabel": "Кирпичный маяк на фоне моря", "craneEat8SemanticLabel": "Тарелка раков", "craneSleep7SemanticLabel": "Яркие дома на площади Рибейра", "craneSleep6SemanticLabel": "Бассейн, окруженный пальмами", "craneSleep5SemanticLabel": "Палатка в поле", "settingsButtonCloseLabel": "Закрыть настройки", "demoSelectionControlsCheckboxDescription": "С помощью флажка пользователь может выбрать несколько параметров из списка. Чаще всего у флажка есть два состояния. В некоторых случаях предусмотрено третье.", "settingsButtonLabel": "Настройки", "demoListsTitle": "Списки", "demoListsSubtitle": "Макеты прокручиваемых списков", "demoListsDescription": "Одна строка с фиксированным размером, которая обычно содержит текст и значок.", "demoOneLineListsTitle": "Одна строка", "demoTwoLineListsTitle": "Две строки", "demoListsSecondary": "Дополнительный текст", "demoSelectionControlsTitle": "Элементы управления выбором", "craneFly7SemanticLabel": "Гора Рашмор", "demoSelectionControlsCheckboxTitle": "Флажок", "craneSleep3SemanticLabel": "Мужчина, который опирается на синий ретроавтомобиль", "demoSelectionControlsRadioTitle": "Радиокнопка", "demoSelectionControlsRadioDescription": "С помощью радиокнопки пользователь может выбрать один параметр из списка. Радиокнопки хорошо подходят для тех случаев, когда вы хотите показать все доступные варианты в одном списке.", "demoSelectionControlsSwitchTitle": "Переключатель", "demoSelectionControlsSwitchDescription": "С помощью переключателя пользователь может включать и отключать отдельный параметр. Рядом с переключателем должно быть ясно указано название и состояние параметра.", "craneFly0SemanticLabel": "Шале на фоне заснеженного пейзажа с хвойными деревьями", "craneFly1SemanticLabel": "Палатка в поле", "craneFly2SemanticLabel": "Молитвенные флаги на фоне заснеженной горы", "craneFly6SemanticLabel": "Вид с воздуха на Дворец изящных искусств", "rallySeeAllAccounts": "Показать все банковские счета", "rallyBillAmount": "Счет \"{billName}\" на сумму {amount}. Срок оплаты: {date}.", "shrineTooltipCloseCart": "Закрыть корзину", "shrineTooltipCloseMenu": "Закрыть меню", "shrineTooltipOpenMenu": "Открыть меню", "shrineTooltipSettings": "Настройки", "shrineTooltipSearch": "Поиск", "demoTabsDescription": "Вкладки позволяют упорядочить контент на экранах, в наборах данных и т. д.", "demoTabsSubtitle": "Вкладки, прокручиваемые по отдельности", "demoTabsTitle": "Вкладки", "rallyBudgetAmount": "Бюджет \"{budgetName}\". Израсходовано: {amountUsed} из {amountTotal}. Осталось: {amountLeft}.", "shrineTooltipRemoveItem": "Удалить товар", "rallyAccountAmount": "Счет \"{accountName}\" с номером {accountNumber}. Баланс: {amount}.", "rallySeeAllBudgets": "Показать все бюджеты", "rallySeeAllBills": "Показать все счета", "craneFormDate": "Выберите дату", "craneFormOrigin": "Выберите пункт отправления", "craneFly2": "Долина Кхумбу, Непал", "craneFly3": "Мачу-Пикчу, Перу", "craneFly4": "Мале, Мальдивы", "craneFly5": "Вицнау, Швейцария", "craneFly6": "Мехико, Мексика", "craneFly7": "Гора Рашмор, США", "settingsTextDirectionLocaleBased": "Региональные настройки", "craneFly9": "Гавана, Куба", "craneFly10": "Каир, Египет", "craneFly11": "Лиссабон, Португалия", "craneFly12": "Напа, США", "craneFly13": "Бали, Индонезия", "craneSleep0": "Мале, Мальдивы", "craneSleep1": "Аспен, США", "craneSleep2": "Мачу-Пикчу, Перу", "demoCupertinoSegmentedControlTitle": "Сегментированный элемент управления", "craneSleep4": "Вицнау, Швейцария", "craneSleep5": "Биг-Сур, США", "craneSleep6": "Напа, США", "craneSleep7": "Порту, Португалия", "craneSleep8": "Тулум, Мексика", "craneEat5": "Сеул, Южная Корея", "demoChipTitle": "Чипы", "demoChipSubtitle": "Компактные элементы, обозначающие объект, атрибут или действие", "demoActionChipTitle": "Чипы действий", "demoActionChipDescription": "Чипы действий представляют собой набор динамических параметров, которые запускают действия, связанные с основным контентом. Как правило, чипы действий отображаются в интерфейсе в зависимости от контекста.", "demoChoiceChipTitle": "Чип выбора", "demoChoiceChipDescription": "Каждый чип выбора представляет собой один из вариантов выбора. Чип выбора может содержать описание или название категории.", "demoFilterChipTitle": "Чип фильтра", "demoFilterChipDescription": "Чипы фильтров содержат теги и описания, которые помогают отсеивать ненужный контент.", "demoInputChipTitle": "Чип записи", "demoInputChipDescription": "Чипы записи представляют сложные данные в компактной форме, например объекты (людей, места, вещи) или текстовые диалоги.", "craneSleep9": "Лиссабон, Португалия", "craneEat10": "Лиссабон, Португалия", "demoCupertinoSegmentedControlDescription": "Позволяет переключаться между несколькими взаимоисключающими вариантами (сегментами). Выделен только тот вариант, который был выбран.", "chipTurnOnLights": "Включить индикаторы", "chipSmall": "Маленький", "chipMedium": "Средний", "chipLarge": "Большой", "chipElevator": "Лифт", "chipWasher": "Стиральная машина", "chipFireplace": "Камин", "chipBiking": "Велосипед", "craneFormDiners": "Закусочные", "rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Увеличьте сумму возможного налогового вычета, назначив категорию для одной нераспределенной транзакции.}few{Увеличьте сумму возможного налогового вычета, назначив категории для {count} нераспределенных транзакций.}many{Увеличьте сумму возможного налогового вычета, назначив категории для {count} нераспределенных транзакций.}other{Увеличьте сумму возможного налогового вычета, назначив категории для {count} нераспределенной транзакции.}}", "craneFormTime": "Выберите время", "craneFormLocation": "Выберите местоположение", "craneFormTravelers": "Число путешествующих", "craneEat8": "Атланта, США", "craneFormDestination": "Выберите пункт назначения", "craneFormDates": "Выберите даты", "craneFly": "АВИАПЕРЕЛЕТЫ", "craneSleep": "ГДЕ ПЕРЕНОЧЕВАТЬ", "craneEat": "ЕДА", "craneFlySubhead": "Куда бы вы хотели отправиться?", "craneSleepSubhead": "Варианты жилья", "craneEatSubhead": "Рестораны", "craneFlyStops": "{numberOfStops,plural,=0{Без пересадок}=1{1 пересадка}few{{numberOfStops} пересадки}many{{numberOfStops} пересадок}other{{numberOfStops} пересадки}}", "craneSleepProperties": "{totalProperties,plural,=0{Нет доступных вариантов жилья}=1{Доступен 1 вариант жилья}few{Доступно {totalProperties} варианта жилья}many{Доступно {totalProperties} вариантов жилья}other{Доступно {totalProperties} варианта жилья}}", "craneEatRestaurants": "{totalRestaurants,plural,=0{Нет ресторанов}=1{1 ресторан}few{{totalRestaurants} ресторана}many{{totalRestaurants} ресторанов}other{{totalRestaurants} ресторана}}", "craneFly0": "Аспен, США", "demoCupertinoSegmentedControlSubtitle": "Сегментированный элемент управления в стиле iOS", "craneSleep10": "Каир, Египет", "craneEat9": "Мадрид, Испания", "craneFly1": "Биг-Сур, США", "craneEat7": "Нашвилл, США", "craneEat6": "Сиэтл, США", "craneFly8": "Сингапур", "craneEat4": "Париж, Франция", "craneEat3": "Портленд, США", "craneEat2": "Кордова, Аргентина", "craneEat1": "Даллас, США", "craneEat0": "Неаполь, Италия", "craneSleep11": "Тайбэй, Тайвань", "craneSleep3": "Гавана, Куба", "shrineLogoutButtonCaption": "ВЫЙТИ", "rallyTitleBills": "СЧЕТА", "rallyTitleAccounts": "БАНКОВСКИЕ СЧЕТА", "shrineProductVagabondSack": "Сумка-ранец", "rallyAccountDetailDataInterestYtd": "Процент с начала года", "shrineProductWhitneyBelt": "Кожаный ремень", "shrineProductGardenStrand": "Цветочные бусы", "shrineProductStrutEarrings": "Серьги на кольцах", "shrineProductVarsitySocks": "Спортивные носки", "shrineProductWeaveKeyring": "Плетеный брелок", "shrineProductGatsbyHat": "Шляпа в стиле Гэтсби", "shrineProductShrugBag": "Сумка хобо", "shrineProductGiltDeskTrio": "Настольный набор", "shrineProductCopperWireRack": "Корзинка из медной проволоки", "shrineProductSootheCeramicSet": "Набор керамической посуды", "shrineProductHurrahsTeaSet": "Прозрачный чайный набор", "shrineProductBlueStoneMug": "Синяя кружка", "shrineProductRainwaterTray": "Минималистичный поднос", "shrineProductChambrayNapkins": "Хлопковые салфетки", "shrineProductSucculentPlanters": "Суккуленты", "shrineProductQuartetTable": "Круглый стол", "shrineProductKitchenQuattro": "Кухонный набор", "shrineProductClaySweater": "Бежевый свитер", "shrineProductSeaTunic": "Легкий свитер", "shrineProductPlasterTunic": "Кремовая туника", "rallyBudgetCategoryRestaurants": "Рестораны", "shrineProductChambrayShirt": "Хлопковая рубашка", "shrineProductSeabreezeSweater": "Мятный свитер", "shrineProductGentryJacket": "Куртка в стиле джентри", "shrineProductNavyTrousers": "Короткие брюки клеш", "shrineProductWalterHenleyWhite": "Белая легкая кофта", "shrineProductSurfAndPerfShirt": "Футболка цвета морской волны", "shrineProductGingerScarf": "Имбирный шарф", "shrineProductRamonaCrossover": "Женственная блузка с запахом", "shrineProductClassicWhiteCollar": "Классическая белая блузка", "shrineProductSunshirtDress": "Летнее платье", "rallyAccountDetailDataInterestRate": "Процентная ставка", "rallyAccountDetailDataAnnualPercentageYield": "Годовая процентная доходность", "rallyAccountDataVacation": "Отпуск", "shrineProductFineLinesTee": "Кофта в полоску", "rallyAccountDataHomeSavings": "Сбережения на дом", "rallyAccountDataChecking": "Расчетный счет", "rallyAccountDetailDataInterestPaidLastYear": "Процент, уплаченный в прошлом году", "rallyAccountDetailDataNextStatement": "Следующая выписка по счету", "rallyAccountDetailDataAccountOwner": "Владелец аккаунта", "rallyBudgetCategoryCoffeeShops": "Кофейни", "rallyBudgetCategoryGroceries": "Продукты", "shrineProductCeriseScallopTee": "Персиковая футболка", "rallyBudgetCategoryClothing": "Одежда", "rallySettingsManageAccounts": "Управление аккаунтами", "rallyAccountDataCarSavings": "Сбережения на машину", "rallySettingsTaxDocuments": "Налоговые документы", "rallySettingsPasscodeAndTouchId": "Код доступа и Touch ID", "rallySettingsNotifications": "Уведомления", "rallySettingsPersonalInformation": "Персональные данные", "rallySettingsPaperlessSettings": "Настройки электронных документов", "rallySettingsFindAtms": "Найти банкоматы", "rallySettingsHelp": "Справка", "rallySettingsSignOut": "Выйти", "rallyAccountTotal": "Всего", "rallyBillsDue": "Срок", "rallyBudgetLeft": "Остаток", "rallyAccounts": "Банковские счета", "rallyBills": "Счета", "rallyBudgets": "Бюджеты", "rallyAlerts": "Оповещения", "rallySeeAll": "ПОКАЗАТЬ ВСЕ", "rallyFinanceLeft": "ОСТАЛОСЬ", "rallyTitleOverview": "ОБЗОР", "shrineProductShoulderRollsTee": "Футболка со свободным рукавом", "shrineNextButtonCaption": "ДАЛЕЕ", "rallyTitleBudgets": "БЮДЖЕТЫ", "rallyTitleSettings": "НАСТРОЙКИ", "rallyLoginLoginToRally": "Вход в Rally", "rallyLoginNoAccount": "Нет аккаунта?", "rallyLoginSignUp": "ЗАРЕГИСТРИРОВАТЬСЯ", "rallyLoginUsername": "Имя пользователя", "rallyLoginPassword": "Пароль", "rallyLoginLabelLogin": "Войти", "rallyLoginRememberMe": "Запомнить меня", "rallyLoginButtonLogin": "ВОЙТИ", "rallyAlertsMessageHeadsUpShopping": "Внимание! Вы израсходовали {percent} своего бюджета на этот месяц.", "rallyAlertsMessageSpentOnRestaurants": "На этой неделе вы потратили {amount} на еду и напитки в ресторанах.", "rallyAlertsMessageATMFees": "В этом месяце вы потратили {amount} на оплату комиссии в банкоматах.", "rallyAlertsMessageCheckingAccount": "Отлично! В этом месяце на вашем счете на {percent} больше средств по сравнению с прошлым месяцем.", "shrineMenuCaption": "МЕНЮ", "shrineCategoryNameAll": "ВСЕ", "shrineCategoryNameAccessories": "АКСЕССУАРЫ", "shrineCategoryNameClothing": "ОДЕЖДА", "shrineCategoryNameHome": "ДЛЯ ДОМА", "shrineLoginUsernameLabel": "Имя пользователя", "shrineLoginPasswordLabel": "Пароль", "shrineCancelButtonCaption": "ОТМЕНА", "shrineCartTaxCaption": "Налог:", "shrineCartPageCaption": "КОРЗИНА", "shrineProductQuantity": "Количество: {quantity}", "shrineProductPrice": "x {price}", "shrineCartItemCount": "{quantity,plural,=0{НЕТ ТОВАРОВ}=1{1 ТОВАР}few{{quantity} ТОВАРА}many{{quantity} ТОВАРОВ}other{{quantity} ТОВАРА}}", "shrineCartClearButtonCaption": "ОЧИСТИТЬ КОРЗИНУ", "shrineCartTotalCaption": "ВСЕГО", "shrineCartSubtotalCaption": "Итого:", "shrineCartShippingCaption": "Доставка:", "shrineProductGreySlouchTank": "Серая майка", "shrineProductStellaSunglasses": "Солнцезащитные очки Stella", "shrineProductWhitePinstripeShirt": "Рубашка в белую полоску", "demoTextFieldWhereCanWeReachYou": "По какому номеру с вами можно связаться?", "settingsTextDirectionLTR": "Слева направо", "settingsTextScalingLarge": "Крупный", "demoBottomSheetHeader": "Заголовок", "demoBottomSheetItem": "Пункт {value}", "demoBottomTextFieldsTitle": "Текстовые поля", "demoTextFieldTitle": "Текстовые поля", "demoTextFieldSubtitle": "Одна строка для редактирования текста и чисел", "demoTextFieldDescription": "С помощью текстовых полей пользователи могут заполнять формы и вводить данные в диалоговых окнах.", "demoTextFieldShowPasswordLabel": "Показать пароль", "demoTextFieldHidePasswordLabel": "Скрыть пароль", "demoTextFieldFormErrors": "Прежде чем отправлять форму, исправьте ошибки, отмеченные красным цветом.", "demoTextFieldNameRequired": "Введите имя.", "demoTextFieldOnlyAlphabeticalChars": "Используйте только буквы.", "demoTextFieldEnterUSPhoneNumber": "Укажите номер телефона в США в следующем формате: (###) ###-####.", "demoTextFieldEnterPassword": "Введите пароль.", "demoTextFieldPasswordsDoNotMatch": "Пароли не совпадают.", "demoTextFieldWhatDoPeopleCallYou": "Как вас зовут?", "demoTextFieldNameField": "Имя*", "demoBottomSheetButtonText": "ПОКАЗАТЬ НИЖНИЙ ЭКРАН", "demoTextFieldPhoneNumber": "Номер телефона*", "demoBottomSheetTitle": "Нижний экран", "demoTextFieldEmail": "Адрес электронной почты", "demoTextFieldTellUsAboutYourself": "Расскажите о себе (например, какое у вас хобби)", "demoTextFieldKeepItShort": "Не пишите много, это только пример.", "starterAppGenericButton": "КНОПКА", "demoTextFieldLifeStory": "Биография", "demoTextFieldSalary": "Зарплата", "demoTextFieldUSD": "USD", "demoTextFieldNoMoreThan": "Не более 8 символов.", "demoTextFieldPassword": "Пароль*", "demoTextFieldRetypePassword": "Введите пароль ещё раз*", "demoTextFieldSubmit": "ОТПРАВИТЬ", "demoBottomNavigationSubtitle": "Навигация внизу экрана с плавным переходом", "demoBottomSheetAddLabel": "Добавить", "demoBottomSheetModalDescription": "Модальный нижний экран можно использовать вместо меню или диалогового окна. Пока такой экран открыт, пользователю недоступны другие элементы приложения.", "demoBottomSheetModalTitle": "Модальный нижний экран", "demoBottomSheetPersistentDescription": "Постоянный нижний экран показывает дополнительную информацию в приложении. Такой экран всегда остается видимым, даже когда пользователь взаимодействует с другими разделами.", "demoBottomSheetPersistentTitle": "Постоянный нижний экран", "demoBottomSheetSubtitle": "Постоянный и модальный нижние экраны", "demoTextFieldNameHasPhoneNumber": "{name}: {phoneNumber}", "buttonText": "КНОПКА", "demoTypographyDescription": "Определения разных стилей текста в Material Design.", "demoTypographySubtitle": "Все стандартные стили текста", "demoTypographyTitle": "Параметры текста", "demoFullscreenDialogDescription": "Свойство fullscreenDialog определяет, будет ли следующая страница полноэкранным модальным диалоговым окном.", "demoFlatButtonDescription": "При нажатии плоской кнопки отображается цветовой эффект, но кнопка не поднимается. Используйте такие кнопки на панелях инструментов, в диалоговых окнах или как встроенные элементы с полями.", "demoBottomNavigationDescription": "На панели навигации в нижней части экрана можно разместить от трех до пяти разделов. Каждый раздел представлен значком и может иметь текстовую надпись. Если пользователь нажмет на один из значков, то перейдет в соответствующий раздел верхнего уровня.", "demoBottomNavigationSelectedLabel": "Выбранный ярлык", "demoBottomNavigationPersistentLabels": "Постоянные ярлыки", "starterAppDrawerItem": "Пункт {value}", "demoTextFieldRequiredField": "Звездочкой (*) отмечены поля, обязательные для заполнения.", "demoBottomNavigationTitle": "Навигация внизу экрана", "settingsLightTheme": "Светлая", "settingsTheme": "Тема", "settingsPlatformIOS": "iOS", "settingsPlatformAndroid": "Android", "settingsTextDirectionRTL": "Справа налево", "settingsTextScalingHuge": "Очень крупный", "cupertinoButton": "Кнопка", "settingsTextScalingNormal": "Обычный", "settingsTextScalingSmall": "Мелкий", "settingsSystemDefault": "Системные настройки", "settingsTitle": "Настройки", "rallyDescription": "Приложение для планирования бюджета", "aboutDialogDescription": "Чтобы посмотреть код этого приложения, откройте {repoLink}.", "bottomNavigationCommentsTab": "Комментарии", "starterAppGenericBody": "Основной текст", "starterAppGenericHeadline": "Заголовок", "starterAppGenericSubtitle": "Подзаголовок", "starterAppGenericTitle": "Название", "starterAppTooltipSearch": "Поиск", "starterAppTooltipShare": "Поделиться", "starterAppTooltipFavorite": "Избранное", "starterAppTooltipAdd": "Добавить", "bottomNavigationCalendarTab": "Календарь", "starterAppDescription": "Адаптивный макет", "starterAppTitle": "Starter", "aboutFlutterSamplesRepo": "Пример Flutter из хранилища GitHub", "bottomNavigationContentPlaceholder": "Тег для вкладки \"{title}\"", "bottomNavigationCameraTab": "Камера", "bottomNavigationAlarmTab": "Будильник", "bottomNavigationAccountTab": "Банковский счет", "demoTextFieldYourEmailAddress": "Ваш адрес электронной почты", "demoToggleButtonDescription": "С помощью переключателей можно сгруппировать связанные параметры. У группы связанных друг с другом переключателей должен быть общий контейнер.", "colorsGrey": "СЕРЫЙ", "colorsBrown": "КОРИЧНЕВЫЙ", "colorsDeepOrange": "НАСЫЩЕННЫЙ ОРАНЖЕВЫЙ", "colorsOrange": "ОРАНЖЕВЫЙ", "colorsAmber": "ЯНТАРНЫЙ", "colorsYellow": "ЖЕЛТЫЙ", "colorsLime": "ЛАЙМОВЫЙ", "colorsLightGreen": "СВЕТЛО-ЗЕЛЕНЫЙ", "colorsGreen": "ЗЕЛЕНЫЙ", "homeHeaderGallery": "Галерея", "homeHeaderCategories": "Категории", "shrineDescription": "Приложение для покупки стильных вещей", "craneDescription": "Персонализированное приложение для путешествий", "homeCategoryReference": "СТИЛИ И ДРУГОЕ", "demoInvalidURL": "Не удалось открыть URL:", "demoOptionsTooltip": "Параметры", "demoInfoTooltip": "Информация", "demoCodeTooltip": "Код демоверсии", "demoDocumentationTooltip": "Документация по API", "demoFullscreenTooltip": "Полноэкранный режим", "settingsTextScaling": "Масштабирование текста", "settingsTextDirection": "Направление текста", "settingsLocale": "Региональные настройки", "settingsPlatformMechanics": "Платформа", "settingsDarkTheme": "Тёмная", "settingsSlowMotion": "Замедленная анимация", "settingsAbout": "О Flutter Gallery", "settingsFeedback": "Отправить отзыв", "settingsAttribution": "Дизайн: TOASTER, Лондон", "demoButtonTitle": "Кнопки", "demoButtonSubtitle": "Текстовые, приподнятые, контурные и другие", "demoFlatButtonTitle": "Плоская кнопка", "demoRaisedButtonDescription": "Приподнятые кнопки позволяют сделать плоские макеты более объемными, а функции на насыщенных или широких страницах – более заметными.", "demoRaisedButtonTitle": "Приподнятая кнопка", "demoOutlineButtonTitle": "Контурная кнопка", "demoOutlineButtonDescription": "Контурные кнопки при нажатии становятся непрозрачными и поднимаются. Часто они используются вместе с приподнятыми кнопками, чтобы обозначить альтернативное, дополнительное действие.", "demoToggleButtonTitle": "Переключатели", "colorsTeal": "БИРЮЗОВЫЙ", "demoFloatingButtonTitle": "Плавающая командная кнопка", "demoFloatingButtonDescription": "Плавающая командная кнопка – круглая кнопка, которая располагается над остальным контентом и позволяет выделить самое важное действие в приложении.", "demoDialogTitle": "Диалоговые окна", "demoDialogSubtitle": "Обычные, с оповещением и полноэкранные", "demoAlertDialogTitle": "Оповещение", "demoAlertDialogDescription": "Диалоговое окно с оповещением сообщает пользователю о событиях, требующих внимания. Оно может иметь заголовок, а также список доступных действий.", "demoAlertTitleDialogTitle": "Оповещение с заголовком", "demoSimpleDialogTitle": "Обычное", "demoSimpleDialogDescription": "В обычном диалоговом окне пользователю предлагается несколько вариантов на выбор. Если у окна есть заголовок, он располагается над вариантами.", "demoFullscreenDialogTitle": "Полноэкранный режим", "demoCupertinoButtonsTitle": "Кнопки", "demoCupertinoButtonsSubtitle": "Кнопки в стиле iOS", "demoCupertinoButtonsDescription": "Кнопка в стиле iOS. Содержит текст или значок, который исчезает и появляется при нажатии. Может иметь фон.", "demoCupertinoAlertsTitle": "Оповещения", "demoCupertinoAlertsSubtitle": "Диалоговые окна с оповещениями в стиле iOS", "demoCupertinoAlertTitle": "Оповещение", "demoCupertinoAlertDescription": "Диалоговое окно с оповещением сообщает пользователю о событиях, требующих внимания. Оно может иметь заголовок, содержимое, а также список доступных действий. Заголовок располагается над содержимым, а действия – под ним.", "demoCupertinoAlertWithTitleTitle": "Оповещение с заголовком", "demoCupertinoAlertButtonsTitle": "Оповещение с кнопками", "demoCupertinoAlertButtonsOnlyTitle": "Только кнопки из оповещения", "demoCupertinoActionSheetTitle": "Окно действия", "demoCupertinoActionSheetDescription": "Окно действия – тип оповещения, в котором пользователю предлагается как минимум два варианта действий в зависимости от контекста. Окно может иметь заголовок, дополнительное сообщение, а также список действий.", "demoColorsTitle": "Цвета", "demoColorsSubtitle": "Все стандартные цвета", "demoColorsDescription": "Константы для цветов и градиентов, которые представляют цветовую палитру Material Design.", "buttonTextEnabled": "ENABLED", "buttonTextDisabled": "DISABLED", "buttonTextCreate": "Создать", "dialogSelectedOption": "Вы выбрали значение \"{value}\".", "dialogDiscardTitle": "Удалить черновик?", "dialogLocationTitle": "Использовать геолокацию Google?", "dialogLocationDescription": "Отправка анонимных геоданных в Google помогает приложениям точнее определять ваше местоположение. Данные будут отправляться, даже если не запущено ни одно приложение.", "dialogCancel": "ОТМЕНА", "dialogDiscard": "УДАЛИТЬ", "dialogDisagree": "ОТМЕНА", "dialogAgree": "ОК", "dialogSetBackup": "Настройка аккаунта для резервного копирования", "colorsBlueGrey": "СИНЕ-СЕРЫЙ", "dialogShow": "ПОКАЗАТЬ ДИАЛОГОВОЕ ОКНО", "dialogFullscreenTitle": "Диалоговое окно в полноэкранном режиме", "dialogFullscreenSave": "СОХРАНИТЬ", "dialogFullscreenDescription": "Демоверсия диалогового окна в полноэкранном режиме.", "cupertinoButtonEnabled": "Enabled", "cupertinoButtonDisabled": "Disabled", "cupertinoButtonWithBackground": "С фоном", "cupertinoAlertCancel": "Отмена", "cupertinoAlertDiscard": "Удалить", "cupertinoAlertLocationTitle": "Разрешить Картам доступ к вашему местоположению при работе с приложением?", "cupertinoAlertLocationDescription": "Ваше текущее местоположение будет показываться на карте и использоваться для составления маршрутов, выдачи актуальных результатов поиска и расчета времени в пути.", "cupertinoAlertAllow": "Разрешить", "cupertinoAlertDontAllow": "Запретить", "cupertinoAlertFavoriteDessert": "Выберите любимый десерт", "cupertinoAlertDessertDescription": "Выберите свой любимый десерт из списка ниже. На основе выбранного варианта мы настроим список рекомендуемых заведений поблизости.", "cupertinoAlertCheesecake": "Чизкейк", "cupertinoAlertTiramisu": "Тирамису", "cupertinoAlertApplePie": "Яблочный пирог", "cupertinoAlertChocolateBrownie": "Брауни с шоколадом", "cupertinoShowAlert": "Показать оповещение", "colorsRed": "КРАСНЫЙ", "colorsPink": "РОЗОВЫЙ", "colorsPurple": "ФИОЛЕТОВЫЙ", "colorsDeepPurple": "ТЕМНО-ФИОЛЕТОВЫЙ", "colorsIndigo": "ИНДИГО", "colorsBlue": "СИНИЙ", "colorsLightBlue": "СВЕТЛО-ГОЛУБОЙ", "colorsCyan": "ЦИАН", "dialogAddAccount": "Добавить аккаунт", "Gallery": "Галерея", "Categories": "Категории", "SHRINE": "SHRINE", "Basic shopping app": "Приложение для покупок", "RALLY": "RALLY", "CRANE": "CRANE", "Travel app": "Приложение для туристов", "MATERIAL": "МАТЕРИАЛ", "CUPERTINO": "CUPERTINO", "REFERENCE STYLES & MEDIA": "РЕФЕРЕНСЫ И МЕДИА" }
gallery/lib/l10n/intl_ru.arb/0
{ "file_path": "gallery/lib/l10n/intl_ru.arb", "repo_id": "gallery", "token_count": 37814 }
815
{ "loading": "Yuklanmoqda", "deselect": "Tanlovni bekor qilish", "select": "Tanlash", "selectable": "Bosib turib tanlang", "selected": "Tanlandi", "demo": "Demo versiyalar", "bottomAppBar": "Quyi ilovalar paneli", "notSelected": "Tanlanmagan", "demoCupertinoSearchTextFieldTitle": "Qidiruv maydoni", "demoCupertinoPicker": "Tanlash oynasi", "demoCupertinoSearchTextFieldSubtitle": "iOS uslubidagi matn qidirish maydoni", "demoCupertinoSearchTextFieldDescription": "Foydalanuvchiga matn kiritish orqali qidirish imkonini beruvchi va takliflarni taklif qilishi va filtrlashi mumkin boʻlgan qidiruv matn maydoni.", "demoCupertinoSearchTextFieldPlaceholder": "Matn kiriting", "demoCupertinoScrollbarTitle": "Aylantirish paneli", "demoCupertinoScrollbarSubtitle": "iOS uslubidagi aylantirish paneli", "demoCupertinoScrollbarDescription": "Berilgan asosiy elementni qamrab oluvchi aylantirish paneli", "demoTwoPaneItem": "{value} obyekti", "demoTwoPaneList": "Roʻyxat", "demoTwoPaneFoldableLabel": "Buklanadigan", "demoTwoPaneSmallScreenLabel": "Kichik ekran", "demoTwoPaneSmallScreenDescription": "TwoPane kichik ekranli qurilmada shunday ishlaydi.", "demoTwoPaneTabletLabel": "Planshet/Kompyuter", "demoTwoPaneTabletDescription": "TwoPane planshet yoki kompyuter kabi kichik ekranli qurilmada shunday ishlaydi.", "demoTwoPaneTitle": "TwoPane", "demoTwoPaneSubtitle": "Buklanadigan, katta yoki kichik ekranli qurilmalarda moslashuvchan dizayn.", "splashSelectDemo": "Demo rejimni tanlang", "demoTwoPaneFoldableDescription": "TwoPane buklanadigan qurilmada shunday ishlaydi.", "demoTwoPaneDetails": "Batafsil", "demoTwoPaneSelectItem": "Obyektni tanlang", "demoTwoPaneItemDetails": "{value} obyekti tafsilotlari", "demoCupertinoContextMenuActionText": "Kontekst menyusini koʻrish uchun Flutter logotipini bosib turing.", "demoCupertinoContextMenuDescription": "Element uzoq bosilganda chiqadigan iOS uslubidagi butun ekranli kontekst menyusi.", "demoAppBarTitle": "Ilova paneli", "demoAppBarDescription": "Ilova paneli joriy ekranga tegishli kontent va amallarni taqdim etadi. U brending, ekran nomlari, navigatsiya va harakatlar uchun ishlatiladi", "demoDividerTitle": "Ajratkich", "demoDividerSubtitle": "Ajratkich kontentni roʻyxatlar va tartiblarda guruhlaydigan ingichka chiziq.", "demoDividerDescription": "Ajratkichdan kontentni ajratish uchun roʻyxatlarda, chizmalarda va boshqa joylarda ishlatish mumkin.", "demoVerticalDividerTitle": "Vertikal ajratkich", "demoCupertinoContextMenuTitle": "Kontekst menyusi", "demoCupertinoContextMenuSubtitle": "iOS uslubidagi kontekst menyusi", "demoAppBarSubtitle": "Joriy ekranga tegishli maʼlumot va amallarni koʻrsatadi", "demoCupertinoContextMenuActionOne": "Birinchi amal", "demoCupertinoContextMenuActionTwo": "Ikkinchi amal", "demoDateRangePickerDescription": "Material Design uslubidagi oyna orqali sana oraligʻini tanlash mumkin.", "demoDateRangePickerTitle": "Sana oraligʻini tanlagich", "demoNavigationDrawerUserName": "Foydalanuvchi nomi", "demoNavigationDrawerUserEmail": "[email protected]", "demoNavigationDrawerText": "Tortma panelni chiqarish uchun chetgan suring yoki yuqori chap burchakdagi belgi ustiga bosing", "demoNavigationRailTitle": "Yon navigatsiya paneli", "demoNavigationRailSubtitle": "Ilova ichida yon navigatsiya panelini chiqarish", "demoNavigationRailDescription": "Ilovaning chap yoki oʻng tomonida chiqadigan, odatda uchdan beshtagacha koʻrishlar soni boʻyicha harakatlanish imkonini beruvchi Material Design uslubidagi vidjet.", "demoNavigationRailFirst": "Birinchi", "demoNavigationDrawerTitle": "Navigatsiya paneli", "demoNavigationRailThird": "Uchinchi", "replyStarredLabel": "Yulduzchali", "demoTextButtonDescription": "Matnli tugmalarni bossangiz, ular koʻtarilmaydi. Uning oʻrniga siyohli dogʻ paydo boʻladi. Bu tugmalardan asboblar panelida va muloqot oynalarida foydalaning yoki ularni maydonga kiriting", "demoElevatedButtonTitle": "Koʻtarilgan tugma", "demoElevatedButtonDescription": "Koʻtarilgan tugmalar yassi maketni qavariqli qilish imkonini beradi. Katta va keng sahifalarda koʻzga tez tashlanadigan boʻladi", "demoOutlinedButtonTitle": "Chegarali tugma", "demoOutlinedButtonDescription": "Chegarali tugmani bosganda shaffof boʻladi va koʻtariladi. Ular odatda qavariq tugmalar bilan biriktiriladi va ikkinchi harakat, yaʼni muqobilini koʻrsatish uchun ishlatiladi.", "demoContainerTransformDemoInstructions": "Bildirgilar, roʻyxatlar va suzuvchi harakat tugmalari", "demoNavigationDrawerSubtitle": "Ilovalar panelida tortma panelni chiqarish", "replyDescription": "Samarali muloqot uchun email ilovasi", "demoNavigationDrawerDescription": "Ekranning chetidan siljitiladigan va ilovaning navigatsiya havolalarini oʻz ichiga olgan gorizontal Material Design paneli.", "replyDraftsLabel": "Qoralamalar", "demoNavigationDrawerToPageOne": "Birinchisi", "replyInboxLabel": "Kiruvchi", "demoSharedXAxisDemoInstructions": "Keyingisi va orqaga tugmalari", "replySpamLabel": "Spam", "replyTrashLabel": "Chiqitdon", "replySentLabel": "Yuborilgan", "demoNavigationRailSecond": "Ikkinchi", "demoNavigationDrawerToPageTwo": "Ikkinchisi", "demoFadeScaleDemoInstructions": "Modal va suzuvchi harakat tugmalari", "demoFadeThroughDemoInstructions": "Ekran pastidagi navigatsiya", "demoSharedZAxisDemoInstructions": "Sozlamalar tugmasi", "demoSharedYAxisDemoInstructions": "“Yaqinda tinglangan” filtri bilan saralash", "demoTextButtonTitle": "Matnli tugma", "demoSharedZAxisBeefSandwichRecipeTitle": "Mol goʻshtli sendvich", "demoSharedZAxisDessertRecipeDescription": "Desert retsepti", "demoSharedYAxisAlbumTileSubtitle": "Ijrochi", "demoSharedYAxisAlbumTileTitle": "Albom", "demoSharedYAxisRecentSortTitle": "Yaqinda tinglangan", "demoSharedYAxisAlphabeticalSortTitle": "A–Z", "demoSharedYAxisAlbumCount": "268 ta albom", "demoSharedYAxisTitle": "Umumiy Y oʻqi", "demoSharedXAxisCreateAccountButtonText": "HISOB YARATISH", "demoFadeScaleAlertDialogDiscardButton": "RAD ETISH", "demoSharedXAxisSignInTextFieldLabel": "Email manzili yoki telefon raqami", "demoSharedXAxisSignInSubtitleText": "Hisobingiz bilan kiring", "demoSharedXAxisSignInWelcomeText": "Salom, David Park!", "demoSharedXAxisIndividualCourseSubtitle": "Alohida koʻrsatilgan", "demoSharedXAxisBundledCourseSubtitle": "Majmuada", "demoFadeThroughAlbumsDestination": "Albomlar", "demoSharedXAxisDesignCourseTitle": "Dizayn", "demoSharedXAxisIllustrationCourseTitle": "Tasvir", "demoSharedXAxisBusinessCourseTitle": "Biznes", "demoSharedXAxisArtsAndCraftsCourseTitle": "Sanʼat va hunarmandchilik", "demoMotionPlaceholderSubtitle": "Qoʻshimcha matn", "demoFadeScaleAlertDialogCancelButton": "BEKOR QILISH", "demoFadeScaleAlertDialogHeader": "Ogohlantiruvchi muloqot oynasi", "demoFadeScaleHideFabButton": "SUZUVCHI HARAKAT TUGMASINI BERKITISH", "demoFadeScaleShowFabButton": "SUZUVCHI HARAKAT TUGMASINI CHIQARISH", "demoFadeScaleShowAlertDialogButton": "MODAL OYNANI CHIQARISH", "demoFadeScaleDescription": "Bu effekt ekran chetlarida paydo boʻladigan yoki yoʻqoladigan foydalanuvchi interfeysi elementlari uchun ishlatiladi.", "demoFadeScaleTitle": "Shaffoflashuv", "demoFadeThroughTextPlaceholder": "123 ta surat", "demoFadeThroughSearchDestination": "Qidiruv", "demoFadeThroughPhotosDestination": "Suratlar", "demoSharedXAxisCoursePageSubtitle": "Turkumlar majmuasi tasmada guruh sifatida chiqadi. Buni istalgan vaqt oʻzgartirish mumkin.", "demoFadeThroughDescription": "Silliq oʻzgarish bir-biriga kuchli aloqasi boʻlmagan foydalanuvchi interfeysi elementlari orasidagi oʻtishlarga moʻljallangan.", "demoFadeThroughTitle": "Shaffof almashinuv", "demoSharedZAxisHelpSettingLabel": "Yordam", "demoMotionSubtitle": "Barcha standart oʻtishlar", "demoSharedZAxisNotificationSettingLabel": "Bildirishnomalar", "demoSharedZAxisProfileSettingLabel": "Profil", "demoSharedZAxisSavedRecipesListTitle": "Saqlangan retseptlar", "demoSharedZAxisBeefSandwichRecipeDescription": "Mol goʻshtli sendvich retsepti", "demoSharedZAxisCrabPlateRecipeDescription": "Qisqichbaqali taom retsepti", "demoSharedXAxisCoursePageTitle": "Kurslarni tartiblang", "demoSharedZAxisCrabPlateRecipeTitle": "Qisqichbaqa", "demoSharedZAxisShrimpPlateRecipeDescription": "Krevetkali taom retsepti", "demoSharedZAxisShrimpPlateRecipeTitle": "Krevetka", "demoContainerTransformTypeFadeThrough": "SHAFFOF ALMASHINUV", "demoSharedZAxisDessertRecipeTitle": "Desert", "demoSharedZAxisSandwichRecipeDescription": "Sendvich retsepti", "demoSharedZAxisSandwichRecipeTitle": "Sendvich", "demoSharedZAxisBurgerRecipeDescription": "Burger retsepti", "demoSharedZAxisBurgerRecipeTitle": "Burger", "demoSharedZAxisSettingsPageTitle": "Sozlamalar", "demoSharedZAxisTitle": "Umumiy Z oʻqi", "demoSharedZAxisPrivacySettingLabel": "Maxfiylik", "demoMotionTitle": "Harakat", "demoContainerTransformTitle": "Konteyner bilan oʻzgartirish", "demoContainerTransformDescription": "Konteyner bilan oʻzgartirish konteynerdan iborat foydalanuvchi interfeysi elementlari orasidagi oʻtishlarga moʻljallangan. Bu effekt interfeysning ikki elementi orasiga koʻrinarli aloqa oʻrnatadi.", "demoContainerTransformModalBottomSheetTitle": "Shaffoflashuv rejimi", "demoContainerTransformTypeFade": "SHAFFOFLASHUV", "demoSharedYAxisAlbumTileDurationUnit": "daqiqa", "demoMotionPlaceholderTitle": "Nomi", "demoSharedXAxisForgotEmailButtonText": "EMAIL MANZILINGIZNI UNUTDINGIZMI?", "demoMotionSmallPlaceholderSubtitle": "Qoʻshimcha", "demoMotionDetailsPageTitle": "Tafsilotlar sahifasi", "demoMotionListTileTitle": "Roʻyxat bandi", "demoSharedAxisDescription": "Umumiy oʻqlar effekti bitta oʻqda joylashgan foydalanuvchi interfeysi elementlari orasidagi oʻtishlarga moʻljallangan. Elementlar orasidagi aloqani mustahkamlash uchun X, Y yoki Z oʻqlari boʻyicha oʻzaro oʻzgartirish qoʻllaniladi.", "demoSharedXAxisTitle": "Umumiy X oʻqi", "demoSharedXAxisBackButtonText": "ORQAGA", "demoSharedXAxisNextButtonText": "KEYINGISI", "demoSharedXAxisCulinaryCourseTitle": "Kulinariya", "githubRepo": "{repoName} GitHub repozitoriysi", "fortnightlyMenuUS": "AQSH", "fortnightlyMenuBusiness": "Biznes", "fortnightlyMenuScience": "Ilm-fan", "fortnightlyMenuSports": "Sport", "fortnightlyMenuTravel": "Sayohat", "fortnightlyMenuCulture": "Madaniyat", "fortnightlyTrendingTechDesign": "TexDizayn", "rallyBudgetDetailAmountLeft": "Qolgan summa", "fortnightlyHeadlineArmy": "Yashil armiyalardagi ichki islohatlar", "fortnightlyDescription": "Eng muhim yangiliklar haqidagi ilova", "rallyBillDetailAmountDue": "Qarz miqdori", "rallyBudgetDetailTotalCap": "Budjet miqdori", "rallyBudgetDetailAmountUsed": "Ishlatilgan summa", "fortnightlyTrendingHealthcareRevolution": "Salomatlik inqiloblari", "fortnightlyMenuFrontPage": "Bosh sahifa", "fortnightlyMenuWorld": "Dunyo", "rallyBillDetailAmountPaid": "Toʻlangan summa", "fortnightlyMenuPolitics": "Siyosat", "fortnightlyHeadlineBees": "Fermalardagi arilar taʼminoti yetishmayapti", "fortnightlyHeadlineGasoline": "Benzin kelajagi", "fortnightlyTrendingGreenArmy": "Yashil beretlar", "fortnightlyHeadlineFeminists": "Feministlar partizanlikka oʻtmoqda", "fortnightlyHeadlineFabrics": "Dizaynerlar futuristik liboslar yaratishda foydalanadigan texnologiyalar", "fortnightlyHeadlineStocks": "Aksiya stagnatsiyalari, valyutalar narxi", "fortnightlyTrendingReform": "Islohatlar", "fortnightlyMenuTech": "Texnologiya", "fortnightlyHeadlineWar": "Urush vaqtidagi amerika boʻlinmalari", "fortnightlyHeadlineHealthcare": "Urushlarsiz, sogʻliqni saqlashdagi yutuqlar", "fortnightlyLatestUpdates": "Soʻngi xabarlar", "fortnightlyTrendingStocks": "Aksiyalar", "rallyBillDetailTotalAmount": "Jami miqdori", "demoCupertinoPickerDateTime": "Sana va vaqt", "signIn": "KIRISH", "dataTableRowWithSugar": "{value} shakar bilan", "dataTableRowApplePie": "Olmali pirog", "dataTableRowDonut": "Yogʻli kulcha", "dataTableRowHoneycomb": "Asalari uyasi", "dataTableRowLollipop": "Obakidandon", "dataTableRowJellyBean": "Marmeladli draje", "dataTableRowGingerbread": "Shirin kulchalar", "dataTableRowCupcake": "Keks", "dataTableRowEclair": "Ekler", "dataTableRowIceCreamSandwich": "Muzqaymoqli sendvich", "dataTableRowFrozenYogurt": "Muzlatilgan yogurt", "dataTableColumnIron": "Temir (%)", "dataTableColumnCalcium": "Kalsiy (%)", "dataTableColumnSodium": "Natriy (mg)", "demoTimePickerTitle": "Vaqt tanlash oynasi", "demo2dTransformationsResetTooltip": "Transformatsiyalarni tiklash", "dataTableColumnFat": "Yogʻlar ( g)", "dataTableColumnCalories": "Kaloriya", "dataTableColumnDessert": "Desert (1 porsiya)", "cardsDemoTravelDestinationLocation1": "Thanjavur, Tamilnadu", "demoTimePickerDescription": "Material Design uslubidagi oyna orqali vaqtni tanlash mumkin.", "demoPickersShowPicker": "TANLASH OYNASINI CHIQARISH", "demoTabsScrollingTitle": "Aylantirish", "demoTabsNonScrollingTitle": "Aylantirilmasin", "craneHours": "{hours,plural,=1{1 soat}other{{hours} soat}}", "craneMinutes": "{minutes,plural,=1{1 daqiqa}other{{minutes} daqiqa}}", "craneFlightDuration": "{hoursShortForm} {minutesShortForm}", "dataTableHeader": "Ovqatlanish", "demoDatePickerTitle": "Sana tanlash oynasi", "demoPickersSubtitle": "Sana va vaqtni tanlash", "demoPickersTitle": "Tanlash oynasi", "demo2dTransformationsEditTooltip": "Katakchani tahrirlash", "demoDataTableDescription": "Jadvaldagi maʼlumotlar ustun va qatorlar boʻyicha ajratilgan. Bu foydalanuvchiga kerakli axborotni tezroq topish va taqdim etilgan variantlarni taqqoslash imkonini beradi.", "demo2dTransformationsDescription": "Katakchalarni tahrirlash uchun bosing va sahnalarga surish uchun ishoralardan foydalaning. Panoramalash uchun suring, miqyosni oʻzgartirish uchun chimding, ikkita barmoq yordamida buring. Dastlabki joylashuviga qaytarish uchun tiklash tugmasini bosing.", "demo2dTransformationsSubtitle": "Panorama, masshtab, burish", "demo2dTransformationsTitle": "2D transformatsiya", "demoCupertinoTextFieldPIN": "PIN kod", "demoCupertinoTextFieldDescription": "Matn maydonchasiga tashqi yoki ekran klaviaturasi yordamida matn kiritish mumkin.", "demoCupertinoTextFieldSubtitle": "iOS uslubidagi matn maydonchasi", "demoCupertinoTextFieldTitle": "Matn maydonchalari", "demoDatePickerDescription": "Material Design uslubidagi oyna orqali sanani tanlash mumkin.", "demoCupertinoPickerTime": "Vaqt", "demoCupertinoPickerDate": "Sana", "demoCupertinoPickerTimer": "Taymer", "demoCupertinoPickerDescription": "iOS uslubidagi tanlash oynasi orqali qator, sana va vaqtni sozlash mumkin.", "demoCupertinoPickerSubtitle": "iOS uslubidagi tanlash oynasi", "demoCupertinoPickerTitle": "Tanlash oynasi", "dataTableRowWithHoney": "{value} asal bilan", "cardsDemoTravelDestinationCity2": "Chettinad", "bannerDemoResetText": "Bannerni yana bir marta chiqarish", "bannerDemoMultipleText": "Bir nechta amal", "bannerDemoLeadingText": "Matn ustidagi belgi", "dismiss": "YOPISH", "cardsDemoTappable": "Bosing", "cardsDemoSelectable": "Bosib turib tanlang", "cardsDemoExplore": "Ochish", "cardsDemoExploreSemantics": "Ochish: {destinationName}", "cardsDemoShareSemantics": "Ulashish: {destinationName}", "cardsDemoTravelDestinationTitle1": "Tamilnadu hududidagi 10 ta borish tavsiya qilinadigan shahar", "cardsDemoTravelDestinationDescription1": "10 raqami", "cardsDemoTravelDestinationCity1": "Thanjavur", "dataTableColumnProtein": "Oqsillar ( g)", "cardsDemoTravelDestinationTitle2": "Janubiy Hindiston sanʼat ustalari", "cardsDemoTravelDestinationDescription2": "Ipak yigiruvchilar", "bannerDemoText": "Boshqa qurilmangizda parolingiz yangilandi. Tizimga qaytadan kiring.", "cardsDemoTravelDestinationLocation2": "Sivaganga, Tamilnadu", "cardsDemoTravelDestinationTitle3": "Brihadisvaradagi ibodatxona", "cardsDemoTravelDestinationDescription3": "Ibodatxonalar", "demoBannerTitle": "Banner", "demoBannerSubtitle": "Banner roʻyxat ichida chiqmoqda", "demoBannerDescription": "Bannerda qisqa, lekin kerakli axborot boʻladi. Bundan tashqari foydalanuvchi bajarilishi lozim boʻlgan amal joylashadi. Uni foydalanuvchi ekrandan olib tashlay oladi.", "demoCardTitle": "Bildirgilar", "demoCardSubtitle": "Burchaklari oʻralgan pastda joylashgan bildirgilar", "demoCardDescription": "Bildirgiga qoʻshimcha axborot joylash mumkin, masalan, albom, taom, joylashuv va kontaktlar haqidagi axborotlarni.", "demoDataTableTitle": "Maʼlumotlar keltirilgan jadvallar", "demoDataTableSubtitle": "Jadval koʻrinishidagi maʼlumotlar", "dataTableColumnCarbs": "Uglevodlar (g)", "placeTanjore": "Tanjore", "demoGridListsTitle": "Jadval shaklidagi roʻyxatlar", "placeFlowerMarket": "Gul bozori", "placeBronzeWorks": "Bronzadan mahsulot ishlab chiqaradigan zavod", "placeMarket": "Bozor", "placeThanjavurTemple": "Thanjavurdagi ibodatxona", "placeSaltFarm": "Tuz fermasi", "placeScooters": "Skuterchilar", "placeSilkMaker": "Ipak fabrikasida ishchi", "placeLunchPrep": "Tushlikni tayyorlash", "placeBeach": "Sohil", "placeFisherman": "Baliqchi", "demoMenuSelected": "Tanlangan qiymat: {value}", "demoMenuRemove": "Olib tashlash", "demoMenuGetLink": "Havolani olish", "demoMenuShare": "Ulashish", "demoBottomAppBarSubtitle": "Navigatsiya va amallar ekranning quyi qismida chiqadi", "demoMenuAnItemWithASectionedMenu": "Qismli menyusi bor obyekt", "demoMenuADisabledMenuItem": "Menyuning faolsizlantirilgan bandi", "demoLinearProgressIndicatorTitle": "Chiziqli jarayon indikatori", "demoMenuContextMenuItemOne": "Kontekst menyusining birinchi bandi", "demoMenuAnItemWithASimpleMenu": "Oddiy menyuli obyekt", "demoCustomSlidersTitle": "Maxsus slayderlar", "demoMenuAnItemWithAChecklistMenu": "Nazoratli roʻyxatlari bor menyuli obyekt", "demoCupertinoActivityIndicatorTitle": "Faollik indikatori", "demoCupertinoActivityIndicatorSubtitle": "iOS uslubidagi faollik indikatori", "demoCupertinoActivityIndicatorDescription": "Soatga teskari aylanadigan iOS uslubidagi faollik indikatori.", "demoCupertinoNavigationBarTitle": "Navigatsiya paneli", "demoCupertinoNavigationBarSubtitle": "iOS uslubidagi navigatsiya paneli", "demoCupertinoNavigationBarDescription": "iOS uslubidagi navigatsiya paneli – asboblar panelining oʻrtasida sahifaning nomi minimal joylashgan panel.", "demoCupertinoPullToRefreshTitle": "Yangilash uchun torting", "demoCupertinoPullToRefreshSubtitle": "Sahifalarni yangilash uchun iOS uslubidagi boshqaruv", "demoCupertinoPullToRefreshDescription": "Sahifani yangilash uchun tepadan pastga tortiladigan iOS uslubidagi boshqaruv.", "demoProgressIndicatorTitle": "Jarayon indikatorlari", "demoProgressIndicatorSubtitle": "Chiziqli, doirasimon va noaniq", "demoCircularProgressIndicatorTitle": "Doirasimon jarayon indikatori", "demoCircularProgressIndicatorDescription": "MD uslubidagi doirasimon jarayon indikatori, ilova bandligini aylantirib tasvirlaydi.", "demoMenuFour": "Toʻrt", "demoLinearProgressIndicatorDescription": "MD uslubidagi chiziqli jarayon indikatori holat paneli deb ham ataladi.", "demoTooltipTitle": "Qalqib chiquvchi maslahat oynalari", "demoTooltipSubtitle": "Bosib turganda yoki kursorni ustiga olib borganda chiqadigan qisqa xabar", "demoTooltipDescription": "Qalqib chiquvchi maslahat oynalari tugmalar va interfeysdagi boshqa elementlarni qanday ishlashini tushunishda yordam beradi. Element bosib turilganda, kursor uning ustiga olib borilganda yoki .unga kirilganda chiqadi.", "demoTooltipInstructions": "Qalqib chiquvchi maslahat oynasi chiqishi uchun bosib turing yoki kursorni ustiga olib boring.", "placeChennai": "Chennay", "demoMenuChecked": "Belgilangan qiymat: {value}", "placeChettinad": "Chettinad", "demoMenuPreview": "Razm solish", "demoBottomAppBarTitle": "Quyi ilovalar paneli", "demoBottomAppBarDescription": "Quyi ilovalar panelida navigatsiya paneli va toʻrttagacha amal joylash mumkin, jumladan, erkin harakatlanuvchi amal tugmasini ham.", "bottomAppBarNotch": "Kesim", "bottomAppBarPosition": "Erkin harakatlanuvchi amal tugmasi joylashuvi", "bottomAppBarPositionDockedEnd": "Chekkaga mahkamlangan", "bottomAppBarPositionDockedCenter": "Markazga mahkamlangan", "bottomAppBarPositionFloatingEnd": "Chekkada erkin harakatlanuvchi", "bottomAppBarPositionFloatingCenter": "Markazda erkin harakatlanuvchi", "demoSlidersEditableNumericalValue": "Raqamli qiymatlari tahrirlanuvchi", "demoGridListsSubtitle": "Qator va ustunlar maketi", "demoGridListsDescription": "Jadval shaklidagi roʻyxatlar bir turdagi maʼlumotlarni koʻrsatish uchun juda qulay. Masalan, rasmlarni. Bunday roʻyxatga kiritilgan obyektlar elementlar deyiladi.", "demoGridListsImageOnlyTitle": "Faqat rasm", "demoGridListsHeaderTitle": "Sarlavha bilan", "demoGridListsFooterTitle": "Quyi sarlavha bilan", "demoSlidersTitle": "Slayderlar", "demoSlidersSubtitle": "Qiymat svayplash orqali tanlanadigan vidjetlar", "demoSlidersDescription": "Slayderlar yordamida berilgan diapazondagi kerakli qiymatni tanlash mumkin. Ular bilan tovush balandligi, yorqinlik yoki tasvir filtrlarini ham sozlash mumkin.", "demoRangeSlidersTitle": "Diapazonli slayderlar", "demoRangeSlidersDescription": "Slayderlar yordamida berilgan diapazondagi kerakli qiymatni tanlash mumkin. Slayderlarning ikkala uchida yaqqol qiymatlarni anglatuvchi belgilar bo‘lishi mumkin Ular bilan tovush balandligi, yorqinlik yoki tasvir filtrlarini ham sozlash mumkin.", "demoMenuAnItemWithAContextMenuButton": "Kontekst menyuli obyekt", "demoCustomSlidersDescription": "Slayderlar yordamida berilgan diapazondagi kerakli qiymat yoki qiymatlar diapazonini tanlash mumkin. Slayderlar maxsus dizaynda va moslashtirilgan ham boʻladi.", "demoSlidersContinuousWithEditableNumericalValue": "Raqamli qiymatlari tahrirlanuvchi uzluksiz slayder", "demoSlidersDiscrete": "Diskret", "demoSlidersDiscreteSliderWithCustomTheme": "Maxsus dizaynli diskret slayder", "demoSlidersContinuousRangeSliderWithCustomTheme": "Maxsus dizaynli uzluksiz diapazonli slayder", "demoSlidersContinuous": "Uzluksiz", "placePondicherry": "Pondicherri", "demoMenuTitle": "Menyu", "demoContextMenuTitle": "Kontekst menyusi", "demoSectionedMenuTitle": "Qismli menyular", "demoSimpleMenuTitle": "Oddiy menyu", "demoChecklistMenuTitle": "Nazoratli roʻyxatlar menyusi", "demoMenuSubtitle": "Menyu tugmalari va oddiy menyular", "demoMenuDescription": "Menyuda alohida blokda joylashgan variantlar roʻyxati mavjud boʻladi. Foydalanuvchi tugmaga bosganda, biror amalni bajarganda yoki boshqa boshqaruv elementlaridan foydalanganda roʻyxat chiqadi.", "demoMenuItemValueOne": "Menyuning birinchi bandi", "demoMenuItemValueTwo": "Menyuning ikkinchi bandi", "demoMenuItemValueThree": "Menyuning uchinchi bandi", "demoMenuOne": "Bir", "demoMenuTwo": "Ikki", "demoMenuThree": "Uch", "demoMenuContextMenuItemThree": "Kontekst menyusining uchinchi bandi", "demoCupertinoSwitchSubtitle": "iOS uslubidagi kalit", "demoSnackbarsText": "Bu – snekbar.", "demoCupertinoSliderSubtitle": "iOS uslubidagi slayder", "demoCupertinoSliderDescription": "Slayder uzluksiz yoki diskret qiymatlarni tanlashda ishlatiladi.", "demoCupertinoSliderContinuous": "Uzluksiz: {value}", "demoCupertinoSliderDiscrete": "Diskret: {value}", "demoSnackbarsAction": "Snekbar amalini bosdingiz.", "backToGallery": "Galereyaga qaytish", "demoCupertinoTabBarTitle": "Varaqlar paneli", "demoCupertinoSwitchDescription": "Kalit tugma biror sozlamani yoqishi yoki faolsizlantirishi mumkin.", "demoSnackbarsActionButtonLabel": "AMAL", "cupertinoTabBarProfileTab": "Profil", "demoSnackbarsButtonLabel": "SNEKBARNI CHIQARISH", "demoSnackbarsDescription": "Snekbarlar foydalanuvchilarga ilovaning amali yoki jarayoni haqida xabar qiladi. Ular ekranning quyi qismida vaqtincha chiqadi. Snekbarlar foydalanishga xalaqit qilmasligi kerak va bezovta qilmasdan yopilish kerak.", "demoSnackbarsSubtitle": "Snekbarlar ekranning quyi qismida xabarlar chiqaradi", "demoSnackbarsTitle": "Snekbarlar", "demoCupertinoSliderTitle": "Slayder", "cupertinoTabBarChatTab": "Chat", "cupertinoTabBarHomeTab": "Boshi", "demoCupertinoTabBarDescription": "iOS uslubidagi quyi navigatsiya varaqlari paneli Bir nechta faol varaqlarni chiqaradi va birinchi varaq asosiy hisoblanadi.", "demoCupertinoTabBarSubtitle": "iOS uslubidagi varaqlar paneli", "demoOptionsFeatureTitle": "Variantlarni koʻrish", "demoOptionsFeatureDescription": "Mavjud variantlarni koʻrish uchun bu yerga bosing.", "demoCodeViewerCopyAll": "HAMMASINI NUSXALASH", "shrineScreenReaderRemoveProductButton": "Olib tashlash: {product}", "shrineScreenReaderProductAddToCart": "Savatga joylash", "shrineScreenReaderCart": "{quantity,plural,=0{Savatchaga hech nima joylanmagan}=1{Savatchada 1 ta mahsulot}other{Savatchada {quantity} ta mahsulot}}", "demoCodeViewerFailedToCopyToClipboardMessage": "Klipbordga nusxalanmadi: {error}", "demoCodeViewerCopiedToClipboardMessage": "Klipbordga nusxalandi.", "craneSleep8SemanticLabel": "Sohil tepasidagi Maya vayronalari", "craneSleep4SemanticLabel": "Togʻlar bilan oʻralgan soy boʻyidagi mehmonxona", "craneSleep2SemanticLabel": "Machu Pikchu qalʼasi", "craneSleep1SemanticLabel": "Qishloqdagi qorli yam-yashil daraxtlar bagʻridagi uy", "craneSleep0SemanticLabel": "Suv ustidagi bir qavatli imorat", "craneFly13SemanticLabel": "Dengiz boʻyidagi palmalari bor hovuz", "craneFly12SemanticLabel": "Atrofida palmalari bor hovuz", "craneFly11SemanticLabel": "Dengiz boʻyidagi gʻishtdan qurilgan mayoq", "craneFly10SemanticLabel": "Kun botayotganda Al-Azhar masjidi minoralari", "craneFly9SemanticLabel": "Eski koʻk avtomobilga suyanib turgan odam", "craneFly8SemanticLabel": "Superdaraxtzor", "craneEat9SemanticLabel": "Pishiriqli kafe peshtaxtasi", "craneEat2SemanticLabel": "Burger", "craneFly5SemanticLabel": "Togʻlar bilan oʻralgan soy boʻyidagi mehmonxona", "demoSelectionControlsSubtitle": "Belgilash katakchalari, radio tugmalar va almashtirgichlar", "craneEat10SemanticLabel": "Pastromali katta sendvich ushlab turgan ayol", "craneFly4SemanticLabel": "Suv ustidagi bir qavatli imorat", "craneEat7SemanticLabel": "Nonvoyxonaga kirish qismi", "craneEat6SemanticLabel": "Krevetkali taom", "craneEat5SemanticLabel": "Ijodkorlar restoranidagi oʻtirish joyi", "craneEat4SemanticLabel": "Shokoladli desert", "craneEat3SemanticLabel": "Koreyscha tako", "craneFly3SemanticLabel": "Machu Pikchu qalʼasi", "craneEat1SemanticLabel": "Baland stullari bor boʻsh bar", "craneEat0SemanticLabel": "Yogʻoch oʻtinli oʻchoqdagi pitsa", "craneSleep11SemanticLabel": "Taypey 101 minorasi", "craneSleep10SemanticLabel": "Kun botayotganda Al-Azhar masjidi minoralari", "craneSleep9SemanticLabel": "Dengiz boʻyidagi gʻishtdan qurilgan mayoq", "craneEat8SemanticLabel": "Qisqichbaqalar likopchasi", "craneSleep7SemanticLabel": "Riberiya maydonidagi rang-barang xonadonlar", "craneSleep6SemanticLabel": "Atrofida palmalari bor hovuz", "craneSleep5SemanticLabel": "Daladagi chodir", "settingsButtonCloseLabel": "Sozlamalarni yopish", "demoSelectionControlsCheckboxDescription": "Belgilash katakchasi bilan foydalanuvchi roʻyxatdagi bir nechta elementni tanlay oladi. Katakchalar ikki qiymatda boʻladi, ayrim vaqtlarda uchinchi qiymat ham ishlatiladi.", "settingsButtonLabel": "Sozlamalar", "demoListsTitle": "Roʻyxatlar", "demoListsSubtitle": "Skrollanuvchi roʻyxat maketlari", "demoListsDescription": "Balandligi mahkamlangan va odatda boshida yoki oxirida rasm aks etuvchi matnlardan iborat boʻladi.", "demoOneLineListsTitle": "Bir qator", "demoTwoLineListsTitle": "Ikki qator", "demoListsSecondary": "Quyi matn", "demoSelectionControlsTitle": "Tanlov boshqaruvi", "craneFly7SemanticLabel": "Rashmor togʻi", "demoSelectionControlsCheckboxTitle": "Belgilash katakchasi", "craneSleep3SemanticLabel": "Eski koʻk avtomobilga suyanib turgan odam", "demoSelectionControlsRadioTitle": "Radiotugma", "demoSelectionControlsRadioDescription": "Radiotugma faqat bir tanlov imkonini beradi. Ular mavjud tanlovlarni bir roʻyxatda chiqarish uchun qulay.", "demoSelectionControlsSwitchTitle": "Almashtirgich", "demoSelectionControlsSwitchDescription": "Almashtirgich tugmasi yordamida foydalanuvchilar biror sozlamani yoqishi yoki faolsizlantirishi mumkin. Almashtirgich yonida doim sozlama nomi va holati chiqadi.", "craneFly0SemanticLabel": "Qishloqdagi qorli yam-yashil daraxtlar bagʻridagi uy", "craneFly1SemanticLabel": "Daladagi chodir", "craneFly2SemanticLabel": "Qorli togʻ bagʻridagi ibodat bayroqlari", "craneFly6SemanticLabel": "Nafis saʼnat saroyining osmondan koʻrinishi", "rallySeeAllAccounts": "Barcha hisoblar", "rallyBillAmount": "{billName} uchun {date} sanasigacha {amount} toʻlash kerak.", "shrineTooltipCloseCart": "Savatchani yopish", "shrineTooltipCloseMenu": "Menyuni yopish", "shrineTooltipOpenMenu": "Menyuni ochish", "shrineTooltipSettings": "Sozlamalar", "shrineTooltipSearch": "Qidiruv", "demoTabsDescription": "Varaqlarda turli ekranlardagi kontent, axborot toʻplamlari va boshqa amallar jamlanadi.", "demoTabsSubtitle": "Alohida aylantiriladigan varaqlar", "demoTabsTitle": "Varaqlar", "rallyBudgetAmount": "{budgetName} uchun ajratilgan {amountTotal} dan {amountUsed} ishlatildi, qolgan balans: {amountLeft}", "shrineTooltipRemoveItem": "Elementni olib tashlash", "rallyAccountAmount": "{accountNumber} raqamli {accountName} hisobida {amount} bor.", "rallySeeAllBudgets": "Barcha budjetlar", "rallySeeAllBills": "Hisob-varaqlari", "craneFormDate": "Sanani tanlang", "craneFormOrigin": "Boshlangʻich manzilni tanlang", "craneFly2": "Xumbu vodiysi, Nepal", "craneFly3": "Machu-Pikchu, Peru", "craneFly4": "Male, Maldiv orollari", "craneFly5": "Vitsnau, Shveytsariya", "craneFly6": "Mexiko, Meksika", "craneFly7": "Rashmor togʻi, AQSH", "settingsTextDirectionLocaleBased": "Mamlakat soliqlari asosida", "craneFly9": "Gavana, Kuba", "craneFly10": "Qohira, Misr", "craneFly11": "Lissabon, Portugaliya", "craneFly12": "Napa, AQSH", "craneFly13": "Bali, Indoneziya", "craneSleep0": "Male, Maldiv orollari", "craneSleep1": "Aspen, AQSH", "craneSleep2": "Machu-Pikchu, Peru", "demoCupertinoSegmentedControlTitle": "Segmentlangan boshqaruv elementlari", "craneSleep4": "Vitsnau, Shveytsariya", "craneSleep5": "Katta Sur, AQSH", "craneSleep6": "Napa, AQSH", "craneSleep7": "Porto, Portugaliya", "craneSleep8": "Tulum, Meksika", "craneEat5": "Seul, Janubiy Koreya", "demoChipTitle": "Elementlar", "demoChipSubtitle": "Kiritish, xususiyat yoki amalni aks etuvchi ixcham elementlar", "demoActionChipTitle": "Amal elementi", "demoActionChipDescription": "Amal chiplari asosiy kontentga oid amallarni faollashtiradigan parametrlar toʻplamini ifodalaydi. Amal chiplari dinamik tarzda chiqib, inteyfeysni boyitadi.", "demoChoiceChipTitle": "Tanlov chipi", "demoChoiceChipDescription": "Tanlov chiplari toʻplamdagi variantlardan birini aks ettiradi. Ular tavsif matni yoki turkumdan iborat boʻladi.", "demoFilterChipTitle": "Filtr chipi", "demoFilterChipDescription": "Filtr chiplari kontentni teglar yoki tavsif soʻzlar bilan filtrlaydi.", "demoInputChipTitle": "Kiritish chipi", "demoInputChipDescription": "Kiritish chiplari obyekt (shaxs, joy yoki narsa) haqida umumiy axborot beradi yoki chatdagi ixcham matn shaklida chiqaradi.", "craneSleep9": "Lissabon, Portugaliya", "craneEat10": "Lissabon, Portugaliya", "demoCupertinoSegmentedControlDescription": "Bir nechta variantdan faqat bittasini belgilashda ishlatiladi. Bir element tanlansa, qolgan tanlov avtomatik yechiladi.", "chipTurnOnLights": "Chiroqlarni yoqish", "chipSmall": "Kichik", "chipMedium": "Oʻrtacha", "chipLarge": "Katta", "chipElevator": "Lift", "chipWasher": "Kir yuvish mashinasi", "chipFireplace": "Kamin", "chipBiking": "Velosipedda", "craneFormDiners": "Tamaddixonalar", "rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Soliq imtiyozlaringizni oshiring! Noaniq 1 ta tranzaksiyani turkumlang.}other{Soliq imtiyozlaringizni oshiring! Noaniq {count} ta tranzaksiyani turkumlang.}}", "craneFormTime": "Vaqtni tanlang", "craneFormLocation": "Joylashuvni tanlang", "craneFormTravelers": "Sayohatchilar", "craneEat8": "Atlanta, AQSH", "craneFormDestination": "Yakuniy manzilni tanlang", "craneFormDates": "Sanalarni tanlang", "craneFly": "UCHISH", "craneSleep": "UYQU", "craneEat": "OVQATLAR", "craneFlySubhead": "Turli manzillarga parvozlar", "craneSleepSubhead": "Turli manzillardagi joylar", "craneEatSubhead": "Turli manzillardagi restoranlar", "craneFlyStops": "{numberOfStops,plural,=0{Uzluksiz}=1{1 ta almashinuv}other{{numberOfStops} ta almashinuv}}", "craneSleepProperties": "{totalProperties,plural,=0{Mavjud uy-joylar topilmadi}=1{1 ta uy-joy mavjud}other{{totalProperties} ta uy-joy mavjud}}", "craneEatRestaurants": "{totalRestaurants,plural,=0{Restoran topilmadi}=1{1 ta restoran}other{{totalRestaurants} ta restoran}}", "craneFly0": "Aspen, AQSH", "demoCupertinoSegmentedControlSubtitle": "iOS uslubidagi boshqaruv elementlari", "craneSleep10": "Qohira, Misr", "craneEat9": "Madrid, Ispaniya", "craneFly1": "Katta Sur, AQSH", "craneEat7": "Neshvill, AQSH", "craneEat6": "Sietl, AQSH", "craneFly8": "Singapur", "craneEat4": "Parij, Fransiya", "craneEat3": "Portlend, AQSH", "craneEat2": "Kordova, Argentina", "craneEat1": "Dallas, AQSH", "craneEat0": "Neapol, Italiya", "craneSleep11": "Taypey, Tayvan", "craneSleep3": "Gavana, Kuba", "shrineLogoutButtonCaption": "CHIQISH", "rallyTitleBills": "HISOB-KITOB", "rallyTitleAccounts": "HISOBLAR", "shrineProductVagabondSack": "Vagabond sumkasi", "rallyAccountDetailDataInterestYtd": "Yil boshidan beri foizlar", "shrineProductWhitneyBelt": "Charm kamar", "shrineProductGardenStrand": "Gulchambar", "shrineProductStrutEarrings": "Halqali zirak", "shrineProductVarsitySocks": "Sport paypoqlari", "shrineProductWeaveKeyring": "Toʻqilgan jevak", "shrineProductGatsbyHat": "Getsbi shlyapa", "shrineProductShrugBag": "Hobo sumka", "shrineProductGiltDeskTrio": "Stol jamlanmasi", "shrineProductCopperWireRack": "Mis simli savat", "shrineProductSootheCeramicSet": "Sopol idishlar jamlanmasi", "shrineProductHurrahsTeaSet": "Choy ichish uchun jamlanma", "shrineProductBlueStoneMug": "Koʻk finjon", "shrineProductRainwaterTray": "Yomgʻir suvi tarnovi", "shrineProductChambrayNapkins": "Paxtali sochiqlar", "shrineProductSucculentPlanters": "Sukkulent oʻsimliklari", "shrineProductQuartetTable": "Aylana stol", "shrineProductKitchenQuattro": "Oshxona jamlanmasi", "shrineProductClaySweater": "Och jigarrang sviter", "shrineProductSeaTunic": "Yengil sviter", "shrineProductPlasterTunic": "Plaster tunika", "rallyBudgetCategoryRestaurants": "Restoranlar", "shrineProductChambrayShirt": "Paxtali koʻylak", "shrineProductSeabreezeSweater": "Yalpizli sviter", "shrineProductGentryJacket": "Jentri kurtka", "shrineProductNavyTrousers": "Kalta klesh shimlari", "shrineProductWalterHenleyWhite": "Oq yengil kofta", "shrineProductSurfAndPerfShirt": "Dengiz toʻlqinlari rangidagi futbolka", "shrineProductGingerScarf": "Sariq sharf", "shrineProductRamonaCrossover": "Ayollar bluzkasi", "shrineProductClassicWhiteCollar": "Klassik oq bluzka", "shrineProductSunshirtDress": "Yozgi koʻylak", "rallyAccountDetailDataInterestRate": "Foiz stavkasi", "rallyAccountDetailDataAnnualPercentageYield": "Yillik foiz daromadi", "rallyAccountDataVacation": "Taʼtil", "shrineProductFineLinesTee": "Chiziqli kofta", "rallyAccountDataHomeSavings": "Uy olish uchun", "rallyAccountDataChecking": "Hisobraqam", "rallyAccountDetailDataInterestPaidLastYear": "Oʻtgan yili toʻlangan foiz", "rallyAccountDetailDataNextStatement": "Keyingi hisob qaydnomasi", "rallyAccountDetailDataAccountOwner": "Hisob egasi", "rallyBudgetCategoryCoffeeShops": "Qahvaxonalar", "rallyBudgetCategoryGroceries": "Baqqollik mollari", "shrineProductCeriseScallopTee": "Shaftolirang futbolka", "rallyBudgetCategoryClothing": "Kiyim-kechak", "rallySettingsManageAccounts": "Hisoblarni boshqarish", "rallyAccountDataCarSavings": "Avtomobil olish uchun", "rallySettingsTaxDocuments": "Soliq hujjatlari", "rallySettingsPasscodeAndTouchId": "Kirish kodi va Touch ID", "rallySettingsNotifications": "Bildirishnomalar", "rallySettingsPersonalInformation": "Shaxsiy axborot", "rallySettingsPaperlessSettings": "Elektron hujjatlar sozlamalari", "rallySettingsFindAtms": "Bankomatlarni topish", "rallySettingsHelp": "Yordam", "rallySettingsSignOut": "Chiqish", "rallyAccountTotal": "Jami", "rallyBillsDue": "Muddati", "rallyBudgetLeft": "Qoldiq", "rallyAccounts": "Hisoblar", "rallyBills": "Hisob-kitob", "rallyBudgets": "Budjetlar", "rallyAlerts": "Bildirishnomalar", "rallySeeAll": "HAMMASI", "rallyFinanceLeft": "QOLDI", "rallyTitleOverview": "UMUMIY", "shrineProductShoulderRollsTee": "Qoʻllar erkin harakatlanadigan futbolka", "shrineNextButtonCaption": "KEYINGISI", "rallyTitleBudgets": "BUDJETLAR", "rallyTitleSettings": "SOZLAMALAR", "rallyLoginLoginToRally": "Rally hisobiga kirish", "rallyLoginNoAccount": "Hisobingiz yoʻqmi?", "rallyLoginSignUp": "ROʻYXATDAN OʻTISH", "rallyLoginUsername": "Foydalanuvchi nomi", "rallyLoginPassword": "Parol", "rallyLoginLabelLogin": "Kirish", "rallyLoginRememberMe": "Eslab qolinsin", "rallyLoginButtonLogin": "KIRISH", "rallyAlertsMessageHeadsUpShopping": "Diqqat! Bu oy budjetingizdan {percent} sarfladingiz.", "rallyAlertsMessageSpentOnRestaurants": "Bu hafta restoranlar uchun {amount} sarfladingiz.", "rallyAlertsMessageATMFees": "Siz bu oy bankomatlar komissiyasi uchun {amount} sarfladingiz", "rallyAlertsMessageCheckingAccount": "Juda yaxshi! Bu oy hisobingizda oldingi oyga nisbatan {percent} koʻp mablagʻ bor.", "shrineMenuCaption": "MENYU", "shrineCategoryNameAll": "HAMMASI", "shrineCategoryNameAccessories": "AKSESSUARLAR", "shrineCategoryNameClothing": "KIYIMLAR", "shrineCategoryNameHome": "UY", "shrineLoginUsernameLabel": "Foydalanuvchi nomi", "shrineLoginPasswordLabel": "Parol", "shrineCancelButtonCaption": "BEKOR QILISH", "shrineCartTaxCaption": "Soliq:", "shrineCartPageCaption": "SAVATCHA", "shrineProductQuantity": "Soni: {quantity}", "shrineProductPrice": "x {price}", "shrineCartItemCount": "{quantity,plural,=0{HECH NIMA}=1{1 TA ELEMENT}other{{quantity} TA ELEMENT}}", "shrineCartClearButtonCaption": "SAVATCHANI TOZALASH", "shrineCartTotalCaption": "JAMI", "shrineCartSubtotalCaption": "Oraliq summa:", "shrineCartShippingCaption": "Yetkazib berish:", "shrineProductGreySlouchTank": "Kulrang mayka", "shrineProductStellaSunglasses": "Stella quyosh koʻzoynaklari", "shrineProductWhitePinstripeShirt": "Oq chiziqli koʻylak", "demoTextFieldWhereCanWeReachYou": "Qaysi raqamga telefon qilib sizni topamiz?", "settingsTextDirectionLTR": "Chapdan oʻngga", "settingsTextScalingLarge": "Yirik", "demoBottomSheetHeader": "Yuqori sarlavha", "demoBottomSheetItem": "{value}-band", "demoBottomTextFieldsTitle": "Matn maydonchalari", "demoTextFieldTitle": "Matn maydonchalari", "demoTextFieldSubtitle": "Harf va raqamlarni tahrirlash uchun bitta qator", "demoTextFieldDescription": "Matn kiritish maydonchalari yordamida foydalanuvchilar grafik interfeysga matn kirita olishadi. Ular odatda shakl va muloqot oynalari shaklida chiqadi.", "demoTextFieldShowPasswordLabel": "Parolni koʻrsatish", "demoTextFieldHidePasswordLabel": "Parolni berkitish", "demoTextFieldFormErrors": "Yuborishdan oldin qizil bilan ajratilgan xatolarni tuzating.", "demoTextFieldNameRequired": "Ismni kiriting.", "demoTextFieldOnlyAlphabeticalChars": "Faqat alifbodagi harflarni kiriting.", "demoTextFieldEnterUSPhoneNumber": "(###) ###-#### - AQSH telefon raqamini kiriting.", "demoTextFieldEnterPassword": "Parolni kiriting.", "demoTextFieldPasswordsDoNotMatch": "Parollar mos kelmadi", "demoTextFieldWhatDoPeopleCallYou": "Ismingiz nima?", "demoTextFieldNameField": "Ism*", "demoBottomSheetButtonText": "QUYI EKRANNI CHIQARISH", "demoTextFieldPhoneNumber": "Telefon raqami*", "demoBottomSheetTitle": "Quyi ekran", "demoTextFieldEmail": "Email", "demoTextFieldTellUsAboutYourself": "Oʻzingiz haqingizda aytib bering (masalan, nima ish qilishingiz yoki qanday hobbilaringiz borligini yozing)", "demoTextFieldKeepItShort": "Qisqa yozing. Bu shunchaki matn namunasi.", "starterAppGenericButton": "TUGMA", "demoTextFieldLifeStory": "Tarjimayi hol", "demoTextFieldSalary": "Maosh", "demoTextFieldUSD": "USD", "demoTextFieldNoMoreThan": "8 ta belgidan oshmasin.", "demoTextFieldPassword": "Parol*", "demoTextFieldRetypePassword": "Parolni qayta kiriting*", "demoTextFieldSubmit": "YUBORISH", "demoBottomNavigationSubtitle": "Oson ochish uchun ekran pastidagi navigatsiya", "demoBottomSheetAddLabel": "Kiritish", "demoBottomSheetModalDescription": "Modal quyi ekrandan menyu yoki muloqot oynasi bilan birgalikda foydalanish mumkin. Bunday ekran ochiqligida ilovaning boshqa elementlaridan foydalanish imkonsiz.", "demoBottomSheetModalTitle": "Modal quyi ekran", "demoBottomSheetPersistentDescription": "Doimiy quyi ekranda ilovadagi qoʻshimcha maʼlumotlar chiqadi. Bunday ekran doim ochiq turadi, hatto foydalanuvchi ilovaning boshqa qismlari bilan ishlayotgan paytda ham.", "demoBottomSheetPersistentTitle": "Doimiy quyi ekran", "demoBottomSheetSubtitle": "Doimiy va modal quyi ekranlar", "demoTextFieldNameHasPhoneNumber": "{name} telefoni raqami: {phoneNumber}", "buttonText": "TUGMA", "demoTypographyDescription": "Material Design ichidagi har xil shriftlar uchun izoh.", "demoTypographySubtitle": "Barcha standart matn uslublari", "demoTypographyTitle": "Matn sozlamalari", "demoFullscreenDialogDescription": "fullscreenDialog xossasi butun ekran rejimidagi modal muloqot oynasida keyingi sahifa borligini koʻrsatadi", "demoFlatButtonDescription": "Tekis tugmalarni bossangiz, ular koʻtarilmaydi. Uning oʻrniga siyohli dogʻ paydo boʻladi. Bu tugmalardan asboblar panelida va muloqot oynalarida foydalaning yoki ularni maydonga kiriting", "demoBottomNavigationDescription": "Ekranning pastki qismidagi navigatsiya panelida xizmatning uchdan beshtagacha qismini joylashtirish mumkin. Ularning har biriga alohida belgi va matn (ixtiyoriy) kiritiladi. Foydalanuvchi belgilardan biriga bossa, kerakli qism ochiladi.", "demoBottomNavigationSelectedLabel": "Tanlangan yorliq", "demoBottomNavigationPersistentLabels": "Doimiy yorliqlar", "starterAppDrawerItem": "{value}-band", "demoTextFieldRequiredField": "* kiritish shart", "demoBottomNavigationTitle": "Ekran pastidagi navigatsiya", "settingsLightTheme": "Kunduzgi", "settingsTheme": "Mavzu", "settingsPlatformIOS": "iOS", "settingsPlatformAndroid": "Android", "settingsTextDirectionRTL": "Oʻngdan chapga", "settingsTextScalingHuge": "Juda katta", "cupertinoButton": "Tugma", "settingsTextScalingNormal": "Normal", "settingsTextScalingSmall": "Kichik", "settingsSystemDefault": "Tizim", "settingsTitle": "Sozlamalar", "rallyDescription": "Budjetni rejalashtirish uchun ilova", "aboutDialogDescription": "Bu ilovaning manba kodini koʻrish uchun bu yerga kiring: {repoLink}.", "bottomNavigationCommentsTab": "Fikrlar", "starterAppGenericBody": "Asosiy qism", "starterAppGenericHeadline": "Sarlavha", "starterAppGenericSubtitle": "Taglavha", "starterAppGenericTitle": "Nomi", "starterAppTooltipSearch": "Qidiruv", "starterAppTooltipShare": "Ulashish", "starterAppTooltipFavorite": "Sevimli", "starterAppTooltipAdd": "Kiritish", "bottomNavigationCalendarTab": "Taqvim", "starterAppDescription": "Moslashuvchan maket", "starterAppTitle": "Starter ilovasi", "aboutFlutterSamplesRepo": "GitHub omboridan Flutter namunalari", "bottomNavigationContentPlaceholder": "{title} sahifasi uchun pleysholder", "bottomNavigationCameraTab": "Kamera", "bottomNavigationAlarmTab": "Signal", "bottomNavigationAccountTab": "Hisob", "demoTextFieldYourEmailAddress": "Email manzilingiz", "demoToggleButtonDescription": "Belgilash/olib tashlash tugmasi bilan oʻxshash parametrlarni guruhlash mumkin. Belgilash/olib tashlash tugmasiga aloqador guruhlar bitta umumiy konteynerda boʻlishi lozim.", "colorsGrey": "KULRANG", "colorsBrown": "JIGARRANG", "colorsDeepOrange": "TOʻQ APELSINRANG", "colorsOrange": "TOʻQ SARIQ", "colorsAmber": "QAHRABO RANG", "colorsYellow": "SARIQ", "colorsLime": "OCH YASHIL", "colorsLightGreen": "OCH YASHIL", "colorsGreen": "YASHIL", "homeHeaderGallery": "Gallereya", "homeHeaderCategories": "Turkumlar", "shrineDescription": "Zamonaviy buyumlarni sotib olish uchun ilova", "craneDescription": "Sayohatlar uchun moslangan ilova", "homeCategoryReference": "USLUBLAR VA BOSHQA", "demoInvalidURL": "URL ochilmadi:", "demoOptionsTooltip": "Parametrlar", "demoInfoTooltip": "Axborot", "demoCodeTooltip": "Demo versiya kodi", "demoDocumentationTooltip": "API hujjatlari", "demoFullscreenTooltip": "Butun ekran", "settingsTextScaling": "Matn hajmi", "settingsTextDirection": "Matn yoʻnalishi", "settingsLocale": "Hududiy sozlamalar", "settingsPlatformMechanics": "Platforma", "settingsDarkTheme": "Tungi", "settingsSlowMotion": "Sekinlashuv", "settingsAbout": "Flutter Gallery haqida", "settingsFeedback": "Fikr-mulohaza yuborish", "settingsAttribution": "Dizayn: TOASTER, London", "demoButtonTitle": "Tugmalar", "demoButtonSubtitle": "Matnli, koʻtarilgan, chegarali va boshqalar", "demoFlatButtonTitle": "Tekis tugma", "demoRaisedButtonDescription": "Qavariq tugmalar yassi maketni qavariqli qilish imkonini beradi. Katta va keng sahifalarda koʻzga tez tashlanadigan boʻladi", "demoRaisedButtonTitle": "Qavariq tugma", "demoOutlineButtonTitle": "Atrofi chizilgan tugma", "demoOutlineButtonDescription": "Atrofi chizilgan tugmani bosganda shaffof boʻladi va koʻtariladi. Ular odatda qavariq tugmalar bilan biriktiriladi va ikkinchi harakat, yaʼni muqobilini koʻrsatish uchun ishlatiladi.", "demoToggleButtonTitle": "Belgilash/olib tashlash tugmalari", "colorsTeal": "MOVIY", "demoFloatingButtonTitle": "Erkin harakatlanuvchi amal tugmasi", "demoFloatingButtonDescription": "Erkin harakatlanuvchi amal tugmasi halqa shaklidagi tugma boʻlib, u boshqa kontentlarning tagida joylashadi va ilovadagi eng muhim harakatlarni belgilash imkonini beradi.", "demoDialogTitle": "Muloqot oynalari", "demoDialogSubtitle": "Oddiy, bildirishnoma va butun ekran", "demoAlertDialogTitle": "Bildirishnoma", "demoAlertDialogDescription": "Ogohlantiruvchi muloqot oynasi foydalanuvchini u eʼtibor qaratishi lozim boʻlgan voqealar yuz berganda ogohlantiradi. Unda sarlavha va mavjud harakatlar roʻyxati boʻlishi mumkin.", "demoAlertTitleDialogTitle": "Sarlavhali bildirishnoma", "demoSimpleDialogTitle": "Oddiy", "demoSimpleDialogDescription": "Oddiy muloqot oynasida foydalanuvchiga tanlash uchun bir nechta variant beriladi. Oynada sarlavha boʻlsa, u variantlar ustida joylashadi.", "demoFullscreenDialogTitle": "Butun ekran", "demoCupertinoButtonsTitle": "Tugmalar", "demoCupertinoButtonsSubtitle": "iOS uslubidagi tugmalar", "demoCupertinoButtonsDescription": "iOS uslubidagi tugma. Unda bosganda chiqadigan va yoʻqoladigan matn yoki belgi boʻladi. Orqa fon boʻlishi ham mumkin.", "demoCupertinoAlertsTitle": "Bildirishnomalar", "demoCupertinoAlertsSubtitle": "iOS uslubidagi bildirishnomali muloqot oynasi", "demoCupertinoAlertTitle": "Bildirishnoma", "demoCupertinoAlertDescription": "Ogohlantiruvchi muloqot oynasi foydalanuvchini u eʼtibor qaratishi lozim boʻlgan voqealar yuz berganda ogohlantiradi. Unda sarlavha, kontent va mavjud harakatlar roʻyxati boʻlishi mumkin. Sarlavha matn tepasida, harakatlar esa ularning ostida joylashadi.", "demoCupertinoAlertWithTitleTitle": "Sarlavhali bildirishnoma", "demoCupertinoAlertButtonsTitle": "Tugmali bildirishnomalar", "demoCupertinoAlertButtonsOnlyTitle": "Faqat bildirishnoma tugmalari", "demoCupertinoActionSheetTitle": "Harakatlar keltirilgan sahifa", "demoCupertinoActionSheetDescription": "Harakatlar sahifasi bildirishnomalarning maxsus uslubi boʻlib, unda foydalanuvchining joriy matnga aloqador ikki yoki undan ortiq tanlovlari majmuasi koʻrsatiladi. Harakatlar sahifasida sarlavha, qoʻshimcha xabar va harakatlar roʻyxati boʻlishi mumkin.", "demoColorsTitle": "Ranglar", "demoColorsSubtitle": "Barcha standart ranglar", "demoColorsDescription": "Material Design ranglar majmuasini taqdim qiluvchi rang va gradiyentlar uchun konstantalar", "buttonTextEnabled": "ENABLED", "buttonTextDisabled": "DISABLED", "buttonTextCreate": "Yaratish", "dialogSelectedOption": "Siz tanlagan qiymat: \"{value}\"", "dialogDiscardTitle": "Qoralama bekor qilinsinmi?", "dialogLocationTitle": "Googlening joylashuvni aniqlash xizmatidan foydalanilsinmi?", "dialogLocationDescription": "Google ilovalarga joylashuvni aniqlashda yordam berishi uchun ruxsat bering. Bu shuni bildiradiki, hech qanday ilova ishlamayotgan boʻlsa ham joylashuv axboroti maxfiy tarzda Googlega yuboriladi.", "dialogCancel": "BEKOR QILISH", "dialogDiscard": "BEKOR QILISH", "dialogDisagree": "ROZI EMASMAN", "dialogAgree": "ROZIMAN", "dialogSetBackup": "Hisobni tanlash", "colorsBlueGrey": "MOVIY KULRANG", "dialogShow": "MULOQOT OYNASINI CHIQARISH", "dialogFullscreenTitle": "Butun ekran rejimidagi muloqot oynasi", "dialogFullscreenSave": "SAQLASH", "dialogFullscreenDescription": "Butun ekran rejimidagi muloqot oynasining demo versiyasi", "cupertinoButtonEnabled": "Enabled", "cupertinoButtonDisabled": "Disabled", "cupertinoButtonWithBackground": "Orqa fon bilan", "cupertinoAlertCancel": "Bekor qilish", "cupertinoAlertDiscard": "Bekor qilish", "cupertinoAlertLocationTitle": "Ilovalardan foydalanishdan oldin “Xaritalar” ilovasiga joylashuv axborotidan foydalanishga ruxsat berasizmi?", "cupertinoAlertLocationDescription": "Joriy joylashuvingiz xaritada chiqadi va yoʻnalishlarni aniqlash, yaqin-atrofdagi qidiruv natijalari, qolgan sayohat vaqtlarini chiqarish uchun kerak boʻladi.", "cupertinoAlertAllow": "Ruxsat berish", "cupertinoAlertDontAllow": "Ruxsat berilmasin", "cupertinoAlertFavoriteDessert": "Sevimli desertingizni tanlang", "cupertinoAlertDessertDescription": "Quyidagi roʻyxatdan sevimli desertingizni tanlang. Tanlovingiz asosida biz yaqin-atrofdagi tavsiya etiladigan yemakxonalar roʻyxatini tuzamiz.", "cupertinoAlertCheesecake": "Chizkeyk", "cupertinoAlertTiramisu": "Tiramisu", "cupertinoAlertApplePie": "Olmali pirog", "cupertinoAlertChocolateBrownie": "Shokoladli brauni", "cupertinoShowAlert": "Bildirishnomani koʻrsatish", "colorsRed": "QIZIL", "colorsPink": "PUSHTI", "colorsPurple": "SIYOHRANG", "colorsDeepPurple": "TOʻQ SIYOHRANG", "colorsIndigo": "INDIGO", "colorsBlue": "KOʻK", "colorsLightBlue": "HAVORANG", "colorsCyan": "ZANGORI", "dialogAddAccount": "Hisob qoʻshish", "Gallery": "Gallereya", "Categories": "Turkumlar", "SHRINE": "ZIYORATGOH", "Basic shopping app": "Standart xaridlar ilovasi", "RALLY": "RALLI", "CRANE": "KRAN", "Travel app": "Sayohatlar ilovasi", "MATERIAL": "MATERIAL", "CUPERTINO": "KUPERTINO", "REFERENCE STYLES & MEDIA": "USLUBLAR VA MEDIA NAMUNALAR" }
gallery/lib/l10n/intl_uz.arb/0
{ "file_path": "gallery/lib/l10n/intl_uz.arb", "repo_id": "gallery", "token_count": 20525 }
816
// Copyright 2019 The Flutter team. 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:dual_screen/dual_screen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gen/gen_l10n/gallery_localizations.dart'; import 'package:gallery/codeviewer/code_displayer.dart'; import 'package:gallery/codeviewer/code_style.dart'; import 'package:gallery/constants.dart'; import 'package:gallery/data/demos.dart'; import 'package:gallery/data/gallery_options.dart'; import 'package:gallery/feature_discovery/feature_discovery.dart'; import 'package:gallery/layout/adaptive.dart'; import 'package:gallery/pages/splash.dart'; import 'package:gallery/themes/gallery_theme_data.dart'; import 'package:gallery/themes/material_demo_theme_data.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:url_launcher/url_launcher_string.dart'; enum _DemoState { normal, options, info, code, fullscreen, } class DemoPage extends StatefulWidget { const DemoPage({ super.key, required this.slug, }); static const String baseRoute = '/demo'; final String? slug; @override State<DemoPage> createState() => _DemoPageState(); } class _DemoPageState extends State<DemoPage> { late Map<String?, GalleryDemo> slugToDemoMap; @override void didChangeDependencies() { super.didChangeDependencies(); // To make sure that we do not rebuild the map for every update to the demo // page, we save it in a variable. The cost of running `slugToDemo` is // still only close to constant, as it's just iterating over all of the // demos. slugToDemoMap = Demos.asSlugToDemoMap(context); } @override Widget build(BuildContext context) { if (widget.slug == null || !slugToDemoMap.containsKey(widget.slug)) { // Return to root if invalid slug. Navigator.of(context).pop(); } return ScaffoldMessenger( child: GalleryDemoPage( restorationId: widget.slug!, demo: slugToDemoMap[widget.slug]!, )); } } class GalleryDemoPage extends StatefulWidget { const GalleryDemoPage({ super.key, required this.restorationId, required this.demo, }); final String restorationId; final GalleryDemo demo; @override State<GalleryDemoPage> createState() => _GalleryDemoPageState(); } class _GalleryDemoPageState extends State<GalleryDemoPage> with RestorationMixin, TickerProviderStateMixin { final RestorableInt _demoStateIndex = RestorableInt(_DemoState.normal.index); final RestorableInt _configIndex = RestorableInt(0); bool? _isDesktop; late AnimationController _codeBackgroundColorController; @override String get restorationId => widget.restorationId; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_demoStateIndex, 'demo_state'); registerForRestoration(_configIndex, 'configuration_index'); } GalleryDemoConfiguration get _currentConfig { return widget.demo.configurations[_configIndex.value]; } bool get _hasOptions => widget.demo.configurations.length > 1; @override void initState() { super.initState(); _codeBackgroundColorController = AnimationController( vsync: this, duration: const Duration(milliseconds: 300), ); } @override void dispose() { _demoStateIndex.dispose(); _configIndex.dispose(); _codeBackgroundColorController.dispose(); super.dispose(); } @override void didChangeDependencies() { super.didChangeDependencies(); _isDesktop ??= isDisplayDesktop(context); } /// Sets state and updates the background color for code. void setStateAndUpdate(VoidCallback callback) { setState(() { callback(); if (_demoStateIndex.value == _DemoState.code.index) { _codeBackgroundColorController.forward(); } else { _codeBackgroundColorController.reverse(); } }); } void _handleTap(_DemoState newState) { var newStateIndex = newState.index; // Do not allow normal state for desktop. if (_demoStateIndex.value == newStateIndex && isDisplayDesktop(context)) { if (_demoStateIndex.value == _DemoState.fullscreen.index) { setStateAndUpdate(() { _demoStateIndex.value = _hasOptions ? _DemoState.options.index : _DemoState.info.index; }); } return; } setStateAndUpdate(() { _demoStateIndex.value = _demoStateIndex.value == newStateIndex ? _DemoState.normal.index : newStateIndex; }); } Future<void> _showDocumentation(BuildContext context) async { final url = _currentConfig.documentationUrl; if (await canLaunchUrlString(url)) { await launchUrlString(url); } else if (context.mounted) { await showDialog<void>( context: context, builder: (context) { return SimpleDialog( title: Text(GalleryLocalizations.of(context)!.demoInvalidURL), children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Text(url), ), ], ); }, ); } } void _resolveState(BuildContext context) { final isDesktop = isDisplayDesktop(context); final isFoldable = isDisplayFoldable(context); if (_DemoState.values[_demoStateIndex.value] == _DemoState.fullscreen && !isDesktop) { // Do not allow fullscreen state for mobile. _demoStateIndex.value = _DemoState.normal.index; } else if (_DemoState.values[_demoStateIndex.value] == _DemoState.normal && (isDesktop || isFoldable)) { // Do not allow normal state for desktop. _demoStateIndex.value = _hasOptions ? _DemoState.options.index : _DemoState.info.index; } else if (isDesktop != _isDesktop) { _isDesktop = isDesktop; // When going from desktop to mobile, return to normal state. if (!isDesktop) { _demoStateIndex.value = _DemoState.normal.index; } } } @override Widget build(BuildContext context) { final isFoldable = isDisplayFoldable(context); final isDesktop = isDisplayDesktop(context); _resolveState(context); final colorScheme = Theme.of(context).colorScheme; final iconColor = colorScheme.onSurface; final selectedIconColor = colorScheme.primary; final appBarPadding = isDesktop ? 20.0 : 0.0; final currentDemoState = _DemoState.values[_demoStateIndex.value]; final localizations = GalleryLocalizations.of(context)!; final options = GalleryOptions.of(context); final appBar = AppBar( systemOverlayStyle: options.resolvedSystemUiOverlayStyle(), backgroundColor: Colors.transparent, leading: Padding( padding: EdgeInsetsDirectional.only(start: appBarPadding), child: IconButton( key: const ValueKey('Back'), icon: const BackButtonIcon(), tooltip: MaterialLocalizations.of(context).backButtonTooltip, onPressed: () { Navigator.maybePop(context); }, ), ), actions: [ if (_hasOptions) IconButton( icon: FeatureDiscovery( title: localizations.demoOptionsFeatureTitle, description: localizations.demoOptionsFeatureDescription, showOverlay: !isDisplayDesktop(context) && !options.isTestMode, color: colorScheme.primary, onTap: () => _handleTap(_DemoState.options), child: Icon( Icons.tune, color: currentDemoState == _DemoState.options ? selectedIconColor : iconColor, ), ), tooltip: localizations.demoOptionsTooltip, onPressed: () => _handleTap(_DemoState.options), ), IconButton( icon: const Icon(Icons.info), tooltip: localizations.demoInfoTooltip, color: currentDemoState == _DemoState.info ? selectedIconColor : iconColor, onPressed: () => _handleTap(_DemoState.info), ), IconButton( icon: const Icon(Icons.code), tooltip: localizations.demoCodeTooltip, color: currentDemoState == _DemoState.code ? selectedIconColor : iconColor, onPressed: () => _handleTap(_DemoState.code), ), IconButton( icon: const Icon(Icons.library_books), tooltip: localizations.demoDocumentationTooltip, color: iconColor, onPressed: () => _showDocumentation(context), ), if (isDesktop) IconButton( icon: const Icon(Icons.fullscreen), tooltip: localizations.demoFullscreenTooltip, color: currentDemoState == _DemoState.fullscreen ? selectedIconColor : iconColor, onPressed: () => _handleTap(_DemoState.fullscreen), ), SizedBox(width: appBarPadding), ], ); final mediaQuery = MediaQuery.of(context); final bottomSafeArea = mediaQuery.padding.bottom; final contentHeight = mediaQuery.size.height - mediaQuery.padding.top - mediaQuery.padding.bottom - appBar.preferredSize.height; final maxSectionHeight = isDesktop ? contentHeight : contentHeight - 64; final horizontalPadding = isDesktop ? mediaQuery.size.width * 0.12 : 0.0; const maxSectionWidth = 420.0; Widget section; switch (currentDemoState) { case _DemoState.options: section = _DemoSectionOptions( maxHeight: maxSectionHeight, maxWidth: maxSectionWidth, configurations: widget.demo.configurations, configIndex: _configIndex.value, onConfigChanged: (index) { setStateAndUpdate(() { _configIndex.value = index; if (!isDesktop) { _demoStateIndex.value = _DemoState.normal.index; } }); }, ); break; case _DemoState.info: section = _DemoSectionInfo( maxHeight: maxSectionHeight, maxWidth: maxSectionWidth, title: _currentConfig.title, description: _currentConfig.description, ); break; case _DemoState.code: final codeTheme = GoogleFonts.robotoMono( fontSize: 12 * options.textScaleFactor(context), ); section = CodeStyle( baseStyle: codeTheme.copyWith(color: const Color(0xFFFAFBFB)), numberStyle: codeTheme.copyWith(color: const Color(0xFFBD93F9)), commentStyle: codeTheme.copyWith(color: const Color(0xFF808080)), keywordStyle: codeTheme.copyWith(color: const Color(0xFF1CDEC9)), stringStyle: codeTheme.copyWith(color: const Color(0xFFFFA65C)), punctuationStyle: codeTheme.copyWith(color: const Color(0xFF8BE9FD)), classStyle: codeTheme.copyWith(color: const Color(0xFFD65BAD)), constantStyle: codeTheme.copyWith(color: const Color(0xFFFF8383)), child: _DemoSectionCode( maxHeight: maxSectionHeight, codeWidget: CodeDisplayPage( _currentConfig.code, ), ), ); break; default: section = Container(); break; } Widget body; Widget demoContent = ScaffoldMessenger( child: DemoWrapper( height: contentHeight, buildRoute: _currentConfig.buildRoute, ), ); if (isDesktop) { final isFullScreen = currentDemoState == _DemoState.fullscreen; final Widget sectionAndDemo = Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (!isFullScreen) Expanded(child: section), SizedBox(width: !isFullScreen ? 48.0 : 0), Expanded(child: demoContent), ], ); body = SafeArea( child: Padding( padding: const EdgeInsets.only(top: 56), child: sectionAndDemo, ), ); } else if (isFoldable) { body = Padding( padding: const EdgeInsets.only(top: 12.0), child: TwoPane( startPane: demoContent, endPane: section, ), ); } else { section = AnimatedSize( duration: const Duration(milliseconds: 200), alignment: Alignment.topCenter, curve: Curves.easeIn, child: section, ); final isDemoNormal = currentDemoState == _DemoState.normal; // Add a tap gesture to collapse the currently opened section. demoContent = Semantics( label: '${GalleryLocalizations.of(context)!.demo}, ${widget.demo.title}', child: MouseRegion( cursor: isDemoNormal ? MouseCursor.defer : SystemMouseCursors.click, child: GestureDetector( onTap: isDemoNormal ? null : () { setStateAndUpdate(() { _demoStateIndex.value = _DemoState.normal.index; }); }, child: Semantics( excludeSemantics: !isDemoNormal, child: demoContent, ), ), ), ); body = SafeArea( bottom: false, child: ListView( // Use a non-scrollable ListView to enable animation of shifting the // demo offscreen. physics: const NeverScrollableScrollPhysics(), children: [ section, demoContent, // Fake the safe area to ensure the animation looks correct. SizedBox(height: bottomSafeArea), ], ), ); } Widget page; if (isDesktop || isFoldable) { page = AnimatedBuilder( animation: _codeBackgroundColorController, builder: (context, child) { Brightness themeBrightness; switch (GalleryOptions.of(context).themeMode) { case ThemeMode.system: themeBrightness = MediaQuery.of(context).platformBrightness; break; case ThemeMode.light: themeBrightness = Brightness.light; break; case ThemeMode.dark: themeBrightness = Brightness.dark; break; } Widget contents = Container( padding: EdgeInsets.symmetric(horizontal: horizontalPadding), child: ApplyTextOptions( child: Scaffold( appBar: appBar, body: body, backgroundColor: Colors.transparent, ), ), ); if (themeBrightness == Brightness.light) { // If it is currently in light mode, add a // dark background for code. Widget codeBackground = SafeArea( child: Container( padding: const EdgeInsets.only(top: 56), child: Container( color: ColorTween( begin: Colors.transparent, end: GalleryThemeData.darkThemeData.canvasColor, ).animate(_codeBackgroundColorController).value, ), ), ); contents = Stack( children: [ codeBackground, contents, ], ); } return Container( color: colorScheme.background, child: contents, ); }); } else { page = Container( color: colorScheme.background, child: ApplyTextOptions( child: Scaffold( appBar: appBar, body: body, resizeToAvoidBottomInset: false, ), ), ); } // Add the splash page functionality for desktop. if (isDesktop) { page = MediaQuery.removePadding( removeTop: true, context: context, child: SplashPage( child: page, ), ); } return FeatureDiscoveryController(page); } } class _DemoSectionOptions extends StatelessWidget { const _DemoSectionOptions({ required this.maxHeight, required this.maxWidth, required this.configurations, required this.configIndex, required this.onConfigChanged, }); final double maxHeight; final double maxWidth; final List<GalleryDemoConfiguration> configurations; final int configIndex; final ValueChanged<int> onConfigChanged; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final colorScheme = Theme.of(context).colorScheme; return Align( alignment: AlignmentDirectional.topStart, child: Container( constraints: BoxConstraints(maxHeight: maxHeight, maxWidth: maxWidth), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Padding( padding: const EdgeInsetsDirectional.only( start: 24, top: 12, end: 24, ), child: Text( GalleryLocalizations.of(context)!.demoOptionsTooltip, style: textTheme.headlineMedium!.apply( color: colorScheme.onSurface, fontSizeDelta: isDisplayDesktop(context) ? desktopDisplay1FontDelta : 0, ), ), ), Divider( thickness: 1, height: 16, color: colorScheme.onSurface, ), Flexible( child: ListView( shrinkWrap: true, children: [ for (final configuration in configurations) _DemoSectionOptionsItem( title: configuration.title, isSelected: configuration == configurations[configIndex], onTap: () { onConfigChanged(configurations.indexOf(configuration)); }, ), ], ), ), const SizedBox(height: 12), ], ), ), ); } } class _DemoSectionOptionsItem extends StatelessWidget { const _DemoSectionOptionsItem({ required this.title, required this.isSelected, this.onTap, }); final String title; final bool isSelected; final GestureTapCallback? onTap; @override Widget build(BuildContext context) { final colorScheme = Theme.of(context).colorScheme; return Material( color: isSelected ? colorScheme.surface : null, child: InkWell( onTap: onTap, child: Container( constraints: const BoxConstraints(minWidth: double.infinity), padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8), child: Text( title, style: Theme.of(context).textTheme.bodyMedium!.apply( color: isSelected ? colorScheme.primary : colorScheme.onSurface, ), ), ), ), ); } } class _DemoSectionInfo extends StatelessWidget { const _DemoSectionInfo({ required this.maxHeight, required this.maxWidth, required this.title, required this.description, }); final double maxHeight; final double maxWidth; final String title; final String description; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; final colorScheme = Theme.of(context).colorScheme; return Align( alignment: AlignmentDirectional.topStart, child: Container( padding: const EdgeInsetsDirectional.only( start: 24, top: 12, end: 24, bottom: 32, ), constraints: BoxConstraints(maxHeight: maxHeight, maxWidth: maxWidth), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ SelectableText( title, style: textTheme.headlineMedium!.apply( color: colorScheme.onSurface, fontSizeDelta: isDisplayDesktop(context) ? desktopDisplay1FontDelta : 0, ), ), const SizedBox(height: 12), SelectableText( description, style: textTheme.bodyMedium!.apply( color: colorScheme.onSurface, ), ), ], ), ), ), ); } } class DemoWrapper extends StatelessWidget { const DemoWrapper({ super.key, required this.height, required this.buildRoute, }); final double height; final WidgetBuilder buildRoute; @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.only(left: 16, right: 16, bottom: 16), height: height, child: ClipRRect( clipBehavior: Clip.antiAliasWithSaveLayer, borderRadius: const BorderRadius.vertical( top: Radius.circular(10.0), bottom: Radius.circular(2.0), ), child: Theme( data: MaterialDemoThemeData.themeData.copyWith( platform: GalleryOptions.of(context).platform, ), child: CupertinoTheme( data: const CupertinoThemeData() .copyWith(brightness: Brightness.light), child: ApplyTextOptions( child: Builder(builder: buildRoute), ), ), ), ), ); } } class _DemoSectionCode extends StatelessWidget { const _DemoSectionCode({ this.maxHeight, this.codeWidget, }); final double? maxHeight; final Widget? codeWidget; @override Widget build(BuildContext context) { final isDesktop = isDisplayDesktop(context); return Theme( data: GalleryThemeData.darkThemeData, child: Padding( padding: const EdgeInsets.only(bottom: 16), child: Container( color: isDesktop ? null : GalleryThemeData.darkThemeData.canvasColor, padding: const EdgeInsets.symmetric(horizontal: 16), height: maxHeight, child: codeWidget, ), ), ); } } class CodeDisplayPage extends StatelessWidget { const CodeDisplayPage(this.code, {super.key}); final CodeDisplayer code; @override Widget build(BuildContext context) { final isDesktop = isDisplayDesktop(context); final richTextCode = code(context); final plainTextCode = richTextCode.toPlainText(); void showSnackBarOnCopySuccess(dynamic result) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( GalleryLocalizations.of(context)! .demoCodeViewerCopiedToClipboardMessage, ), ), ); } void showSnackBarOnCopyFailure(Object exception) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( GalleryLocalizations.of(context)! .demoCodeViewerFailedToCopyToClipboardMessage(exception), ), ), ); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: isDesktop ? const EdgeInsets.only(bottom: 8) : const EdgeInsets.symmetric(vertical: 8), child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.white.withOpacity(0.15), padding: const EdgeInsets.symmetric(horizontal: 8), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4)), ), ), onPressed: () async { await Clipboard.setData(ClipboardData(text: plainTextCode)) .then(showSnackBarOnCopySuccess) .catchError(showSnackBarOnCopyFailure); }, child: Text( GalleryLocalizations.of(context)!.demoCodeViewerCopyAll, style: Theme.of(context).textTheme.labelLarge!.copyWith( color: Colors.white, fontWeight: FontWeight.w500, ), ), ), ), Expanded( child: SingleChildScrollView( child: Container( padding: const EdgeInsets.symmetric(vertical: 8), child: SelectableText.rich( richTextCode, textDirection: TextDirection.ltr, ), ), ), ), ], ); } }
gallery/lib/pages/demo.dart/0
{ "file_path": "gallery/lib/pages/demo.dart", "repo_id": "gallery", "token_count": 11460 }
817
// Copyright 2019 The Flutter team. 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:math' as math; import 'package:animations/animations.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_gen/gen_l10n/gallery_localizations.dart'; import 'package:gallery/data/gallery_options.dart'; import 'package:gallery/layout/adaptive.dart'; import 'package:gallery/layout/text_scale.dart'; import 'package:gallery/studies/rally/charts/line_chart.dart'; import 'package:gallery/studies/rally/charts/pie_chart.dart'; import 'package:gallery/studies/rally/charts/vertical_fraction_bar.dart'; import 'package:gallery/studies/rally/colors.dart'; import 'package:gallery/studies/rally/data.dart'; import 'package:gallery/studies/rally/formatters.dart'; class FinancialEntityView extends StatelessWidget { const FinancialEntityView({ super.key, required this.heroLabel, required this.heroAmount, required this.wholeAmount, required this.segments, required this.financialEntityCards, }) : assert(segments.length == financialEntityCards.length); /// The amounts to assign each item. final List<RallyPieChartSegment> segments; final String heroLabel; final double heroAmount; final double wholeAmount; final List<FinancialEntityCategoryView> financialEntityCards; @override Widget build(BuildContext context) { final maxWidth = pieChartMaxSize + (cappedTextScale(context) - 1.0) * 100.0; return LayoutBuilder(builder: (context, constraints) { return Column( children: [ ConstrainedBox( constraints: BoxConstraints( // We decrease the max height to ensure the [RallyPieChart] does // not take up the full height when it is smaller than // [kPieChartMaxSize]. maxHeight: math.min( constraints.biggest.shortestSide * 0.9, maxWidth, ), ), child: RallyPieChart( heroLabel: heroLabel, heroAmount: heroAmount, wholeAmount: wholeAmount, segments: segments, ), ), const SizedBox(height: 24), Container( height: 1, constraints: BoxConstraints(maxWidth: maxWidth), color: RallyColors.inputBackground, ), Container( constraints: BoxConstraints(maxWidth: maxWidth), color: RallyColors.cardBackground, child: Column( children: financialEntityCards, ), ), ], ); }); } } /// A reusable widget to show balance information of a single entity as a card. class FinancialEntityCategoryView extends StatelessWidget { const FinancialEntityCategoryView({ super.key, required this.indicatorColor, required this.indicatorFraction, required this.title, required this.subtitle, required this.semanticsLabel, required this.amount, required this.suffix, }); final Color indicatorColor; final double indicatorFraction; final String title; final String subtitle; final String semanticsLabel; final String amount; final Widget suffix; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Semantics.fromProperties( properties: SemanticsProperties( button: true, enabled: true, label: semanticsLabel, ), excludeSemantics: true, // TODO(x): State restoration of FinancialEntityCategoryDetailsPage on mobile is blocked because OpenContainer does not support restorablePush, https://github.com/flutter/gallery/issues/570. child: OpenContainer( transitionDuration: const Duration(milliseconds: 350), transitionType: ContainerTransitionType.fade, openBuilder: (context, openContainer) => FinancialEntityCategoryDetailsPage(), openColor: RallyColors.primaryBackground, closedColor: RallyColors.primaryBackground, closedElevation: 0, closedBuilder: (context, openContainer) { return TextButton( style: TextButton.styleFrom(foregroundColor: Colors.black), onPressed: openContainer, child: Column( children: [ Container( padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8), child: Row( children: [ Container( alignment: Alignment.center, height: 32 + 60 * (cappedTextScale(context) - 1), padding: const EdgeInsets.symmetric(horizontal: 12), child: VerticalFractionBar( color: indicatorColor, fraction: indicatorFraction, ), ), Expanded( child: Wrap( alignment: WrapAlignment.spaceBetween, crossAxisAlignment: WrapCrossAlignment.center, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: textTheme.bodyMedium! .copyWith(fontSize: 16), ), Text( subtitle, style: textTheme.bodyMedium! .copyWith(color: RallyColors.gray60), ), ], ), Text( amount, style: textTheme.bodyLarge!.copyWith( fontSize: 20, color: RallyColors.gray, ), ), ], ), ), Container( constraints: const BoxConstraints(minWidth: 32), padding: const EdgeInsetsDirectional.only(start: 12), child: suffix, ), ], ), ), const Divider( height: 1, indent: 16, endIndent: 16, color: RallyColors.dividerColor, ), ], ), ); }, ), ); } } /// Data model for [FinancialEntityCategoryView]. class FinancialEntityCategoryModel { const FinancialEntityCategoryModel( this.indicatorColor, this.indicatorFraction, this.title, this.subtitle, this.usdAmount, this.suffix, ); final Color indicatorColor; final double indicatorFraction; final String title; final String subtitle; final double usdAmount; final Widget suffix; } FinancialEntityCategoryView buildFinancialEntityFromAccountData( AccountData model, int accountDataIndex, BuildContext context, ) { final amount = usdWithSignFormat(context).format(model.primaryAmount); final shortAccountNumber = model.accountNumber.substring(6); return FinancialEntityCategoryView( suffix: const Icon(Icons.chevron_right, color: Colors.grey), title: model.name, subtitle: '• • • • • • $shortAccountNumber', semanticsLabel: GalleryLocalizations.of(context)!.rallyAccountAmount( model.name, shortAccountNumber, amount, ), indicatorColor: RallyColors.accountColor(accountDataIndex), indicatorFraction: 1, amount: amount, ); } FinancialEntityCategoryView buildFinancialEntityFromBillData( BillData model, int billDataIndex, BuildContext context, ) { final amount = usdWithSignFormat(context).format(model.primaryAmount); return FinancialEntityCategoryView( suffix: const Icon(Icons.chevron_right, color: Colors.grey), title: model.name, subtitle: model.dueDate, semanticsLabel: GalleryLocalizations.of(context)!.rallyBillAmount( model.name, model.dueDate, amount, ), indicatorColor: RallyColors.billColor(billDataIndex), indicatorFraction: 1, amount: amount, ); } FinancialEntityCategoryView buildFinancialEntityFromBudgetData( BudgetData model, int budgetDataIndex, BuildContext context, ) { final amountUsed = usdWithSignFormat(context).format(model.amountUsed); final primaryAmount = usdWithSignFormat(context).format(model.primaryAmount); final amount = usdWithSignFormat(context).format(model.primaryAmount - model.amountUsed); return FinancialEntityCategoryView( suffix: Text( GalleryLocalizations.of(context)!.rallyFinanceLeft, style: Theme.of(context) .textTheme .bodyMedium! .copyWith(color: RallyColors.gray60, fontSize: 10), ), title: model.name, subtitle: '$amountUsed / $primaryAmount', semanticsLabel: GalleryLocalizations.of(context)!.rallyBudgetAmount( model.name, model.amountUsed, model.primaryAmount, amount, ), indicatorColor: RallyColors.budgetColor(budgetDataIndex), indicatorFraction: model.amountUsed / model.primaryAmount, amount: amount, ); } List<FinancialEntityCategoryView> buildAccountDataListViews( List<AccountData> items, BuildContext context, ) { return List<FinancialEntityCategoryView>.generate( items.length, (i) => buildFinancialEntityFromAccountData(items[i], i, context), ); } List<FinancialEntityCategoryView> buildBillDataListViews( List<BillData> items, BuildContext context, ) { return List<FinancialEntityCategoryView>.generate( items.length, (i) => buildFinancialEntityFromBillData(items[i], i, context), ); } List<FinancialEntityCategoryView> buildBudgetDataListViews( List<BudgetData> items, BuildContext context, ) { return <FinancialEntityCategoryView>[ for (int i = 0; i < items.length; i++) buildFinancialEntityFromBudgetData(items[i], i, context) ]; } class FinancialEntityCategoryDetailsPage extends StatelessWidget { FinancialEntityCategoryDetailsPage({super.key}); final List<DetailedEventData> items = DummyDataService.getDetailedEventItems(); @override Widget build(BuildContext context) { final isDesktop = isDisplayDesktop(context); return ApplyTextOptions( child: Scaffold( appBar: AppBar( elevation: 0, centerTitle: true, title: Text( GalleryLocalizations.of(context)!.rallyAccountDataChecking, style: Theme.of(context).textTheme.bodyMedium!.copyWith(fontSize: 18), ), ), body: Column( children: [ SizedBox( height: 200, width: double.infinity, child: RallyLineChart(events: items), ), Expanded( child: Padding( padding: isDesktop ? const EdgeInsets.all(40) : EdgeInsets.zero, child: ListView( shrinkWrap: true, children: [ for (DetailedEventData detailedEventData in items) _DetailedEventCard( title: detailedEventData.title, date: detailedEventData.date, amount: detailedEventData.amount, ), ], ), ), ), ], ), ), ); } } class _DetailedEventCard extends StatelessWidget { const _DetailedEventCard({ required this.title, required this.date, required this.amount, }); final String title; final DateTime date; final double amount; @override Widget build(BuildContext context) { final isDesktop = isDisplayDesktop(context); return TextButton( style: TextButton.styleFrom( foregroundColor: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 16), ), onPressed: () {}, child: Column( children: [ Container( padding: const EdgeInsets.symmetric(vertical: 16), width: double.infinity, child: isDesktop ? Row( children: [ Expanded( flex: 1, child: _EventTitle(title: title), ), _EventDate(date: date), Expanded( flex: 1, child: Align( alignment: AlignmentDirectional.centerEnd, child: _EventAmount(amount: amount), ), ), ], ) : Wrap( alignment: WrapAlignment.spaceBetween, children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ _EventTitle(title: title), _EventDate(date: date), ], ), _EventAmount(amount: amount), ], ), ), SizedBox( height: 1, child: Container( color: RallyColors.dividerColor, ), ), ], ), ); } } class _EventAmount extends StatelessWidget { const _EventAmount({required this.amount}); final double amount; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Text( usdWithSignFormat(context).format(amount), style: textTheme.bodyLarge!.copyWith( fontSize: 20, color: RallyColors.gray, ), ); } } class _EventDate extends StatelessWidget { const _EventDate({required this.date}); final DateTime date; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Text( shortDateFormat(context).format(date), semanticsLabel: longDateFormat(context).format(date), style: textTheme.bodyMedium!.copyWith(color: RallyColors.gray60), ); } } class _EventTitle extends StatelessWidget { const _EventTitle({required this.title}); final String title; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return Text( title, style: textTheme.bodyMedium!.copyWith(fontSize: 16), ); } }
gallery/lib/studies/rally/finance.dart/0
{ "file_path": "gallery/lib/studies/rally/finance.dart", "repo_id": "gallery", "token_count": 7154 }
818
import 'package:animations/animations.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:gallery/layout/adaptive.dart'; import 'package:gallery/studies/reply/colors.dart'; import 'package:gallery/studies/reply/mail_view_page.dart'; import 'package:gallery/studies/reply/model/email_model.dart'; import 'package:gallery/studies/reply/model/email_store.dart'; import 'package:gallery/studies/reply/profile_avatar.dart'; import 'package:provider/provider.dart'; const _assetsPackage = 'flutter_gallery_assets'; const _iconAssetLocation = 'reply/icons'; class MailPreviewCard extends StatelessWidget { const MailPreviewCard({ super.key, required this.id, required this.email, required this.onDelete, required this.onStar, required this.isStarred, required this.onStarredMailbox, }); final int id; final Email email; final VoidCallback onDelete; final VoidCallback onStar; final bool isStarred; final bool onStarredMailbox; @override Widget build(BuildContext context) { final theme = Theme.of(context); // TODO(x): State restoration of mail view page is blocked because OpenContainer does not support restorablePush, https://github.com/flutter/gallery/issues/570. return OpenContainer( openBuilder: (context, closedContainer) { return MailViewPage(id: id, email: email); }, openColor: theme.cardColor, closedShape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(0)), ), closedElevation: 0, closedColor: theme.cardColor, closedBuilder: (context, openContainer) { final isDesktop = isDisplayDesktop(context); final colorScheme = theme.colorScheme; final mailPreview = _MailPreview( id: id, email: email, onTap: openContainer, onStar: onStar, onDelete: onDelete, ); if (isDesktop) { return mailPreview; } else { return Dismissible( key: ObjectKey(email), dismissThresholds: const { DismissDirection.startToEnd: 0.8, DismissDirection.endToStart: 0.4, }, onDismissed: (direction) { switch (direction) { case DismissDirection.endToStart: if (onStarredMailbox) { onStar(); } break; case DismissDirection.startToEnd: onDelete(); break; default: } }, background: _DismissibleContainer( icon: 'twotone_delete', backgroundColor: colorScheme.primary, iconColor: ReplyColors.blue50, alignment: Alignment.centerLeft, padding: const EdgeInsetsDirectional.only(start: 20), ), confirmDismiss: (direction) async { if (direction == DismissDirection.endToStart) { if (onStarredMailbox) { return true; } onStar(); return false; } else { return true; } }, secondaryBackground: _DismissibleContainer( icon: 'twotone_star', backgroundColor: isStarred ? colorScheme.secondary : theme.scaffoldBackgroundColor, iconColor: isStarred ? colorScheme.onSecondary : colorScheme.onBackground, alignment: Alignment.centerRight, padding: const EdgeInsetsDirectional.only(end: 20), ), child: mailPreview, ); } }, ); } } class _DismissibleContainer extends StatelessWidget { const _DismissibleContainer({ required this.icon, required this.backgroundColor, required this.iconColor, required this.alignment, required this.padding, }); final String icon; final Color backgroundColor; final Color iconColor; final Alignment alignment; final EdgeInsetsDirectional padding; @override Widget build(BuildContext context) { return AnimatedContainer( alignment: alignment, curve: standardEasing, color: backgroundColor, duration: kThemeAnimationDuration, padding: padding, child: Material( color: Colors.transparent, child: ImageIcon( AssetImage( 'reply/icons/$icon.png', package: 'flutter_gallery_assets', ), size: 36, color: iconColor, ), ), ); } } class _MailPreview extends StatelessWidget { const _MailPreview({ required this.id, required this.email, required this.onTap, this.onStar, this.onDelete, }); final int id; final Email email; final VoidCallback onTap; final VoidCallback? onStar; final VoidCallback? onDelete; @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; var emailStore = Provider.of<EmailStore>( context, listen: false, ); return InkWell( onTap: () { Provider.of<EmailStore>( context, listen: false, ).selectedEmailId = id; onTap(); }, child: LayoutBuilder( builder: (context, constraints) { return ConstrainedBox( constraints: BoxConstraints(maxHeight: constraints.maxHeight), child: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Row( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Text( '${email.sender} - ${email.time}', style: textTheme.bodySmall, ), const SizedBox(height: 4), Text(email.subject, style: textTheme.headlineSmall), const SizedBox(height: 16), ], ), ), _MailPreviewActionBar( avatar: email.avatar, isStarred: emailStore.isEmailStarred(email.id), onStar: onStar, onDelete: onDelete, ), ], ), Padding( padding: const EdgeInsetsDirectional.only( end: 20, ), child: Text( email.message, overflow: TextOverflow.ellipsis, maxLines: 1, style: textTheme.bodyMedium, ), ), if (email.containsPictures) ...[ const Flexible( fit: FlexFit.loose, child: Column( children: [ SizedBox(height: 20), _PicturePreview(), ], ), ), ], ], ), ), ); }, ), ); } } class _PicturePreview extends StatelessWidget { const _PicturePreview(); bool _shouldShrinkImage() { switch (defaultTargetPlatform) { case TargetPlatform.iOS: case TargetPlatform.android: return true; default: return false; } } @override Widget build(BuildContext context) { return SizedBox( height: 96, child: ListView.builder( itemCount: 4, scrollDirection: Axis.horizontal, itemBuilder: (context, index) { return Padding( padding: const EdgeInsetsDirectional.only(end: 4), child: Image.asset( 'reply/attachments/paris_${index + 1}.jpg', gaplessPlayback: true, package: 'flutter_gallery_assets', cacheWidth: _shouldShrinkImage() ? 200 : null, ), ); }, ), ); } } class _MailPreviewActionBar extends StatelessWidget { const _MailPreviewActionBar({ required this.avatar, required this.isStarred, this.onStar, this.onDelete, }); final String avatar; final bool isStarred; final VoidCallback? onStar; final VoidCallback? onDelete; @override Widget build(BuildContext context) { final isDark = Theme.of(context).brightness == Brightness.dark; final color = isDark ? ReplyColors.white50 : ReplyColors.blue600; final isDesktop = isDisplayDesktop(context); final starredIconColor = isStarred ? Theme.of(context).colorScheme.secondary : color; return Row( children: [ if (isDesktop) ...[ IconButton( icon: ImageIcon( const AssetImage( '$_iconAssetLocation/twotone_star.png', package: _assetsPackage, ), color: starredIconColor, ), onPressed: onStar, ), IconButton( icon: ImageIcon( const AssetImage( '$_iconAssetLocation/twotone_delete.png', package: _assetsPackage, ), color: color, ), onPressed: onDelete, ), IconButton( icon: Icon( Icons.more_vert, color: color, ), onPressed: () {}, ), const SizedBox(width: 12), ], ProfileAvatar(avatar: avatar), ], ); } }
gallery/lib/studies/reply/mail_card_preview.dart/0
{ "file_path": "gallery/lib/studies/reply/mail_card_preview.dart", "repo_id": "gallery", "token_count": 5294 }
819
// Copyright 2019 The Flutter team. 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:gallery/studies/shrine/model/product.dart'; import 'package:gallery/studies/shrine/model/products_repository.dart'; import 'package:scoped_model/scoped_model.dart'; double _salesTaxRate = 0.06; double _shippingCostPerItem = 7; class AppStateModel extends Model { // All the available products. List<Product> _availableProducts = []; // The currently selected category of products. Category _selectedCategory = categoryAll; // The IDs and quantities of products currently in the cart. final Map<int, int> _productsInCart = <int, int>{}; Map<int, int> get productsInCart => Map<int, int>.from(_productsInCart); // Total number of items in the cart. int get totalCartQuantity => _productsInCart.values.fold(0, (v, e) => v + e); Category get selectedCategory => _selectedCategory; // Totaled prices of the items in the cart. double get subtotalCost { return _productsInCart.keys .map((id) => _availableProducts[id].price * _productsInCart[id]!) .fold(0.0, (sum, e) => sum + e); } // Total shipping cost for the items in the cart. double get shippingCost { return _shippingCostPerItem * _productsInCart.values.fold(0.0, (sum, e) => sum + e); } // Sales tax for the items in the cart double get tax => subtotalCost * _salesTaxRate; // Total cost to order everything in the cart. double get totalCost => subtotalCost + shippingCost + tax; // Returns a copy of the list of available products, filtered by category. List<Product> getProducts() { if (_selectedCategory == categoryAll) { return List<Product>.from(_availableProducts); } else { return _availableProducts .where((p) => p.category == _selectedCategory) .toList(); } } // Adds a product to the cart. void addProductToCart(int productId) { if (!_productsInCart.containsKey(productId)) { _productsInCart[productId] = 1; } else { _productsInCart[productId] = _productsInCart[productId]! + 1; } notifyListeners(); } // Adds products to the cart by a certain amount. // quantity must be non-null positive value. void addMultipleProductsToCart(int productId, int quantity) { assert(quantity > 0); if (!_productsInCart.containsKey(productId)) { _productsInCart[productId] = quantity; } else { _productsInCart[productId] = _productsInCart[productId]! + quantity; } notifyListeners(); } // Removes an item from the cart. void removeItemFromCart(int productId) { if (_productsInCart.containsKey(productId)) { if (_productsInCart[productId] == 1) { _productsInCart.remove(productId); } else { _productsInCart[productId] = _productsInCart[productId]! - 1; } } notifyListeners(); } // Returns the Product instance matching the provided id. Product getProductById(int id) { return _availableProducts.firstWhere((p) => p.id == id); } // Removes everything from the cart. void clearCart() { _productsInCart.clear(); notifyListeners(); } // Loads the list of available products from the repo. void loadProducts() { _availableProducts = ProductsRepository.loadProducts(categoryAll); notifyListeners(); } void setCategory(Category newCategory) { _selectedCategory = newCategory; notifyListeners(); } @override String toString() { return 'AppStateModel(totalCost: $totalCost)'; } }
gallery/lib/studies/shrine/model/app_state_model.dart/0
{ "file_path": "gallery/lib/studies/shrine/model/app_state_model.dart", "repo_id": "gallery", "token_count": 1209 }
820
// Copyright 2019 The Flutter team. 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:flutter_gen/gen_l10n/gallery_localizations.dart'; import 'package:gallery/data/gallery_options.dart'; import 'package:gallery/studies/starter/home.dart'; import 'package:gallery/studies/starter/routes.dart' as routes; const _primaryColor = Color(0xFF6200EE); class StarterApp extends StatelessWidget { const StarterApp({super.key}); static const String defaultRoute = routes.defaultRoute; @override Widget build(BuildContext context) { return MaterialApp( restorationScopeId: 'starter_app', title: GalleryLocalizations.of(context)!.starterAppTitle, debugShowCheckedModeBanner: false, localizationsDelegates: GalleryLocalizations.localizationsDelegates, supportedLocales: GalleryLocalizations.supportedLocales, locale: GalleryOptions.of(context).locale, initialRoute: StarterApp.defaultRoute, routes: { StarterApp.defaultRoute: (context) => const _Home(), }, theme: ThemeData( highlightColor: Colors.transparent, colorScheme: const ColorScheme( primary: _primaryColor, primaryContainer: Color(0xFF3700B3), secondary: Color(0xFF03DAC6), secondaryContainer: Color(0xFF018786), background: Colors.white, surface: Colors.white, onBackground: Colors.black, error: Color(0xFFB00020), onError: Colors.white, onPrimary: Colors.white, onSecondary: Colors.black, onSurface: Colors.black, brightness: Brightness.light, ), dividerTheme: const DividerThemeData( thickness: 1, color: Color(0xFFE5E5E5), ), platform: GalleryOptions.of(context).platform, ), ); } } class _Home extends StatelessWidget { const _Home(); @override Widget build(BuildContext context) { return const ApplyTextOptions( child: HomePage(), ); } }
gallery/lib/studies/starter/app.dart/0
{ "file_path": "gallery/lib/studies/starter/app.dart", "repo_id": "gallery", "token_count": 824 }
821
// Copyright 2019 The Flutter team. 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:test/test.dart'; import '../tool/codeviewer_cli/segment_generator.dart'; import 'utils.dart'; void main() { bool compareCodeSegments(String a, String b) { return standardizeLineEndings(a) == standardizeLineEndings(b); } test('verify code segments are up to date', () async { final currentCodeSegments = readCodeSegments(); var newCodeSegments = await getCodeSegments(); expect(compareCodeSegments(currentCodeSegments, newCodeSegments), true, reason: 'code_segments.dart is not up to date. ' 'Did you forget to run `dart run grinder update-code-segments`?'); }, onPlatform: <String, dynamic>{ 'linux': [ const Skip('TODO: figure out why this test fails on Linux.'), ], }); }
gallery/test/code_segments_test.dart/0
{ "file_path": "gallery/test/code_segments_test.dart", "repo_id": "gallery", "token_count": 312 }
822
// Copyright 2020 The Flutter team. 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' show JsonEncoder; import 'dart:io'; import 'package:test/test.dart'; import 'package:web_benchmarks/server.dart'; import 'benchmarks/common.dart'; import 'benchmarks/project_root_directory.dart'; final metricList = <String>[ 'preroll_frame', 'apply_frame', 'drawFrameDuration', ]; final valueList = <String>[ 'average', 'outlierAverage', 'outlierRatio', 'noise', ]; /// Tests that the Gallery web benchmarks are run and reported correctly. Future<void> main() async { test('Can run a web benchmark', () async { stdout.writeln('Starting web benchmark tests ...'); final taskResult = await serveWebBenchmark( benchmarkAppDirectory: projectRootDirectory(), entryPoint: 'test_benchmarks/benchmarks/client.dart', useCanvasKit: false, ); stdout.writeln('Web benchmark tests finished.'); expect(taskResult.scores.keys, hasLength(benchmarkList.length)); for (final benchmarkName in benchmarkList) { expect( taskResult.scores[benchmarkName], hasLength(metricList.length * valueList.length + 1), ); for (final metricName in metricList) { for (final valueName in valueList) { expect( taskResult.scores[benchmarkName]?.where( (score) => score.metric == '$metricName.$valueName', ), hasLength(1), ); } } expect( taskResult.scores[benchmarkName]?.where( (score) => score.metric == 'totalUiFrame.average', ), hasLength(1), ); } expect( const JsonEncoder.withIndent(' ').convert(taskResult.toJson()), isA<String>(), ); }, timeout: Timeout.none, skip: true); // TODO(guidezpl): re-enable these benchmarks https://github.com/flutter/gallery/issues/903 }
gallery/test_benchmarks/benchmarks_test.dart/0
{ "file_path": "gallery/test_benchmarks/benchmarks_test.dart", "repo_id": "gallery", "token_count": 793 }
823
// Copyright 2019 The Flutter team. 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; /// Precache images to make sure they show up in golden tests. Future<void> pumpWidgetWithImages( WidgetTester tester, Widget widget, List<AssetImage> assets, ) async { Future<void>? precacheFuture; await tester.pumpWidget( Builder(builder: (buildContext) { precacheFuture = tester.runAsync(() async { await Future.wait([ for (final asset in assets) precacheImage( asset, buildContext, ), ]); }); return widget; }), ); await precacheFuture; }
gallery/test_goldens/testing/precache_images.dart/0
{ "file_path": "gallery/test_goldens/testing/precache_images.dart", "repo_id": "gallery", "token_count": 317 }
824