text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
{ "datePickerHourSemanticsLabelOne": "Ordu$houra da", "datePickerHourSemanticsLabelOther": "$hourak dira", "datePickerMinuteSemanticsLabelOne": "Minutu bat", "datePickerMinuteSemanticsLabelOther": "$minute minutu", "datePickerDateOrder": "ymd", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Gaur", "alertDialogLabel": "Alerta", "timerPickerHourLabelOne": "ordu", "timerPickerHourLabelOther": "ordu", "timerPickerMinuteLabelOne": "min.", "timerPickerMinuteLabelOther": "min.", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Ebaki", "copyButtonLabel": "Kopiatu", "pasteButtonLabel": "Itsatsi", "selectAllButtonLabel": "Hautatu dena", "tabSemanticsLabel": "$tabIndex/$tabCount fitxa", "modalBarrierDismissLabel": "Baztertu", "searchTextFieldPlaceholderLabel": "Bilatu", "noSpellCheckReplacementsLabel": "Ez da aurkitu ordezteko hitzik", "menuDismissLabel": "Baztertu menua", "lookUpButtonLabel": "Bilatu", "searchWebButtonLabel": "Bilatu sarean", "shareButtonLabel": "Partekatu...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_eu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_eu.arb", "repo_id": "flutter", "token_count": 439 }
712
{ "datePickerHourSemanticsLabelOne": "$hour in punto", "datePickerHourSemanticsLabelOther": "$hour in punto", "datePickerMinuteSemanticsLabelOne": "1 minuto", "datePickerMinuteSemanticsLabelOther": "$minute minuti", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Oggi", "alertDialogLabel": "Avviso", "timerPickerHourLabelOne": "ora", "timerPickerHourLabelOther": "ore", "timerPickerMinuteLabelOne": "min.", "timerPickerMinuteLabelOther": "min.", "timerPickerSecondLabelOne": "sec.", "timerPickerSecondLabelOther": "sec.", "cutButtonLabel": "Taglia", "copyButtonLabel": "Copia", "pasteButtonLabel": "Incolla", "selectAllButtonLabel": "Seleziona tutto", "tabSemanticsLabel": "Scheda $tabIndex di $tabCount", "modalBarrierDismissLabel": "Ignora", "searchTextFieldPlaceholderLabel": "Cerca", "noSpellCheckReplacementsLabel": "Nessuna sostituzione trovata", "menuDismissLabel": "Ignora menu", "lookUpButtonLabel": "Cerca", "searchWebButtonLabel": "Cerca sul web", "shareButtonLabel": "Condividi…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_it.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_it.arb", "repo_id": "flutter", "token_count": 426 }
713
{ "datePickerHourSemanticsLabelOne": "$hour နာရီ", "datePickerHourSemanticsLabelOther": "$hour နာရီ", "datePickerMinuteSemanticsLabelOne": "၁ မိနစ်", "datePickerMinuteSemanticsLabelOther": "$minute မိနစ်", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "ယနေ့", "alertDialogLabel": "သတိပေးချက်", "timerPickerHourLabelOne": "နာရီ", "timerPickerHourLabelOther": "နာရီ", "timerPickerMinuteLabelOne": "မိနစ်", "timerPickerMinuteLabelOther": "မိနစ်", "timerPickerSecondLabelOne": "စက္ကန့်", "timerPickerSecondLabelOther": "စက္ကန့်", "cutButtonLabel": "ဖြတ်ယူရန်", "copyButtonLabel": "မိတ္တူကူးရန်", "pasteButtonLabel": "ကူးထည့်ရန်", "selectAllButtonLabel": "အားလုံး ရွေးရန်", "tabSemanticsLabel": "တဘ် $tabCount ခုအနက် $tabIndex ခု", "modalBarrierDismissLabel": "ပယ်ရန်", "searchTextFieldPlaceholderLabel": "ရှာရန်", "noSpellCheckReplacementsLabel": "အစားထိုးမှုများ မတွေ့ပါ", "menuDismissLabel": "မီနူးကိုပယ်ပါ", "lookUpButtonLabel": "အပေါ်ကြည့်ရန်", "searchWebButtonLabel": "ဝဘ်တွင်ရှာရန်", "shareButtonLabel": "မျှဝေရန်...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_my.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_my.arb", "repo_id": "flutter", "token_count": 964 }
714
{ "datePickerHourSemanticsLabelFew": "$hour сата", "datePickerMinuteSemanticsLabelFew": "$minute минута", "timerPickerHourLabelFew": "сата", "timerPickerMinuteLabelFew": "мин", "timerPickerSecondLabelFew": "сек", "datePickerHourSemanticsLabelOne": "$hour сат", "datePickerHourSemanticsLabelOther": "$hour сати", "datePickerMinuteSemanticsLabelOne": "1 минут", "datePickerMinuteSemanticsLabelOther": "$minute минута", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "пре подне", "postMeridiemAbbreviation": "по подне", "todayLabel": "Данас", "alertDialogLabel": "Обавештење", "timerPickerHourLabelOne": "сат", "timerPickerHourLabelOther": "сати", "timerPickerMinuteLabelOne": "мин", "timerPickerMinuteLabelOther": "мин", "timerPickerSecondLabelOne": "сек", "timerPickerSecondLabelOther": "сек", "cutButtonLabel": "Исеци", "copyButtonLabel": "Копирај", "pasteButtonLabel": "Налепи", "selectAllButtonLabel": "Изабери све", "tabSemanticsLabel": "$tabIndex. картица од $tabCount", "modalBarrierDismissLabel": "Одбаци", "searchTextFieldPlaceholderLabel": "Претражите", "noSpellCheckReplacementsLabel": "Нису пронађене замене", "menuDismissLabel": "Одбаците мени", "lookUpButtonLabel": "Поглед нагоре", "searchWebButtonLabel": "Претражи веб", "shareButtonLabel": "Дели…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sr.arb", "repo_id": "flutter", "token_count": 672 }
715
{ "datePickerHourSemanticsLabelOne": "$hour ezimpondweni", "datePickerHourSemanticsLabelOther": "$hour ezimpondweni", "datePickerMinuteSemanticsLabelOne": "1 iminithi", "datePickerMinuteSemanticsLabelOther": "$minute amaminithi", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Namuhla", "alertDialogLabel": "Isexwayiso", "timerPickerHourLabelOne": "ihora", "timerPickerHourLabelOther": "amahora", "timerPickerMinuteLabelOne": "iminithi.", "timerPickerMinuteLabelOther": "iminithi.", "timerPickerSecondLabelOne": "isekhondi.", "timerPickerSecondLabelOther": "isekhondi.", "cutButtonLabel": "Sika", "copyButtonLabel": "Kopisha", "pasteButtonLabel": "Namathisela", "selectAllButtonLabel": "Khetha konke", "tabSemanticsLabel": "Ithebhu $tabIndex kwangu-$tabCount", "modalBarrierDismissLabel": "Cashisa", "searchTextFieldPlaceholderLabel": "Sesha", "noSpellCheckReplacementsLabel": "Akukho Okuzofakwa Esikhundleni Okutholakele", "menuDismissLabel": "Chitha imenyu", "lookUpButtonLabel": "Bheka Phezulu", "searchWebButtonLabel": "Sesha Iwebhu", "shareButtonLabel": "Yabelana...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_zu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_zu.arb", "repo_id": "flutter", "token_count": 476 }
716
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "remainingTextFieldCharacterCountMany": "$remainingCount nod ar ôl", "licensesPackageDetailTextTwo": "$licenseCount drwydded", "licensesPackageDetailTextFew": "$licenseCount trwydded", "licensesPackageDetailTextMany": "$licenseCount thrwydded", "selectedRowCountTitleTwo": "Mae $selectedRowCount eitem wedi'u dewis", "selectedRowCountTitleFew": "Mae $selectedRowCount eitem wedi'u dewis", "selectedRowCountTitleMany": "Mae $selectedRowCount eitem wedi'u dewis", "remainingTextFieldCharacterCountFew": "$remainingCount nod ar ôl", "remainingTextFieldCharacterCountTwo": "$remainingCount nod ar ôl", "openAppDrawerTooltip": "Agor y ddewislen llywio", "backButtonTooltip": "Nôl", "closeButtonTooltip": "Cau", "deleteButtonTooltip": "Dileu", "moreButtonTooltip": "Rhagor", "nextMonthTooltip": "Mis nesaf", "previousMonthTooltip": "Mis blaenorol", "nextPageTooltip": "Tudalen nesaf", "previousPageTooltip": "Tudalen flaenorol", "firstPageTooltip": "Tudalen gyntaf", "lastPageTooltip": "Tudalen olaf", "showMenuTooltip": "Dangos y ddewislen", "scrimLabel": "Scrim", "bottomSheetLabel": "Taflen Gwaelod", "scrimOnTapHint": "Cau $modalRouteContentName", "aboutListTileTitle": "Ynghylch $applicationName", "licensesPageTitle": "Trwyddedau", "licensesPackageDetailTextZero": "Dim trwydded", "licensesPackageDetailTextOne": "1 trwydded", "licensesPackageDetailTextOther": "$licenseCount trwydded", "pageRowsInfoTitle": "$firstRow–$lastRow o $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow o tua $rowCount", "rowsPerPageTitle": "Rhesi fesul tudalen:", "tabLabel": "Tab $tabIndex o $tabCount", "selectedRowCountTitleZero": "Nid oes unrhyw eitemau wedi'u dewis", "selectedRowCountTitleOne": "Mae 1 eitem wedi'i dewis", "selectedRowCountTitleOther": "Mae $selectedRowCount eitem wedi'u dewis", "cancelButtonLabel": "Canslo", "closeButtonLabel": "Cau", "continueButtonLabel": "Parhau", "copyButtonLabel": "Copïo", "cutButtonLabel": "Torri", "okButtonLabel": "Iawn", "pasteButtonLabel": "Gludo", "selectAllButtonLabel": "Dewis y Cyfan", "viewLicensesButtonLabel": "Gweld trwyddedau", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Dewis oriau", "timePickerMinuteModeAnnouncement": "Dewis munudau", "modalBarrierDismissLabel": "Diystyru", "dateSeparator": "/", "dateHelpText": "dd/mm/bbbb", "selectYearSemanticsLabel": "Dewiswch flwyddyn", "unspecifiedDate": "Dyddiad", "unspecifiedDateRange": "Ystod Dyddiadau", "dateInputLabel": "Rhowch Ddyddiad", "dateRangeStartLabel": "Dyddiad Dechrau", "dateRangeEndLabel": "Dyddiad Gorffen", "dateRangeStartDateSemanticLabel": "Dyddiad dechrau $fullDate", "dateRangeEndDateSemanticLabel": "Dyddiad gorffen $fullDate", "invalidDateFormatLabel": "Fformat annilys.", "invalidDateRangeLabel": "Ystod annilys.", "dateOutOfRangeLabel": "Allan o'r ystod.", "saveButtonLabel": "Cadw", "datePickerHelpText": "Dewiswch ddyddiad", "dateRangePickerHelpText": "Dewis ystod", "calendarModeButtonLabel": "Newid i galendr", "inputDateModeButtonLabel": "Newid i fewnbwn", "timePickerDialHelpText": "Dewiswch amser", "timePickerInputHelpText": "Rhowch amser", "timePickerHourLabel": "Awr", "timePickerMinuteLabel": "Munud", "invalidTimeLabel": "Rhowch amser dilys", "dialModeButtonLabel": "Newid i fodd deialu dewiswr", "inputTimeModeButtonLabel": "Newid i fodd mewnbwn testun", "signedInLabel": "Wedi mewngofnodi", "hideAccountsLabel": "Cuddio cyfrifon", "showAccountsLabel": "Dangos cyfrifon", "drawerLabel": "Dewislen llywio", "menuBarMenuLabel": "Dewislen bar dewislen", "popupMenuLabel": "Dewislen ffenestr naid", "dialogLabel": "Deialog", "alertDialogLabel": "Rhybudd", "searchFieldLabel": "Chwilio", "currentDateLabel": "Heddiw", "reorderItemToStart": "Symud i'r dechrau", "reorderItemToEnd": "Symud i'r diwedd", "reorderItemUp": "Symud i fyny", "reorderItemDown": "Symud i lawr", "reorderItemLeft": "Symud i'r chwith", "reorderItemRight": "Symud i'r dde", "expandedIconTapHint": "Crebachu", "collapsedIconTapHint": "Ehangu", "remainingTextFieldCharacterCountZero": "Dim nodau ar ôl", "remainingTextFieldCharacterCountOne": "1 nod ar ôl", "remainingTextFieldCharacterCountOther": "$remainingCount nod ar ôl", "refreshIndicatorSemanticLabel": "Ail-lwytho", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "Gorffen", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "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", "keyboardKeyShift": "Shift", "keyboardKeySpace": "Space", "expansionTileExpandedHint": "tapiwch ddwywaith i grebachu", "expansionTileCollapsedHint": "tapiwch ddwywaith i ehangu", "expansionTileExpandedTapHint": "Crebachu", "expansionTileCollapsedTapHint": "Ehangwch am ragor o fanylion", "expandedHint": "Wedi'i grebachu", "collapsedHint": "Wedi'i ehangu", "scanTextButtonLabel": "Sganio testun", "menuDismissLabel": "Diystyru'r ddewislen", "lookUpButtonLabel": "Chwilio", "searchWebButtonLabel": "Chwilio'r We", "shareButtonLabel": "Rhannu...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_cy.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_cy.arb", "repo_id": "flutter", "token_count": 2597 }
717
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "openAppDrawerTooltip": "Navigációs menü megnyitása", "backButtonTooltip": "Vissza", "closeButtonTooltip": "Bezárás", "deleteButtonTooltip": "Törlés", "nextMonthTooltip": "Következő hónap", "previousMonthTooltip": "Előző hónap", "nextPageTooltip": "Következő oldal", "previousPageTooltip": "Előző oldal", "firstPageTooltip": "Első oldal", "lastPageTooltip": "Utolsó oldal", "showMenuTooltip": "Menü megjelenítése", "aboutListTileTitle": "A(z) $applicationName névjegye", "licensesPageTitle": "Licencek", "pageRowsInfoTitle": "$rowCount/$firstRow–$lastRow.", "pageRowsInfoTitleApproximate": "Körülbelül $rowCount/$firstRow–$lastRow.", "rowsPerPageTitle": "Oldalankénti sorszám:", "tabLabel": "$tabCount/$tabIndex. lap", "selectedRowCountTitleOne": "1 elem kiválasztva", "selectedRowCountTitleOther": "$selectedRowCount elem kiválasztva", "cancelButtonLabel": "Mégse", "closeButtonLabel": "Bezárás", "continueButtonLabel": "Folytatás", "copyButtonLabel": "Másolás", "cutButtonLabel": "Kivágás", "scanTextButtonLabel": "Szöveg beolvasása", "okButtonLabel": "OK", "pasteButtonLabel": "Beillesztés", "selectAllButtonLabel": "Összes kijelölése", "viewLicensesButtonLabel": "Licencek megtekintése", "anteMeridiemAbbreviation": "de.", "postMeridiemAbbreviation": "du.", "timePickerHourModeAnnouncement": "Óra kiválasztása", "timePickerMinuteModeAnnouncement": "Perc kiválasztása", "modalBarrierDismissLabel": "Elvetés", "signedInLabel": "Bejelentkezve", "hideAccountsLabel": "Fiókok elrejtése", "showAccountsLabel": "Fiókok megjelenítése", "drawerLabel": "Navigációs menü", "popupMenuLabel": "Előugró menü", "dialogLabel": "Párbeszédablak", "alertDialogLabel": "Értesítés", "searchFieldLabel": "Keresés", "reorderItemToStart": "Áthelyezés az elejére", "reorderItemToEnd": "Áthelyezés a végére", "reorderItemUp": "Áthelyezés felfelé", "reorderItemDown": "Áthelyezés lefelé", "reorderItemLeft": "Áthelyezés balra", "reorderItemRight": "Áthelyezés jobbra", "expandedIconTapHint": "Összecsukás", "collapsedIconTapHint": "Kibontás", "remainingTextFieldCharacterCountOne": "1 karakter maradt", "remainingTextFieldCharacterCountOther": "$remainingCount karakter maradt", "refreshIndicatorSemanticLabel": "Frissítés", "moreButtonTooltip": "Több", "dateSeparator": ".", "dateHelpText": "éééé. hh. nn.", "selectYearSemanticsLabel": "Válassza ki az évet", "unspecifiedDate": "Dátum", "unspecifiedDateRange": "Dátumtartomány", "dateInputLabel": "Adja meg a dátumot", "dateRangeStartLabel": "Kezdés dátuma", "dateRangeEndLabel": "Befejezés dátuma", "dateRangeStartDateSemanticLabel": "Kezdés dátuma: $fullDate", "dateRangeEndDateSemanticLabel": "Befejezés dátuma: $fullDate", "invalidDateFormatLabel": "Érvénytelen formátum.", "invalidDateRangeLabel": "Érvénytelen tartomány.", "dateOutOfRangeLabel": "Tartományon kívül.", "saveButtonLabel": "Mentés", "datePickerHelpText": "Dátum kiválasztása", "dateRangePickerHelpText": "Dátumtartomány kiválasztása", "calendarModeButtonLabel": "Váltás naptárra", "inputDateModeButtonLabel": "Váltás bevitelre", "timePickerDialHelpText": "Időpont kiválasztása", "timePickerInputHelpText": "Időpont megadása", "timePickerHourLabel": "Óra", "timePickerMinuteLabel": "Perc", "invalidTimeLabel": "Érvényes formátumban adja meg az időt", "dialModeButtonLabel": "Váltás időpontválasztó módra", "inputTimeModeButtonLabel": "Váltás szövegbeviteli módra", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licenc", "licensesPackageDetailTextOther": "$licenseCount licenc", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Csatorna – le", "keyboardKeyChannelUp": "Csatorna – fel", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Kiadás", "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": "Bekapcsolás", "keyboardKeyPowerOff": "Kikapcsolás", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Kiválasztás", "keyboardKeySpace": "Szóköz", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menüsor menüje", "currentDateLabel": "Ma", "scrimLabel": "Borítás", "bottomSheetLabel": "Alsó lap", "scrimOnTapHint": "$modalRouteContentName bezárása", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "duplán koppintva összecsukhatja", "expansionTileCollapsedHint": "duplán koppintva kibonthatja", "expansionTileExpandedTapHint": "Összecsukás", "expansionTileCollapsedTapHint": "Bontsa ki a további részletek megtekintéséhez", "expandedHint": "Összecsukva", "collapsedHint": "Kibontva", "menuDismissLabel": "Menü bezárása", "lookUpButtonLabel": "Felfelé nézés", "searchWebButtonLabel": "Keresés az interneten", "shareButtonLabel": "Megosztás…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_hu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_hu.arb", "repo_id": "flutter", "token_count": 2550 }
718
{ "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": "ഒരു ഇനം തിരഞ്ഞെടുത്തു", "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": "ഒരു പ്രതീകം ശേഷിക്കുന്നു", "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": "ഒരു ലൈസൻസ്", "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_ml.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ml.arb", "repo_id": "flutter", "token_count": 5767 }
719
{ "licensesPackageDetailTextFew": "$licenseCount лицензии", "licensesPackageDetailTextMany": "$licenseCount лицензий", "remainingTextFieldCharacterCountFew": "Осталось $remainingCount символа", "remainingTextFieldCharacterCountMany": "Осталось $remainingCount символов", "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "selectedRowCountTitleFew": "Выбрано $selectedRowCount объекта", "selectedRowCountTitleMany": "Выбрано $selectedRowCount объектов", "openAppDrawerTooltip": "Открыть меню навигации", "backButtonTooltip": "Назад", "closeButtonTooltip": "Закрыть", "deleteButtonTooltip": "Удалить", "nextMonthTooltip": "Следующий месяц", "previousMonthTooltip": "Предыдущий месяц", "nextPageTooltip": "Следующая страница", "previousPageTooltip": "Предыдущая страница", "firstPageTooltip": "Первая страница", "lastPageTooltip": "Последняя страница", "showMenuTooltip": "Показать меню", "pageRowsInfoTitle": "$firstRow–$lastRow из $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow из примерно $rowCount", "rowsPerPageTitle": "Строк на странице:", "tabLabel": "Вкладка $tabIndex из $tabCount", "aboutListTileTitle": "$applicationName: сведения", "licensesPageTitle": "Лицензии", "selectedRowCountTitleZero": "Строки не выбраны", "selectedRowCountTitleOne": "Выбран 1 объект", "selectedRowCountTitleOther": "Выбрано $selectedRowCount объекта", "cancelButtonLabel": "Отмена", "closeButtonLabel": "Закрыть", "continueButtonLabel": "Продолжить", "copyButtonLabel": "Копировать", "cutButtonLabel": "Вырезать", "scanTextButtonLabel": "Сканировать текст", "okButtonLabel": "ОК", "pasteButtonLabel": "Вставить", "selectAllButtonLabel": "Выбрать все", "viewLicensesButtonLabel": "Посмотреть лицензии", "anteMeridiemAbbreviation": "АМ", "postMeridiemAbbreviation": "PM", "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": "дд.мм.гггг", "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": "Следующий канал", "keyboardKeyChannelUp": "Предыдущий канал", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Извлечь", "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 Ввод", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "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_ru.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ru.arb", "repo_id": "flutter", "token_count": 3587 }
720
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "Navigatsiya menyusini ochish", "backButtonTooltip": "Orqaga", "closeButtonTooltip": "Yopish", "deleteButtonTooltip": "Olib tashlash", "nextMonthTooltip": "Keyingi oy", "previousMonthTooltip": "Avvalgi oy", "nextPageTooltip": "Keyingi sahifa", "previousPageTooltip": "Avvalgi sahifa", "firstPageTooltip": "Birinchi sahifa", "lastPageTooltip": "Oxirgi sahifa", "showMenuTooltip": "Menyuni koʻrsatish", "aboutListTileTitle": "$applicationName haqida", "licensesPageTitle": "Litsenziyalar", "pageRowsInfoTitle": "$firstRow–$lastRow, jami: $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow, jami: $rowCount", "rowsPerPageTitle": "Har bir sahifadagi qatorlar soni:", "tabLabel": "$tabCount varaqdan $tabIndex", "selectedRowCountTitleOne": "1 ta element tanlandi", "selectedRowCountTitleOther": "$selectedRowCount ta element tanlandi", "cancelButtonLabel": "Bekor qilish", "closeButtonLabel": "Yopish", "continueButtonLabel": "Davom etish", "copyButtonLabel": "Nusxa olish", "cutButtonLabel": "Kesib olish", "scanTextButtonLabel": "Matnni skanerlash", "okButtonLabel": "OK", "pasteButtonLabel": "Joylash", "selectAllButtonLabel": "Hammasi", "viewLicensesButtonLabel": "Litsenziyalarni koʻrish", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Soatni tanlang", "timePickerMinuteModeAnnouncement": "Daqiqani tanlang", "modalBarrierDismissLabel": "Yopish", "signedInLabel": "Hisobingizga kirgansiz", "hideAccountsLabel": "Hisoblarni berkitish", "showAccountsLabel": "Hisoblarni koʻrsatish", "drawerLabel": "Navigatsiya menyusi", "popupMenuLabel": "Pop-ap menyusi", "dialogLabel": "Muloqot oynasi", "alertDialogLabel": "Ogohlantirish", "searchFieldLabel": "Qidirish", "reorderItemToStart": "Boshiga siljitish", "reorderItemToEnd": "Oxiriga siljitish", "reorderItemUp": "Tepaga siljitish", "reorderItemDown": "Pastga siljitish", "reorderItemLeft": "Chapga siljitish", "reorderItemRight": "Oʻngga siljitish", "expandedIconTapHint": "Kichraytirish", "collapsedIconTapHint": "Yoyish", "remainingTextFieldCharacterCountOne": "1 ta belgi qoldi", "remainingTextFieldCharacterCountOther": "$remainingCount ta belgi qoldi", "refreshIndicatorSemanticLabel": "Yangilash", "moreButtonTooltip": "Yana", "dateSeparator": "/", "dateHelpText": "mm/dd/yyyy", "selectYearSemanticsLabel": "Yilni tanlang", "unspecifiedDate": "Sana", "unspecifiedDateRange": "Sana oraligʻi", "dateInputLabel": "Sanani kiriting", "dateRangeStartLabel": "Boshlanish sanasi", "dateRangeEndLabel": "Tugash sanasi", "dateRangeStartDateSemanticLabel": "Boshlanish sanasi: $fullDate", "dateRangeEndDateSemanticLabel": "Tugash sanasi: $fullDate", "invalidDateFormatLabel": "Yaroqsiz format.", "invalidDateRangeLabel": "Yaroqsiz oraliq.", "dateOutOfRangeLabel": "Diapazondan tashqarida.", "saveButtonLabel": "Saqlash", "datePickerHelpText": "Sanani tanlang", "dateRangePickerHelpText": "Oraliqni tanlang", "calendarModeButtonLabel": "Taqvimda ochish", "inputDateModeButtonLabel": "Mustaqil kiritish", "timePickerDialHelpText": "Vaqtni tanlang", "timePickerInputHelpText": "Vaqtni kiriting", "timePickerHourLabel": "Soat", "timePickerMinuteLabel": "Daqiqa", "invalidTimeLabel": "Vaqt xato kiritildi", "dialModeButtonLabel": "Vaqtni burab tanlash rejimi", "inputTimeModeButtonLabel": "Vaqtni yozib tanlash rejimi", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 ta litsenziya", "licensesPackageDetailTextOther": "$licenseCount ta litsenziya", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Keyingi kanal", "keyboardKeyChannelUp": "Avvalgi kanal", "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": "Boʻsh joy", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menyu paneli", "currentDateLabel": "Bugun", "scrimLabel": "Kanop", "bottomSheetLabel": "Quyi ekran", "scrimOnTapHint": "Yopish: $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "yigʻish uchun ikki marta bosing", "expansionTileCollapsedHint": "yoyish uchun ikki marta bosing", "expansionTileExpandedTapHint": "Yigʻish", "expansionTileCollapsedTapHint": "Batafsil koʻrish uchun yoying", "expandedHint": "Yigʻilgan", "collapsedHint": "Yoyilgan", "menuDismissLabel": "Menyuni yopish", "lookUpButtonLabel": "Tepaga qarang", "searchWebButtonLabel": "Internetdan qidirish", "shareButtonLabel": "Ulashish…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_uz.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_uz.arb", "repo_id": "flutter", "token_count": 2345 }
721
{ "reorderItemToStart": "Přesunout na začátek", "reorderItemToEnd": "Přesunout na konec", "reorderItemUp": "Přesunout nahoru", "reorderItemDown": "Přesunout dolů", "reorderItemLeft": "Přesunout doleva", "reorderItemRight": "Přesunout doprava" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_cs.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_cs.arb", "repo_id": "flutter", "token_count": 125 }
722
{ "reorderItemToStart": "Premjesti na početak", "reorderItemToEnd": "Premjesti na kraj", "reorderItemUp": "Pomakni prema gore", "reorderItemDown": "Pomakni prema dolje", "reorderItemLeft": "Pomakni ulijevo", "reorderItemRight": "Pomakni udesno" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_hr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_hr.arb", "repo_id": "flutter", "token_count": 114 }
723
{ "reorderItemToStart": "Преместете на почеток", "reorderItemToEnd": "Преместете на крајот", "reorderItemUp": "Преместете нагоре", "reorderItemDown": "Преместете надолу", "reorderItemLeft": "Преместете налево", "reorderItemRight": "Преместете надесно" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_mk.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_mk.arb", "repo_id": "flutter", "token_count": 185 }
724
{ "reorderItemToStart": "Mutați la început", "reorderItemToEnd": "Mutați la sfârșit", "reorderItemUp": "Mutați în sus", "reorderItemDown": "Mutați în jos", "reorderItemLeft": "Mutați la stânga", "reorderItemRight": "Mutați la dreapta" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_ro.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ro.arb", "repo_id": "flutter", "token_count": 128 }
725
{ "reorderItemToStart": "شروع میں منتقل کریں", "reorderItemToEnd": "آخر میں منتقل کریں", "reorderItemUp": "اوپر منتقل کریں", "reorderItemDown": "نیچے منتقل کریں", "reorderItemLeft": "بائیں منتقل کریں", "reorderItemRight": "دائیں منتقل کریں" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_ur.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ur.arb", "repo_id": "flutter", "token_count": 196 }
726
// 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/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Test semantics of TabPageSelector in pt-BR', (WidgetTester tester) async { final TabController controller = TabController( vsync: const TestVSync(), length: 2, ); await tester.pumpWidget( Localizations( locale: const Locale('pt', 'BR'), delegates: const <LocalizationsDelegate<dynamic>>[ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: Material( child: Column( children: <Widget>[ TabBar( controller: controller, indicatorWeight: 30.0, tabs: const <Widget>[Tab(text: 'TAB1'), Tab(text: 'TAB2')], ), Flexible( child: TabBarView( controller: controller, children: const <Widget>[Text('PAGE1'), Text('PAGE2')], ), ), Expanded(child: TabPageSelector(controller: controller)), ], ), ), ), ), ); final SemanticsHandle handle = tester.ensureSemantics(); expect(tester.getSemantics(find.byType(TabPageSelector)), matchesSemantics(label: 'Guia 1 de 2')); handle.dispose(); }); }
flutter/packages/flutter_localizations/test/material/tabs_test.dart/0
{ "file_path": "flutter/packages/flutter_localizations/test/material/tabs_test.dart", "repo_id": "flutter", "token_count": 800 }
727
# 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. # For details regarding the *Flutter Fix* feature, see # https://flutter.dev/docs/development/tools/flutter-fix # Please add new fixes to the top of the file, separated by one blank line # from other fixes. In a comment, include a link to the PR where the change # requiring the fix was made. # Every fix must be tested. See the # flutter/packages/flutter_test/test_fixes/README.md file for instructions # on testing these data driven fixes. # For documentation about this file format, see # https://dart.dev/go/data-driven-fixes. # * Fixes in this file are for the flutter_test/widget_tester.dart file. * version: 1 transforms: # Changes made in https://github.com/flutter/flutter/pull/89952 - title: "Migrate to timeout" date: 2023-03-30 element: uris: [ 'flutter_test.dart' ] function: 'testWidgets' oneOf: - if: "initialTimeout != '' && timeout == ''" changes: - kind: 'addParameter' index: 3 name: 'timeout' style: optional_named argumentValue: expression: 'Timeout({% initialTimeout %})' requiredIf: "initialTimeout != '' && timeout == ''" - kind: 'removeParameter' name: 'initialTimeout' - if: "initialTimeout != '' && timeout != ''" changes: - kind: 'removeParameter' name: 'initialTimeout' variables: initialTimeout: kind: 'fragment' value: 'arguments[initialTimeout]' timeout: kind: 'fragment' value: 'arguments[timeout]'
flutter/packages/flutter_test/lib/fix_data/fix_flutter_test/fix_widget_tester.yaml/0
{ "file_path": "flutter/packages/flutter_test/lib/fix_data/fix_flutter_test/fix_widget_tester.yaml", "repo_id": "flutter", "token_count": 666 }
728
// 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'; /// The maximum amount of time considered safe to spend for a frame's build /// phase. Anything past that is in the danger of missing the frame as 60FPS. /// /// Changing this doesn't re-evaluate existing summary. Duration kBuildBudget = const Duration(milliseconds: 16); // TODO(CareF): Automatically calculate the refresh budget (#61958) /// This class and summarizes a list of [FrameTiming] for the performance /// metrics. class FrameTimingSummarizer { /// Summarize `data` to frame build time and frame rasterizer time statistics. /// /// See [TimelineSummary.summaryJson] for detail. factory FrameTimingSummarizer( List<FrameTiming> data, { int? newGenGCCount, int? oldGenGCCount, }) { assert(data.isNotEmpty); final List<Duration> frameBuildTime = List<Duration>.unmodifiable( data.map<Duration>((FrameTiming datum) => datum.buildDuration), ); final List<Duration> frameBuildTimeSorted = List<Duration>.from(frameBuildTime)..sort(); final List<Duration> frameRasterizerTime = List<Duration>.unmodifiable( data.map<Duration>((FrameTiming datum) => datum.rasterDuration), ); final List<Duration> frameRasterizerTimeSorted = List<Duration>.from(frameRasterizerTime)..sort(); final List<Duration> vsyncOverhead = List<Duration>.unmodifiable( data.map<Duration>((FrameTiming datum) => datum.vsyncOverhead), ); final List<int> layerCacheCounts = List<int>.unmodifiable( data.map<int>((FrameTiming datum) => datum.layerCacheCount), ); final List<int> layerCacheCountsSorted = List<int>.from(layerCacheCounts)..sort(); final List<int> layerCacheBytes = List<int>.unmodifiable( data.map<int>((FrameTiming datum) => datum.layerCacheBytes), ); final List<int> layerCacheBytesSorted = List<int>.from(layerCacheBytes)..sort(); final List<int> pictureCacheCounts = List<int>.unmodifiable( data.map<int>((FrameTiming datum) => datum.pictureCacheCount), ); final List<int> pictureCacheCountsSorted = List<int>.from(pictureCacheCounts)..sort(); final List<int> pictureCacheBytes = List<int>.unmodifiable( data.map<int>((FrameTiming datum) => datum.pictureCacheBytes), ); final List<int> pictureCacheBytesSorted = List<int>.from(pictureCacheBytes)..sort(); final List<Duration> vsyncOverheadSorted = List<Duration>.from(vsyncOverhead)..sort(); Duration add(Duration a, Duration b) => a + b; int addInts(int a, int b) => a + b; return FrameTimingSummarizer._( frameBuildTime: frameBuildTime, frameRasterizerTime: frameRasterizerTime, vsyncOverhead: vsyncOverhead, // This average calculation is microsecond precision, which is fine // because typical values of these times are milliseconds. averageFrameBuildTime: frameBuildTime.reduce(add) ~/ data.length, p90FrameBuildTime: _findPercentile(frameBuildTimeSorted, 0.90), p99FrameBuildTime: _findPercentile(frameBuildTimeSorted, 0.99), worstFrameBuildTime: frameBuildTimeSorted.last, missedFrameBuildBudget: _countExceed(frameBuildTimeSorted, kBuildBudget), averageFrameRasterizerTime: frameRasterizerTime.reduce(add) ~/ data.length, p90FrameRasterizerTime: _findPercentile(frameRasterizerTimeSorted, 0.90), p99FrameRasterizerTime: _findPercentile(frameRasterizerTimeSorted, 0.99), worstFrameRasterizerTime: frameRasterizerTimeSorted.last, averageLayerCacheCount: layerCacheCounts.reduce(addInts) / data.length, p90LayerCacheCount: _findPercentile(layerCacheCountsSorted, 0.90), p99LayerCacheCount: _findPercentile(layerCacheCountsSorted, 0.99), worstLayerCacheCount: layerCacheCountsSorted.last, averageLayerCacheBytes: layerCacheBytes.reduce(addInts) / data.length, p90LayerCacheBytes: _findPercentile(layerCacheBytesSorted, 0.90), p99LayerCacheBytes: _findPercentile(layerCacheBytesSorted, 0.99), worstLayerCacheBytes: layerCacheBytesSorted.last, averagePictureCacheCount: pictureCacheCounts.reduce(addInts) / data.length, p90PictureCacheCount: _findPercentile(pictureCacheCountsSorted, 0.90), p99PictureCacheCount: _findPercentile(pictureCacheCountsSorted, 0.99), worstPictureCacheCount: pictureCacheCountsSorted.last, averagePictureCacheBytes: pictureCacheBytes.reduce(addInts) / data.length, p90PictureCacheBytes: _findPercentile(pictureCacheBytesSorted, 0.90), p99PictureCacheBytes: _findPercentile(pictureCacheBytesSorted, 0.99), worstPictureCacheBytes: pictureCacheBytesSorted.last, missedFrameRasterizerBudget: _countExceed(frameRasterizerTimeSorted, kBuildBudget), averageVsyncOverhead: vsyncOverhead.reduce(add) ~/ data.length, p90VsyncOverhead: _findPercentile(vsyncOverheadSorted, 0.90), p99VsyncOverhead: _findPercentile(vsyncOverheadSorted, 0.99), worstVsyncOverhead: vsyncOverheadSorted.last, newGenGCCount: newGenGCCount ?? -1, oldGenGCCount: oldGenGCCount ?? -1, ); } const FrameTimingSummarizer._({ required this.frameBuildTime, required this.frameRasterizerTime, required this.averageFrameBuildTime, required this.p90FrameBuildTime, required this.p99FrameBuildTime, required this.worstFrameBuildTime, required this.missedFrameBuildBudget, required this.averageFrameRasterizerTime, required this.p90FrameRasterizerTime, required this.p99FrameRasterizerTime, required this.worstFrameRasterizerTime, required this.averageLayerCacheCount, required this.p90LayerCacheCount, required this.p99LayerCacheCount, required this.worstLayerCacheCount, required this.averageLayerCacheBytes, required this.p90LayerCacheBytes, required this.p99LayerCacheBytes, required this.worstLayerCacheBytes, required this.averagePictureCacheCount, required this.p90PictureCacheCount, required this.p99PictureCacheCount, required this.worstPictureCacheCount, required this.averagePictureCacheBytes, required this.p90PictureCacheBytes, required this.p99PictureCacheBytes, required this.worstPictureCacheBytes, required this.missedFrameRasterizerBudget, required this.vsyncOverhead, required this.averageVsyncOverhead, required this.p90VsyncOverhead, required this.p99VsyncOverhead, required this.worstVsyncOverhead, required this.newGenGCCount, required this.oldGenGCCount, }); /// List of frame build time in microseconds final List<Duration> frameBuildTime; /// List of frame rasterizer time in microseconds final List<Duration> frameRasterizerTime; /// List of the time difference between vsync signal and frame building start /// time final List<Duration> vsyncOverhead; /// The average value of [frameBuildTime] in milliseconds. final Duration averageFrameBuildTime; /// The 90-th percentile value of [frameBuildTime] in milliseconds final Duration p90FrameBuildTime; /// The 99-th percentile value of [frameBuildTime] in milliseconds final Duration p99FrameBuildTime; /// The largest value of [frameBuildTime] in milliseconds final Duration worstFrameBuildTime; /// Number of items in [frameBuildTime] that's greater than [kBuildBudget] final int missedFrameBuildBudget; /// The average value of [frameRasterizerTime] in milliseconds. final Duration averageFrameRasterizerTime; /// The 90-th percentile value of [frameRasterizerTime] in milliseconds. final Duration p90FrameRasterizerTime; /// The 99-th percentile value of [frameRasterizerTime] in milliseconds. final Duration p99FrameRasterizerTime; /// The largest value of [frameRasterizerTime] in milliseconds. final Duration worstFrameRasterizerTime; /// The average number of layers cached across all frames. final double averageLayerCacheCount; /// The 90-th percentile number of layers cached across all frames. final int p90LayerCacheCount; /// The 90-th percentile number of layers cached across all frames. final int p99LayerCacheCount; /// The most number of layers cached across all frames. final int worstLayerCacheCount; /// The average number of bytes consumed by cached layers across all frames. final double averageLayerCacheBytes; /// The 90-th percentile number of bytes consumed by cached layers across all frames. final int p90LayerCacheBytes; /// The 90-th percentile number of bytes consumed by cached layers across all frames. final int p99LayerCacheBytes; /// The highest number of bytes consumed by cached layers across all frames. final int worstLayerCacheBytes; /// The average number of pictures cached across all frames. final double averagePictureCacheCount; /// The 90-th percentile number of pictures cached across all frames. final int p90PictureCacheCount; /// The 90-th percentile number of pictures cached across all frames. final int p99PictureCacheCount; /// The most number of pictures cached across all frames. final int worstPictureCacheCount; /// The average number of bytes consumed by cached pictures across all frames. final double averagePictureCacheBytes; /// The 90-th percentile number of bytes consumed by cached pictures across all frames. final int p90PictureCacheBytes; /// The 90-th percentile number of bytes consumed by cached pictures across all frames. final int p99PictureCacheBytes; /// The highest number of bytes consumed by cached pictures across all frames. final int worstPictureCacheBytes; /// Number of items in [frameRasterizerTime] that's greater than [kBuildBudget] final int missedFrameRasterizerBudget; /// The average value of [vsyncOverhead]; final Duration averageVsyncOverhead; /// The 90-th percentile value of [vsyncOverhead] in milliseconds final Duration p90VsyncOverhead; /// The 99-th percentile value of [vsyncOverhead] in milliseconds final Duration p99VsyncOverhead; /// The largest value of [vsyncOverhead] in milliseconds. final Duration worstVsyncOverhead; /// The number of new generation GCs. final int newGenGCCount; /// The number of old generation GCs. final int oldGenGCCount; /// Convert the summary result to a json object. /// /// See [TimelineSummary.summaryJson] for detail. Map<String, dynamic> get summary => <String, dynamic>{ 'average_frame_build_time_millis': averageFrameBuildTime.inMicroseconds / 1E3, '90th_percentile_frame_build_time_millis': p90FrameBuildTime.inMicroseconds / 1E3, '99th_percentile_frame_build_time_millis': p99FrameBuildTime.inMicroseconds / 1E3, 'worst_frame_build_time_millis': worstFrameBuildTime.inMicroseconds / 1E3, 'missed_frame_build_budget_count': missedFrameBuildBudget, 'average_frame_rasterizer_time_millis': averageFrameRasterizerTime.inMicroseconds / 1E3, '90th_percentile_frame_rasterizer_time_millis': p90FrameRasterizerTime.inMicroseconds / 1E3, '99th_percentile_frame_rasterizer_time_millis': p99FrameRasterizerTime.inMicroseconds / 1E3, 'worst_frame_rasterizer_time_millis': worstFrameRasterizerTime.inMicroseconds / 1E3, 'average_layer_cache_count': averageLayerCacheCount, '90th_percentile_layer_cache_count': p90LayerCacheCount, '99th_percentile_layer_cache_count': p99LayerCacheCount, 'worst_layer_cache_count': worstLayerCacheCount, 'average_layer_cache_memory': averageLayerCacheBytes / 1024.0 / 1024.0, '90th_percentile_layer_cache_memory': p90LayerCacheBytes / 1024.0 / 1024.0, '99th_percentile_layer_cache_memory': p99LayerCacheBytes / 1024.0 / 1024.0, 'worst_layer_cache_memory': worstLayerCacheBytes / 1024.0 / 1024.0, 'average_picture_cache_count': averagePictureCacheCount, '90th_percentile_picture_cache_count': p90PictureCacheCount, '99th_percentile_picture_cache_count': p99PictureCacheCount, 'worst_picture_cache_count': worstPictureCacheCount, 'average_picture_cache_memory': averagePictureCacheBytes / 1024.0 / 1024.0, '90th_percentile_picture_cache_memory': p90PictureCacheBytes / 1024.0 / 1024.0, '99th_percentile_picture_cache_memory': p99PictureCacheBytes / 1024.0 / 1024.0, 'worst_picture_cache_memory': worstPictureCacheBytes / 1024.0 / 1024.0, 'missed_frame_rasterizer_budget_count': missedFrameRasterizerBudget, 'frame_count': frameBuildTime.length, 'frame_build_times': frameBuildTime .map<int>((Duration datum) => datum.inMicroseconds) .toList(), 'frame_rasterizer_times': frameRasterizerTime .map<int>((Duration datum) => datum.inMicroseconds) .toList(), 'new_gen_gc_count': newGenGCCount, 'old_gen_gc_count': oldGenGCCount, }; } /// Returns the 100*p-th percentile of [data]. /// /// [data] must be sorted in ascending order. T _findPercentile<T>(List<T> data, double p) { assert(p >= 0 && p <= 1); return data[((data.length - 1) * p).round()]; } /// Returns the number of elements in [data] that exceed [threshold]. /// /// [data] must be sorted in ascending order. int _countExceed<T extends Comparable<T>>(List<T> data, T threshold) { final int exceedsThresholdIndex = data.indexWhere((T datum) => datum.compareTo(threshold) > 0); if (exceedsThresholdIndex == -1) { return 0; } return data.length - exceedsThresholdIndex; }
flutter/packages/flutter_test/lib/src/frame_timing_summarizer.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/frame_timing_summarizer.dart", "repo_id": "flutter", "token_count": 4629 }
729
// 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:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'binding.dart'; import 'test_async_utils.dart'; import 'test_text_input_key_handler.dart'; export 'package:flutter/services.dart' show TextEditingValue, TextInputAction; /// A testing stub for the system's onscreen keyboard. /// /// Typical app tests will not need to use this class directly. /// /// The [TestWidgetsFlutterBinding] class registers a [TestTextInput] instance /// ([TestWidgetsFlutterBinding.testTextInput]) as a stub keyboard /// implementation if its [TestWidgetsFlutterBinding.registerTestTextInput] /// property returns true when a test starts, and unregisters it when the test /// ends (unless it ends with a failure). /// /// See [register], [unregister], and [isRegistered] for details. /// /// The [enterText], [updateEditingValue], [receiveAction], and /// [closeConnection] methods can be used even when the [TestTextInput] is not /// registered. All other methods will assert if [isRegistered] is false. /// /// See also: /// /// * [WidgetTester.enterText], which uses this class to simulate keyboard input. /// * [WidgetTester.showKeyboard], which uses this class to simulate showing the /// popup keyboard and initializing its text. class TestTextInput { /// Create a fake keyboard backend. /// /// The [onCleared] argument may be set to be notified of when the keyboard /// is dismissed. TestTextInput({ this.onCleared }); /// Called when the keyboard goes away. /// /// To use the methods on this API that send fake keyboard messages (such as /// [updateEditingValue], [enterText], or [receiveAction]), the keyboard must /// first be requested, e.g. using [WidgetTester.showKeyboard]. final VoidCallback? onCleared; /// Log for method calls. /// /// For all registered channels, handled calls are added to the list. Can /// be cleaned using `log.clear()`. final List<MethodCall> log = <MethodCall>[]; /// Installs this object as a mock handler for [SystemChannels.textInput]. /// /// Called by the binding at the top of a test when /// [TestWidgetsFlutterBinding.registerTestTextInput] is true. void register() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, _handleTextInputCall); /// Removes this object as a mock handler for [SystemChannels.textInput]. /// /// After calling this method, the channel will exchange messages with the /// Flutter engine instead of the stub. /// /// Called by the binding at the end of a (successful) test when /// [TestWidgetsFlutterBinding.registerTestTextInput] is true. void unregister() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.textInput, null); /// Whether this [TestTextInput] is registered with [SystemChannels.textInput]. /// /// The binding uses the [register] and [unregister] methods to control this /// value when [TestWidgetsFlutterBinding.registerTestTextInput] is true. bool get isRegistered => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.checkMockMessageHandler(SystemChannels.textInput.name, _handleTextInputCall); int? _client; /// Whether there are any active clients listening to text input. bool get hasAnyClients { assert(isRegistered); return _client != null && _client! > 0; } /// The last set of arguments supplied to the `TextInput.setClient` and /// `TextInput.updateConfig` methods of this stub implementation. Map<String, dynamic>? setClientArgs; /// The last set of arguments that [TextInputConnection.setEditingState] sent /// to this stub implementation (i.e. the arguments set to /// `TextInput.setEditingState`). /// /// This is a map representation of a [TextEditingValue] object. For example, /// it will have a `text` entry whose value matches the most recent /// [TextEditingValue.text] that was sent to the embedder. Map<String, dynamic>? editingState; /// Whether the onscreen keyboard is visible to the user. /// /// Specifically, this reflects the last call to `TextInput.show` or /// `TextInput.hide` received by the stub implementation. bool get isVisible { assert(isRegistered); return _isVisible; } bool _isVisible = false; // Platform specific key handler that can process unhandled keyboard events. TestTextInputKeyHandler? _keyHandler; /// Resets any internal state of this object. /// /// This method is invoked by the testing framework between tests. It should /// not ordinarily be called by tests directly. void reset() { log.clear(); _client = null; setClientArgs = null; editingState = null; _isVisible = false; } Future<dynamic> _handleTextInputCall(MethodCall methodCall) async { log.add(methodCall); switch (methodCall.method) { case 'TextInput.setClient': final List<dynamic> arguments = methodCall.arguments as List<dynamic>; _client = arguments[0] as int; setClientArgs = arguments[1] as Map<String, dynamic>; case 'TextInput.updateConfig': setClientArgs = methodCall.arguments as Map<String, dynamic>; case 'TextInput.clearClient': _client = null; _isVisible = false; _keyHandler = null; onCleared?.call(); case 'TextInput.setEditingState': editingState = methodCall.arguments as Map<String, dynamic>; case 'TextInput.show': _isVisible = true; if (!kIsWeb && defaultTargetPlatform == TargetPlatform.macOS) { _keyHandler ??= MacOSTestTextInputKeyHandler(_client ?? -1); } case 'TextInput.hide': _isVisible = false; _keyHandler = null; } } /// Simulates the user hiding the onscreen keyboard. /// /// This does nothing but set the internal flag. void hide() { assert(isRegistered); _isVisible = false; } /// Simulates the user changing the text of the focused text field, and resets /// the selection. /// /// Calling this method replaces the content of the connected input field with /// `text`, and places the caret at the end of the text. /// /// To update the UI under test after this method is invoked, use /// [WidgetTester.pump]. /// /// This can be called even if the [TestTextInput] has not been [register]ed. /// /// If this is used to inject text when there is a real IME connection, for /// example when using the [integration_test] library, there is a risk that /// the real IME will become confused as to the current state of input. /// /// See also: /// /// * [updateEditingValue], which takes a [TextEditingValue] so that one can /// also change the selection. void enterText(String text) { updateEditingValue(TextEditingValue( text: text, selection: TextSelection.collapsed(offset: text.length), )); } /// Simulates the user changing the [TextEditingValue] to the given value. /// /// To update the UI under test after this method is invoked, use /// [WidgetTester.pump]. /// /// This can be called even if the [TestTextInput] has not been [register]ed. /// /// If this is used to inject text when there is a real IME connection, for /// example when using the [integration_test] library, there is a risk that /// the real IME will become confused as to the current state of input. /// /// See also: /// /// * [enterText], which is similar but takes only a String and resets the /// selection. void updateEditingValue(TextEditingValue value) { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.updateEditingState', <dynamic>[_client ?? -1, value.toJSON()], ), ), (ByteData? data) { /* ignored */ }, ); } /// Simulates the user pressing one of the [TextInputAction] buttons. /// Does not check that the [TextInputAction] performed is an acceptable one /// based on the `inputAction` [setClientArgs]. /// /// This can be called even if the [TestTextInput] has not been [register]ed. /// /// If this is used to inject an action when there is a real IME connection, /// for example when using the [integration_test] library, there is a risk /// that the real IME will become confused as to the current state of input. Future<void> receiveAction(TextInputAction action) async { return TestAsyncUtils.guard(() { final Completer<void> completer = Completer<void>(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.performAction', <dynamic>[_client ?? -1, action.toString()], ), ), (ByteData? data) { assert(data != null); try { // Decoding throws a PlatformException if the data represents an // error, and that's all we care about here. SystemChannels.textInput.codec.decodeEnvelope(data!); // If we reach here then no error was found. Complete without issue. completer.complete(); } catch (error) { // An exception occurred as a result of receiveAction()'ing. Report // that error. completer.completeError(error); } }, ); return completer.future; }); } /// Simulates the user closing the text input connection. /// /// For example: /// /// * User pressed the home button and sent the application to background. /// * User closed the virtual keyboard. /// /// This can be called even if the [TestTextInput] has not been [register]ed. /// /// If this is used to inject text when there is a real IME connection, for /// example when using the [integration_test] library, there is a risk that /// the real IME will become confused as to the current state of input. void closeConnection() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.onConnectionClosed', <dynamic>[_client ?? -1], ), ), (ByteData? data) { /* response from framework is discarded */ }, ); } /// Simulates a scribble interaction starting. Future<void> startScribbleInteraction() async { assert(isRegistered); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.scribbleInteractionBegan', <dynamic>[_client ?? -1,] ), ), (ByteData? data) { /* response from framework is discarded */ }, ); } /// Simulates a scribble interaction finishing. Future<void> finishScribbleInteraction() async { assert(isRegistered); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.scribbleInteractionFinished', <dynamic>[_client ?? -1,] ), ), (ByteData? data) { /* response from framework is discarded */ }, ); } /// Simulates a Scribble focus. Future<void> scribbleFocusElement(String elementIdentifier, Offset offset) async { assert(isRegistered); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.focusElement', <dynamic>[elementIdentifier, offset.dx, offset.dy] ), ), (ByteData? data) { /* response from framework is discarded */ }, ); } /// Simulates iOS asking for the list of Scribble elements during UIIndirectScribbleInteraction. Future<List<List<dynamic>>> scribbleRequestElementsInRect(Rect rect) async { assert(isRegistered); List<List<dynamic>> response = <List<dynamic>>[]; await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.requestElementsInRect', <dynamic>[rect.left, rect.top, rect.width, rect.height] ), ), (ByteData? data) { response = (SystemChannels.textInput.codec.decodeEnvelope(data!) as List<dynamic>).map((dynamic element) => element as List<dynamic>).toList(); }, ); return response; } /// Simulates iOS inserting a UITextPlaceholder during a long press with the pencil. Future<void> scribbleInsertPlaceholder() async { assert(isRegistered); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.insertTextPlaceholder', <dynamic>[_client ?? -1, 0.0, 0.0] ), ), (ByteData? data) { /* response from framework is discarded */ }, ); } /// Simulates iOS removing a UITextPlaceholder after a long press with the pencil is released. Future<void> scribbleRemovePlaceholder() async { assert(isRegistered); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall( 'TextInputClient.removeTextPlaceholder', <dynamic>[_client ?? -1] ), ), (ByteData? data) { /* response from framework is discarded */ }, ); } /// Gives text input chance to respond to unhandled key down event. Future<void> handleKeyDownEvent(LogicalKeyboardKey key) async { await _keyHandler?.handleKeyDownEvent(key); } /// Gives text input chance to respond to unhandled key up event. Future<void> handleKeyUpEvent(LogicalKeyboardKey key) async { await _keyHandler?.handleKeyUpEvent(key); } /// Simulates iOS responding to an undo or redo gesture or button. Future<void> handleKeyboardUndo(String direction) async { assert(isRegistered); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( SystemChannels.textInput.name, SystemChannels.textInput.codec.encodeMethodCall( MethodCall('TextInputClient.handleUndo', <dynamic>[direction]), ), (ByteData? data) {/* response from framework is discarded */}, ); } }
flutter/packages/flutter_test/lib/src/test_text_input.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/test_text_input.dart", "repo_id": "flutter", "token_count": 5038 }
730
// 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/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_test/flutter_test.dart'; // This test is very fragile and bypasses some zone-related checks. // It is written this way to verify some invariants that would otherwise // be difficult to check. // Do not use this test as a guide for writing good Flutter code. class TestBinding extends WidgetsFlutterBinding { @override void initInstances() { super.initInstances(); _instance = this; } @override bool debugCheckZone(String entryPoint) { return true; } static TestBinding get instance => BindingBase.checkInstance(_instance); static TestBinding? _instance; static TestBinding ensureInitialized() { if (TestBinding._instance == null) { TestBinding(); } return TestBinding.instance; } } class CountButton extends StatefulWidget { const CountButton({super.key}); @override State<CountButton> createState() => _CountButtonState(); } class _CountButtonState extends State<CountButton> { int counter = 0; @override Widget build(BuildContext context) { return ElevatedButton( child: Text('Counter $counter'), onPressed: () { setState(() { counter += 1; }); }, ); } } class AnimateSample extends StatefulWidget { const AnimateSample({super.key}); @override State<AnimateSample> createState() => _AnimateSampleState(); } class _AnimateSampleState extends State<AnimateSample> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(seconds: 1), )..forward(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller, builder: (BuildContext context, _) => Text('Value: ${_controller.value}'), ); } } void main() { TestBinding.ensureInitialized(); test('Test pump on LiveWidgetController', () async { runApp(const MaterialApp(home: Center(child: CountButton()))); await SchedulerBinding.instance.endOfFrame; final WidgetController controller = LiveWidgetController(WidgetsBinding.instance); await controller.tap(find.text('Counter 0')); expect(find.text('Counter 0'), findsOneWidget); expect(find.text('Counter 1'), findsNothing); await controller.pump(); expect(find.text('Counter 0'), findsNothing); expect(find.text('Counter 1'), findsOneWidget); }); test('Test pumpAndSettle on LiveWidgetController', () async { runApp(const MaterialApp(home: Center(child: AnimateSample()))); await SchedulerBinding.instance.endOfFrame; final WidgetController controller = LiveWidgetController(WidgetsBinding.instance); expect(find.text('Value: 1.0'), findsNothing); await controller.pumpAndSettle(); expect(find.text('Value: 1.0'), findsOneWidget); }); test('Input event array on LiveWidgetController', () async { final List<String> logs = <String>[]; runApp( MaterialApp( home: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); await SchedulerBinding.instance.endOfFrame; final WidgetController controller = LiveWidgetController(WidgetsBinding.instance); final Offset location = controller.getCenter(find.text('test')); final List<PointerEventRecord> records = <PointerEventRecord>[ PointerEventRecord(Duration.zero, <PointerEvent>[ // Typically PointerAddedEvent is not used in testers, but for records // captured on a device it is usually what starts a gesture. PointerAddedEvent( position: location, ), PointerDownEvent( position: location, buttons: kSecondaryMouseButton, pointer: 1, ), ]), ...<PointerEventRecord>[ for (Duration t = const Duration(milliseconds: 5); t < const Duration(milliseconds: 80); t += const Duration(milliseconds: 16)) PointerEventRecord(t, <PointerEvent>[ PointerMoveEvent( timeStamp: t - const Duration(milliseconds: 1), position: location, buttons: kSecondaryMouseButton, pointer: 1, ), ]), ], PointerEventRecord(const Duration(milliseconds: 80), <PointerEvent>[ PointerUpEvent( timeStamp: const Duration(milliseconds: 79), position: location, buttons: kSecondaryMouseButton, pointer: 1, ), ]), ]; final List<Duration> timeDiffs = await controller.handlePointerEventRecord(records); expect(timeDiffs.length, records.length); for (final Duration diff in timeDiffs) { // Allow some freedom of time delay in real world. // TODO(pdblasi-google): The expected wiggle room should be -1, but occasional // results were reaching -6. This assert has been adjusted to reduce flakiness, // but the root cause is still unknown. (https://github.com/flutter/flutter/issues/109638) assert(diff.inMilliseconds > -7, 'timeDiffs were: $timeDiffs (offending time was ${diff.inMilliseconds}ms)'); } const String b = '$kSecondaryMouseButton'; expect(logs.first, 'down $b'); for (int i = 1; i < logs.length - 1; i++) { expect(logs[i], 'move $b'); } expect(logs.last, 'up $b'); }); }
flutter/packages/flutter_test/test/live_widget_controller_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/live_widget_controller_test.dart", "repo_id": "flutter", "token_count": 2232 }
731
// 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'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:matcher/expect.dart' as matcher; import 'package:matcher/src/expect/async_matcher.dart'; // ignore: implementation_imports import 'multi_view_testing.dart'; void main() { group('expectLater', () { testWidgets('completes when matcher completes', (WidgetTester tester) async { final Completer<void> completer = Completer<void>(); final Future<void> future = expectLater(null, FakeMatcher(completer)); String? result; future.then<void>((void value) { result = '123'; }); matcher.expect(result, isNull); completer.complete(); matcher.expect(result, isNull); await future; await tester.pump(); matcher.expect(result, '123'); }); testWidgets('respects the skip flag', (WidgetTester tester) async { final Completer<void> completer = Completer<void>(); final Future<void> future = expectLater(null, FakeMatcher(completer), skip: 'testing skip'); // [intended] API testing bool completed = false; future.then<void>((_) { completed = true; }); matcher.expect(completed, isFalse); await future; matcher.expect(completed, isTrue); }); }); group('group retry flag allows test to run multiple times', () { bool retried = false; group('the group with retry flag', () { testWidgets('the test inside it', (WidgetTester tester) async { addTearDown(() => retried = true); expect(retried, isTrue); }); }, retry: 1); }); group('testWidget retry flag allows test to run multiple times', () { bool retried = false; testWidgets('the test with retry flag', (WidgetTester tester) async { addTearDown(() => retried = true); expect(retried, isTrue); }, retry: 1); }); group('respects the group skip flag', () { testWidgets('should be skipped', (WidgetTester tester) async { expect(false, true); }); }, skip: true); // [intended] API testing group('pumping', () { testWidgets('pumping', (WidgetTester tester) async { await tester.pumpWidget(const Text('foo', textDirection: TextDirection.ltr)); int count; final AnimationController test = AnimationController( duration: const Duration(milliseconds: 5100), vsync: tester, ); count = await tester.pumpAndSettle(const Duration(seconds: 1)); expect(count, 1); // it always pumps at least one frame test.forward(from: 0.0); count = await tester.pumpAndSettle(const Duration(seconds: 1)); // 1 frame at t=0, starting the animation // 1 frame at t=1 // 1 frame at t=2 // 1 frame at t=3 // 1 frame at t=4 // 1 frame at t=5 // 1 frame at t=6, ending the animation expect(count, 7); test.forward(from: 0.0); await tester.pump(); // starts the animation count = await tester.pumpAndSettle(const Duration(seconds: 1)); expect(count, 6); test.forward(from: 0.0); await tester.pump(); // starts the animation await tester.pump(); // has no effect count = await tester.pumpAndSettle(const Duration(seconds: 1)); expect(count, 6); }); testWidgets('pumpFrames', (WidgetTester tester) async { final List<int> logPaints = <int>[]; int? initial; final Widget target = _AlwaysAnimating( onPaint: () { final int current = SchedulerBinding.instance.currentFrameTimeStamp.inMicroseconds; initial ??= current; logPaints.add(current - initial!); }, ); await tester.pumpFrames(target, const Duration(milliseconds: 55)); // `pumpframes` defaults to 16 milliseconds and 683 microseconds per pump, // so we expect 4 pumps of 16683 microseconds each in the 55ms duration. expect(logPaints, <int>[0, 16683, 33366, 50049]); logPaints.clear(); await tester.pumpFrames(target, const Duration(milliseconds: 30), const Duration(milliseconds: 10)); // Since `pumpFrames` was given a 10ms interval per pump, we expect the // results to continue from 50049 with 10000 microseconds per pump over // the 30ms duration. expect(logPaints, <int>[60049, 70049, 80049]); }); }); group('pageBack', () { testWidgets('fails when there are no back buttons', (WidgetTester tester) async { await tester.pumpWidget(Container()); expect( expectAsync0(tester.pageBack), throwsA(isA<TestFailure>()), ); }); testWidgets('successfully taps material back buttons', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Center( child: Builder( builder: (BuildContext context) { return ElevatedButton( child: const Text('Next'), onPressed: () { Navigator.push<void>(context, MaterialPageRoute<void>( builder: (BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Page 2'), ), ); }, )); }, ); } , ), ), ), ); await tester.tap(find.text('Next')); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); await tester.pageBack(); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); expect(find.text('Next'), findsOneWidget); expect(find.text('Page 2'), findsNothing); }); testWidgets('successfully taps cupertino back buttons', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Center( child: Builder( builder: (BuildContext context) { return CupertinoButton( child: const Text('Next'), onPressed: () { Navigator.push<void>(context, CupertinoPageRoute<void>( builder: (BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('Page 2'), ), child: Container(), ); }, )); }, ); } , ), ), ), ); await tester.tap(find.text('Next')); await tester.pump(); await tester.pump(const Duration(milliseconds: 400)); await tester.pageBack(); await tester.pump(); await tester.pumpAndSettle(); expect(find.text('Next'), findsOneWidget); expect(find.text('Page 2'), findsNothing); }); }); testWidgets('hasRunningAnimations control test', (WidgetTester tester) async { final AnimationController controller = AnimationController( duration: const Duration(seconds: 1), vsync: const TestVSync(), ); expect(tester.hasRunningAnimations, isFalse); controller.forward(); expect(tester.hasRunningAnimations, isTrue); controller.stop(); expect(tester.hasRunningAnimations, isFalse); controller.forward(); expect(tester.hasRunningAnimations, isTrue); await tester.pumpAndSettle(); expect(tester.hasRunningAnimations, isFalse); }); testWidgets('pumpAndSettle control test', (WidgetTester tester) async { final AnimationController controller = AnimationController( duration: const Duration(minutes: 525600), vsync: const TestVSync(), ); expect(await tester.pumpAndSettle(), 1); controller.forward(); try { await tester.pumpAndSettle(); expect(true, isFalse); } catch (e) { expect(e, isFlutterError); } controller.stop(); expect(await tester.pumpAndSettle(), 1); controller.duration = const Duration(seconds: 1); controller.forward(); expect(await tester.pumpAndSettle(const Duration(milliseconds: 300)), 5); // 0, 300, 600, 900, 1200ms }); testWidgets('Input event array', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); final Offset location = tester.getCenter(find.text('test')); final List<PointerEventRecord> records = <PointerEventRecord>[ PointerEventRecord(Duration.zero, <PointerEvent>[ // Typically PointerAddedEvent is not used in testers, but for records // captured on a device it is usually what start a gesture. PointerAddedEvent( position: location, ), PointerDownEvent( position: location, buttons: kSecondaryMouseButton, pointer: 1, ), ]), ...<PointerEventRecord>[ for (Duration t = const Duration(milliseconds: 5); t < const Duration(milliseconds: 80); t += const Duration(milliseconds: 16)) PointerEventRecord(t, <PointerEvent>[ PointerMoveEvent( timeStamp: t - const Duration(milliseconds: 1), position: location, buttons: kSecondaryMouseButton, pointer: 1, ), ]), ], PointerEventRecord(const Duration(milliseconds: 80), <PointerEvent>[ PointerUpEvent( timeStamp: const Duration(milliseconds: 79), position: location, buttons: kSecondaryMouseButton, pointer: 1, ), ]), ]; final List<Duration> timeDiffs = await tester.handlePointerEventRecord(records); expect(timeDiffs.length, records.length); for (final Duration diff in timeDiffs) { expect(diff, Duration.zero); } const String b = '$kSecondaryMouseButton'; expect(logs.first, 'down $b'); for (int i = 1; i < logs.length - 1; i++) { expect(logs[i], 'move $b'); } expect(logs.last, 'up $b'); }); group('runAsync', () { testWidgets('works with no async calls', (WidgetTester tester) async { String? value; await tester.runAsync(() async { value = '123'; }); expect(value, '123'); }); testWidgets('works with real async calls', (WidgetTester tester) async { final StringBuffer buf = StringBuffer('1'); await tester.runAsync(() async { buf.write('2'); //ignore: avoid_slow_async_io await Directory.current.stat(); buf.write('3'); }); buf.write('4'); expect(buf.toString(), '1234'); }); testWidgets('propagates return values', (WidgetTester tester) async { final String? value = await tester.runAsync<String>(() async { return '123'; }); expect(value, '123'); }); testWidgets('reports errors via framework', (WidgetTester tester) async { final String? value = await tester.runAsync<String>(() async { throw ArgumentError(); }); expect(value, isNull); expect(tester.takeException(), isArgumentError); }); testWidgets('disallows re-entry', (WidgetTester tester) async { final Completer<void> completer = Completer<void>(); tester.runAsync<void>(() => completer.future); expect(() => tester.runAsync(() async { }), throwsA(isA<TestFailure>())); completer.complete(); }); testWidgets('maintains existing zone values', (WidgetTester tester) async { final Object key = Object(); await runZoned<Future<void>>(() { expect(Zone.current[key], 'abczed'); return tester.runAsync<void>(() async { expect(Zone.current[key], 'abczed'); }); }, zoneValues: <dynamic, dynamic>{ key: 'abczed', }); }); testWidgets('control test (return value)', (WidgetTester tester) async { final String? result = await tester.binding.runAsync<String>(() async => 'Judy Turner'); expect(result, 'Judy Turner'); }); testWidgets('async throw', (WidgetTester tester) async { final String? result = await tester.binding.runAsync<Never>(() async => throw Exception('Lois Dilettente')); expect(result, isNull); expect(tester.takeException(), isNotNull); }); testWidgets('sync throw', (WidgetTester tester) async { final String? result = await tester.binding.runAsync<Never>(() => throw Exception('Butch Barton')); expect(result, isNull); expect(tester.takeException(), isNotNull); }); }); group('showKeyboard', () { testWidgets('can be called twice', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: TextFormField(), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); await tester.showKeyboard(find.byType(TextField)); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); await tester.showKeyboard(find.byType(TextField)); await tester.showKeyboard(find.byType(TextField)); await tester.pump(); }); testWidgets( 'can focus on offstage text input field if finder says not to skip offstage nodes', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Offstage( child: TextFormField(), ), ), ), ); await tester.showKeyboard(find.byType(TextField, skipOffstage: false)); }); }); testWidgets('verifyTickersWereDisposed control test', (WidgetTester tester) async { late FlutterError error; final Ticker ticker = tester.createTicker((Duration duration) {}); ticker.start(); try { tester.verifyTickersWereDisposed(''); } on FlutterError catch (e) { error = e; } finally { expect(error, isNotNull); expect(error.diagnostics.length, 4); expect(error.diagnostics[2].level, DiagnosticLevel.hint); expect( error.diagnostics[2].toStringDeep(), 'Tickers used by AnimationControllers should be disposed by\n' 'calling dispose() on the AnimationController itself. Otherwise,\n' 'the ticker will leak.\n', ); expect(error.diagnostics.last, isA<DiagnosticsProperty<Ticker>>()); expect(error.diagnostics.last.value, ticker); expect(error.toStringDeep(), startsWith( 'FlutterError\n' ' A Ticker was active .\n' ' All Tickers must be disposed.\n' ' Tickers used by AnimationControllers should be disposed by\n' ' calling dispose() on the AnimationController itself. Otherwise,\n' ' the ticker will leak.\n' ' The offending ticker was:\n' ' _TestTicker()\n', )); } ticker.stop(); }); group('testWidgets variants work', () { int numberOfVariationsRun = 0; testWidgets('variant tests run all values provided', (WidgetTester tester) async { if (debugDefaultTargetPlatformOverride == null) { expect(numberOfVariationsRun, equals(TargetPlatform.values.length)); } else { numberOfVariationsRun += 1; } }, variant: TargetPlatformVariant(TargetPlatform.values.toSet())); testWidgets('variant tests have descriptions with details', (WidgetTester tester) async { if (debugDefaultTargetPlatformOverride == null) { expect(tester.testDescription, equals('variant tests have descriptions with details')); } else { expect( tester.testDescription, equals('variant tests have descriptions with details (variant: $debugDefaultTargetPlatformOverride)'), ); } }, variant: TargetPlatformVariant(TargetPlatform.values.toSet())); }); group('TargetPlatformVariant', () { int numberOfVariationsRun = 0; TargetPlatform? origTargetPlatform; setUpAll(() { origTargetPlatform = debugDefaultTargetPlatformOverride; }); tearDownAll(() { expect(debugDefaultTargetPlatformOverride, equals(origTargetPlatform)); }); testWidgets('TargetPlatformVariant.only tests given value', (WidgetTester tester) async { expect(debugDefaultTargetPlatformOverride, equals(TargetPlatform.iOS)); expect(defaultTargetPlatform, equals(TargetPlatform.iOS)); }, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); group('all', () { testWidgets('TargetPlatformVariant.all tests run all variants', (WidgetTester tester) async { if (debugDefaultTargetPlatformOverride == null) { expect(numberOfVariationsRun, equals(TargetPlatform.values.length)); } else { numberOfVariationsRun += 1; } }, variant: TargetPlatformVariant.all()); const Set<TargetPlatform> excludePlatforms = <TargetPlatform>{ TargetPlatform.android, TargetPlatform.linux }; testWidgets('TargetPlatformVariant.all, excluding runs an all variants except those provided in excluding', (WidgetTester tester) async { if (debugDefaultTargetPlatformOverride == null) { expect(numberOfVariationsRun, equals(TargetPlatform.values.length - excludePlatforms.length)); expect( excludePlatforms, isNot(contains(debugDefaultTargetPlatformOverride)), reason: 'this test should not run on any platform in excludePlatforms' ); } else { numberOfVariationsRun += 1; } }, variant: TargetPlatformVariant.all(excluding: excludePlatforms)); }); testWidgets('TargetPlatformVariant.desktop + mobile contains all TargetPlatform values', (WidgetTester tester) async { final TargetPlatformVariant all = TargetPlatformVariant.all(); final TargetPlatformVariant desktop = TargetPlatformVariant.all(); final TargetPlatformVariant mobile = TargetPlatformVariant.all(); expect(desktop.values.union(mobile.values), equals(all.values)); }); }); group('Pending timer', () { late TestExceptionReporter currentExceptionReporter; setUp(() { currentExceptionReporter = reportTestException; }); tearDown(() { reportTestException = currentExceptionReporter; }); test('Throws assertion message without code', () async { late FlutterErrorDetails flutterErrorDetails; reportTestException = (FlutterErrorDetails details, String testDescription) { flutterErrorDetails = details; }; final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); await binding.runTest(() async { final Timer timer = Timer(const Duration(seconds: 1), () {}); expect(timer.isActive, true); }, () {}); expect(flutterErrorDetails.exception, isA<AssertionError>()); expect((flutterErrorDetails.exception as AssertionError).message, 'A Timer is still pending even after the widget tree was disposed.'); expect(binding.inTest, true); binding.postTest(); }); }); group('Accessibility announcements testing API', () { testWidgets('Returns the list of announcements', (WidgetTester tester) async { // Make sure the handler is properly set expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .checkMockMessageHandler(SystemChannels.accessibility.name, null), isFalse); await SemanticsService.announce('announcement 1', TextDirection.ltr); await SemanticsService.announce('announcement 2', TextDirection.rtl, assertiveness: Assertiveness.assertive); await SemanticsService.announce('announcement 3', TextDirection.rtl); final List<CapturedAccessibilityAnnouncement> list = tester.takeAnnouncements(); expect(list, hasLength(3)); final CapturedAccessibilityAnnouncement first = list[0]; expect(first.message, 'announcement 1'); expect(first.textDirection, TextDirection.ltr); final CapturedAccessibilityAnnouncement second = list[1]; expect(second.message, 'announcement 2'); expect(second.textDirection, TextDirection.rtl); expect(second.assertiveness, Assertiveness.assertive); final CapturedAccessibilityAnnouncement third = list[2]; expect(third.message, 'announcement 3'); expect(third.textDirection, TextDirection.rtl); expect(third.assertiveness, Assertiveness.polite); final List<CapturedAccessibilityAnnouncement> emptyList = tester.takeAnnouncements(); expect(emptyList, <CapturedAccessibilityAnnouncement>[]); }); test('New test API is not breaking existing tests', () async { final List<Map<dynamic, dynamic>> log = <Map<dynamic, dynamic>>[]; Future<dynamic> handleMessage(dynamic mockMessage) async { final Map<dynamic, dynamic> message = mockMessage as Map<dynamic, dynamic>; log.add(message); } TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler<dynamic>( SystemChannels.accessibility, handleMessage); await SemanticsService.announce('announcement 1', TextDirection.rtl, assertiveness: Assertiveness.assertive); expect( log, equals(<Map<String, dynamic>>[ <String, dynamic>{ 'type': 'announce', 'data': <String, dynamic>{ 'message': 'announcement 1', 'textDirection': 0, 'assertiveness': 1 } }, ])); // Remove the handler TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockDecodedMessageHandler<dynamic>( SystemChannels.accessibility, null); }); tearDown(() { // Make sure that the handler is removed in [TestWidgetsFlutterBinding.postTest] expect(TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .checkMockMessageHandler(SystemChannels.accessibility.name, null), isTrue); }); }); testWidgets('wrapWithView: false does not include View', (WidgetTester tester) async { FlutterView? flutterView; View? view; int builderCount = 0; await tester.pumpWidget( wrapWithView: false, Builder( builder: (BuildContext context) { builderCount++; flutterView = View.maybeOf(context); view = context.findAncestorWidgetOfExactType<View>(); return const ViewCollection(views: <Widget>[]); }, ), ); expect(builderCount, 1); expect(view, isNull); expect(flutterView, isNull); expect(find.byType(View), findsNothing); }); testWidgets('passing a view to pumpWidget with wrapWithView: true throws', (WidgetTester tester) async { await tester.pumpWidget( View( view: FakeView(tester.view), child: const SizedBox.shrink(), ), ); expect( tester.takeException(), isFlutterError.having( (FlutterError e) => e.message, 'message', contains('consider setting the "wrapWithView" parameter of that method to false'), ), ); }); testWidgets('can pass a View to pumpWidget when wrapWithView: false', (WidgetTester tester) async { await tester.pumpWidget( wrapWithView: false, View( view: tester.view, child: const SizedBox.shrink(), ), ); expect(find.byType(View), findsOne); }); } class FakeMatcher extends AsyncMatcher { FakeMatcher(this.completer); final Completer<void> completer; @override Future<String?> matchAsync(dynamic object) { return completer.future.then<String?>((void value) { return object?.toString(); }); } @override Description describe(Description description) => description.add('--fake--'); } class _AlwaysAnimating extends StatefulWidget { const _AlwaysAnimating({ required this.onPaint, }); final VoidCallback onPaint; @override State<StatefulWidget> createState() => _AlwaysAnimatingState(); } class _AlwaysAnimatingState extends State<_AlwaysAnimating> with SingleTickerProviderStateMixin { late AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: this, ); _controller.repeat(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller.view, builder: (BuildContext context, Widget? child) { return CustomPaint( painter: _AlwaysRepaint(widget.onPaint), ); }, ); } } class _AlwaysRepaint extends CustomPainter { _AlwaysRepaint(this.onPaint); final VoidCallback onPaint; @override bool shouldRepaint(CustomPainter oldDelegate) => true; @override void paint(Canvas canvas, Size size) { onPaint(); } }
flutter/packages/flutter_test/test/widget_tester_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/widget_tester_test.dart", "repo_id": "flutter", "token_count": 10588 }
732
# Flutter Tools This section of the Flutter repository contains the command line developer tools for building Flutter applications. ## Working on Flutter Tools Be sure to follow the instructions on [CONTRIBUTING.md](../../CONTRIBUTING.md) to set up your development environment. Further, familiarize yourself with the [style guide](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo), which we follow. ### Setting up First, ensure that the Dart SDK and other necessary artifacts are available by invoking the Flutter Tools wrapper script. In this directory run: ```shell $ flutter --version ``` ### Running the Tool To run Flutter Tools from source, in this directory run: ```shell $ dart bin/flutter_tools.dart ``` followed by command-line arguments, as usual. ### Running the analyzer To run the analyzer on Flutter Tools, in this directory run: ```shell $ flutter analyze ``` ### Writing tests As with other parts of the Flutter repository, all changes in behavior [must be tested](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#write-test-find-bug). Tests live under the `test/` subdirectory. - Hermetic unit tests of tool internals go under `test/general.shard` and must run in significantly less than two seconds. - Tests of tool commands go under `test/commands.shard`. Hermetic tests go under its `hermetic/` subdirectory. Non-hermetic tests go under its `permeable` sub-directory. Avoid adding tests here and prefer writing either a unit test or a full integration test. - Integration tests (e.g. tests that run the tool in a subprocess) go under `test/integration.shard`. - Slow web-related tests go in the `test/web.shard` directory. In general, the tests for the code in a file called `file.dart` should go in a file called `file_test.dart` in the subdirectory that matches the behavior of the test. The `dart_test.yaml` file configures the timeout for these tests to be 15 minutes. The `test.dart` script that is used in CI overrides this to two seconds for the `test/general.shard` directory, to catch behaviour that is unexpectedly slow. Please avoid setting any other timeouts. #### Using local engine builds in integration tests The integration tests can be configured to use a specific local engine variant by setting the `FLUTTER_LOCAL_ENGINE` and `FLUTTER_LOCAL_ENGINE_HOST` environment svariable to the name of the local engines (e.g. `android_debug_unopt` and `host_debug_unopt`). If the local engine build requires a source path, this can be provided by setting the `FLUTTER_LOCAL_ENGINE_SRC_PATH` environment variable. This second variable is not necessary if the `flutter` and `engine` checkouts are in adjacent directories. ```shell export FLUTTER_LOCAL_ENGINE=android_debug_unopt export FLUTTER_LOCAL_ENGINE_HOST=host_debug_unopt flutter test test/integration.shard/some_test_case ``` ### Running the tests To run all of the unit tests: ```shell $ flutter test test/general.shard ``` The tests in `test/integration.shard` are slower to run than the tests in `test/general.shard`. Depending on your development computer, you might want to limit concurrency. Generally it is easier to run these on CI, or to manually verify the behavior you are changing instead of running the test. The integration tests also require the `FLUTTER_ROOT` environment variable to be set. The full invocation to run everything might therefore look something like: ```shell $ export FLUTTER_ROOT=~/path/to/flutter-sdk $ flutter test --concurrency 1 ``` This may take some time (on the order of an hour). The unit tests alone take much less time (on the order of a minute). You can run the tests in a specific file, e.g.: ```shell $ flutter test test/general.shard/utils_test.dart ``` ### Forcing snapshot regeneration To force the Flutter Tools snapshot to be regenerated, delete the following files: ```shell $ rm ../../bin/cache/flutter_tools.stamp ../../bin/cache/flutter_tools.snapshot ```
flutter/packages/flutter_tools/README.md/0
{ "file_path": "flutter/packages/flutter_tools/README.md", "repo_id": "flutter", "token_count": 1148 }
733
# Flutter Daemon ## Overview The `flutter` command-line tool supports a daemon server mode for use by IDEs and other tools. ``` flutter daemon ``` It runs a persistent, JSON-RPC based server to communicate with devices. IDEs and other tools can start the flutter tool in this mode and get device addition and removal notifications, as well as being able to programmatically start and stop apps on those devices. A set of `flutter daemon` commands/events are also exposed via `flutter run --machine` and `flutter attach --machine` which allow IDEs and tools to launch and attach to Flutter applications and interact to send commands like Hot Reload. The command and events that are available in these modes are documented at the bottom of this document. ## Protocol The daemon speaks [JSON-RPC](http://json-rpc.org/) to clients. It uses stdin and stdout as the transport protocol. To send a command to the server, create your command as a JSON-RPC message, encode it to JSON, surround the encoded text with square brackets, and write it as one line of text to the stdin of the process: ``` [{"method":"daemon.version","id":0}] ``` The response will come back as a single line from stdout: ``` [{"id":0,"result":"0.1.0"}] ``` All requests and responses should be wrapped in square brackets. This ensures that the communications are resilient to stray output in the stdout/stdin stream. `id` is an opaque type to the server, but ids should be unique for the life of the server. A response to a particular command will contain the id that was passed in for that command. Each command should have a `method` field. This is in the form '`domain.command`'. Any params for that command should be passed in through a `params` field. Here's an example request/response for the `device.getDevices` method: ``` [{"method":"device.getDevices","id":2}] ``` ``` [{"id":2,"result":[{"id":"702ABC1F-5EA5-4F83-84AB-6380CA91D39A","name":"iPhone 6","platform":"ios_x64","available":true}]}] ``` Events that come from the server will have an `event` field containing the type of event, along with a `params` field. ``` [{"event":"device.added","params":{"id":"1DD6786B-37D4-4355-AA15-B818A87A18B4","name":"iPhone XS Max","platform":"ios","emulator":true,"ephemeral":false,"platformType":"ios","category":"mobile"}}] ``` ## Domains and Commands ### daemon domain #### daemon.version The `version()` command responds with a String with the protocol version. #### daemon.shutdown The `shutdown()` command will terminate the flutter daemon. It is not necessary to call this before shutting down the daemon; it is perfectly acceptable to just kill the daemon process. #### daemon.getSupportedPlatforms The `getSupportedPlatforms()` command will enumerate all platforms supported by the project located at the provided `projectRoot`. It returns a Map with the key 'platformTypes' containing a Map of platform types to a Map with the following entries: - isSupported (bool) - whether or not the platform type is supported - reasons (List<Map<String, Object>>, only included if isSupported == false) - a list of reasons why the platform is not supported The schema for each element in `reasons` is: - reasonText (String) - a description of why the platform is not supported - fixText (String) - human readable instructions of how to fix this reason - fixCode (String) - stringified version of the `_ReasonCode` enum. To be used by daemon clients who intend to auto-fix. The possible platform types are the `PlatformType` enumeration in the lib/src/device.dart library. #### Events #### daemon.connected The `daemon.connected` event is sent when the daemon starts. The `params` field will be a map with the following fields: - `version`: The protocol version. This is the same version returned by the `version()` command. - `pid`: The `pid` of the daemon process. #### daemon.log This is sent when user-facing output is received. The `params` field will be a map with the field `log`. The `log` field is a string with the output text. If the output indicates an error, an `error` boolean field will be present, and set to `true`. #### daemon.showMessage The `daemon.showMessage` event is sent by the daemon when some if would be useful to show a message to the user. This could be an error notification or a notification that some development tools are not configured or not installed. The JSON message will contain an `event` field with the value `daemon.showMessage`, and a `params` field containing a map with `level`, `title`, and `message` fields. The valid options for `level` are `info`, `warning`, and `error`. It is up to the client to decide how best to display the message; for some clients, it may map well to a toast style notification. There is an implicit contract that the daemon will not send too many messages over a reasonable period of time. #### daemon.logMessage The `daemon.logMessage` event is sent whenever a log message is created - either a status level message or an error. The JSON message will contain an `event` field with the value `daemon.logMessage`, and a `params` field containing a map with `level`, `message`, and (optionally) `stackTrace` fields. Generally, clients won't display content from `daemon.logMessage` events unless they're set to a more verbose output mode. ### app domain #### app.restart The `restart()` restarts the given application. It returns a Map of `{ int code, String message }` to indicate success or failure in restarting the app. A `code` of `0` indicates success, and non-zero indicates a failure. - `appId`: the id of a previously started app; this is required. - `fullRestart`: optional; whether to do a full (rather than an incremental) restart of the application - `reason`: optional; the reason for the full restart (eg. `save`, `manual`) for reporting purposes - `pause`: optional; when doing a hot restart the isolate should enter a paused mode - `debounce`: optional; whether to automatically debounce multiple requests sent in quick succession (this may introduce a short delay in processing the request) #### app.reloadMethod (Removed) This functionality was deprecated and removed after Flutter version 1.23.0 #### app.callServiceExtension The `callServiceExtension()` allows clients to make arbitrary calls to service protocol extensions. It returns a `Map` - the result returned by the service protocol method. - `appId`: the id of a previously started app; this is required. - `methodName`: the name of the service protocol extension to invoke; this is required. - `params`: an optional Map of parameters to pass to the service protocol extension. #### app.detach The `detach()` command takes one parameter, `appId`. It returns a `bool` to indicate success or failure in detaching from an app without stopping it. - `appId`: the id of a previously started app; this is required. #### app.stop The `stop()` command takes one parameter, `appId`. It returns a `bool` to indicate success or failure in stopping an app. - `appId`: the id of a previously started app; this is required. #### Events #### app.start This is sent when an app is starting. The `params` field will be a map with the fields `appId`, `directory`, `deviceId`, `launchMode` (`run`/`attach`) and `mode` (`debug`, `profile`, `release`, `jit_release`). #### app.debugPort This is sent when a VM service port is available for a started app. The `params` field will be a map with the fields `appId`, `port`, and `wsUri`. Clients should prefer using the `wsUri` field in preference to synthesizing a URI using the `port` field. An optional field, `baseUri`, is populated if a path prefix is required for setting breakpoints on the target device. #### app.started This is sent once the application launch process is complete and the app is either paused before main() (if `startPaused` is true) or main() has begun running. When attaching, this even will be fired once attached. The `params` field will be a map containing the field `appId`. #### app.log This is sent when output is logged for a running application. The `params` field will be a map with the fields `appId` and `log`. The `log` field is a string with the output text. If the output indicates an error, an `error` boolean field will be present, and set to `true`. #### app.progress This is sent when an operation starts and again when it stops. When an operation starts, the event contains the fields `id`, an opaque identifier, and `message` containing text describing the operation. When that same operation ends, the event contains the same `id` field value as when the operation started, along with a `finished` bool field with the value true, but no `message` field. #### app.stop This is sent when an app is stopped or detached from. The `params` field will be a map with the field `appId`. #### app.webLaunchUrl This is sent once a web application is being served and available for the user to access. The `params` field will be a map with a string `url` field and a boolean `launched` indicating whether the application has already been launched in a browser (this will generally be true for a browser device unless `--no-web-browser-launch` was used, and false for the headless `web-server` device). ### Daemon-to-Editor Requests These requests come _from_ the Flutter daemon and should be responded to by the client/editor. #### app.exposeUrl This request is enabled only if `flutter run` is run with the `--web-allow-expose-url` flag. This request is sent by the server when it has a local URL that needs to be exposed to the end-user. This is to support running on a remote machine where a URL (for example `http://localhost:1234`) may not be directly accessible to the end-user. With this URL clients can perform tunneling and then provide the tunneled URL back to Flutter so that it can be used in code that will be executed on the end-users machine (for example when a web application needs to be able to connect back to a service like the DWDS debugging service). This request will only be sent if a web application was run in a mode that requires mapped URLs (such as using `--no-web-browser-launch` for browser devices or the headless `web-server` device when debugging). The request will contain an `id` field and a `params` field that is a map containing a string `url` field. The response should be sent using the same `id` as the request with a `result` map containing the mapped `url` (or the same URL in the case where the client does not need to perform any mapping). ### device domain #### device.getDevices Return a list of all connected devices. The `params` field will be a List; each item is a map with the fields `id`, `name`, `platform`, `category`, `platformType`, `ephemeral`, `emulator` (a boolean) and `emulatorId`. `category` is a string description of the kind of workflow the device supports. The current categories are "mobile", "web" and "desktop", or null if none. `platformType` is a string description of the platform sub-folder the device supports. The current categories are "android", "ios", "linux", "macos", "fuchsia", "windows", and "web". These are kept in sync with the response from `daemon.getSupportedPlatforms`. `ephemeral` is a boolean which indicates where the device needs to be manually connected to a development machine. For example, a physical Android device is ephemeral, but the "web" device (that is always present) is not. `emulatorId` is a string ID that matches the ID from `getEmulators` to allow clients to match running devices to the emulators that started them (for example to hide emulators that are already running). This field is not guaranteed to be populated even if a device was spawned from an emulator as it may require a successful connection to the device to retrieve it. In the case of a failed connection or the device is not an emulator, this field will be null. #### device.enable Turn on device polling. This will poll for newly connected devices, and fire `device.added` and `device.removed` events. #### device.disable Turn off device polling. #### device.forward Forward a host port to a device port. This call takes two required arguments, `deviceId` and `devicePort`, and one optional argument, `hostPort`. If `hostPort` is not specified, the host port will be any available port. This method returns a map with a `hostPort` fieldset. #### device.unforward Removed a forwarded port. It takes `deviceId`, `devicePort`, and `hostPort` as required arguments. #### Events #### device.added This is sent when a device is connected (and polling has been enabled via `enable()`). The `params` field will be a map with the fields `id`, `name`, `platform`, `category`, `platformType`, `ephemeral`, and `emulator`. For more information on `platform`, `category`, `platformType`, and `ephemeral` see `device.getDevices`. #### device.removed This is sent when a device is disconnected (and polling has been enabled via `enable()`). The `params` field will be a map with the fields `id`, `name`, `platform`, `category`, `platformType`, `ephemeral`, and `emulator`. For more information on `platform`, `category`, `platformType`, and `ephemeral` see `device.getDevices`. ### emulator domain #### emulator.getEmulators Return a list of all available emulators. The `params` field will be a List; each item is a map with the fields `id`, `name`, `category` and `platformType`. `category` and `platformType` values match the values described in `device.getDevices`. #### emulator.launch The `launch()` command allows launching an emulator/simulator by its `id`. - `emulatorId`: the id of an emulator as returned by `getEmulators`. - `coldBoot`: an optional boolean flag which indicates if the emulator should be cold booted. Only supported for android emulators, silently ignored if emulator type is not android. #### emulator.create The `create()` command creates a new Android emulator with an optional `name`. - `name`: an optional name for this emulator The returned `params` will contain: - `success` - whether the emulator was successfully created - `emulatorName` - the name of the emulator created; this will have been auto-generated if you did not supply one - `error` - when `success`=`false`, a message explaining why the creation of the emulator failed ### devtools domain #### devtools.serve The `serve()` command starts a DevTools server if one isn't already running. The return value will contain: - `success` - whether the server started. - `host` - the address host if the server successfully started. - `port` - the port if the server successfully started. ## 'flutter run --machine' and 'flutter attach --machine' When running `flutter run --machine` or `flutter attach --machine` the following subset of the daemon is available: ### daemon domain The following subset of the daemon domain is available in `flutter run --machine`. Refer to the documentation above for details. - Commands - [`version`](#daemonversion) - [`shutdown`](#daemonshutdown) - Events - [`connected`](#daemonconnected) - [`log`](#daemonlog) - [`logMessage`](#daemonlogmessage) ### app domain The following subset of the app domain is available in `flutter run --machine`. Refer to the documentation above for details. - Commands - [`restart`](#apprestart) - [`callServiceExtension`](#appcallserviceextension) - [`detach`](#appdetach) - [`stop`](#appstop) - Events - [`start`](#appstart) - [`debugPort`](#appdebugport) - [`started`](#appstarted) - [`log`](#applog) - [`progress`](#appprogress) - [`stop`](#appstop) ## Source See the [source](https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/commands/daemon.dart) for the daemon protocol and implementation. ## Changelog - 0.6.1: Added `coldBoot` option to `emulator.launch` command. - 0.6.0: Added `debounce` option to `app.restart` command. - 0.5.3: Added `emulatorId` field to device. - 0.5.2: Added `platformType` and `category` fields to emulator. - 0.5.1: Added `platformType`, `ephemeral`, and `category` fields to device. - 0.5.0: Added `daemon.getSupportedPlatforms` command - 0.4.2: Added `app.detach` command - 0.4.1: Added `flutter attach --machine` - 0.4.0: Added `emulator.create` command - 0.3.0: Added `daemon.connected` event at startup
flutter/packages/flutter_tools/doc/daemon.md/0
{ "file_path": "flutter/packages/flutter_tools/doc/daemon.md", "repo_id": "flutter", "token_count": 4343 }
734
// 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 org.gradle.api.JavaVersion import org.jetbrains.kotlin.gradle.plugin.KotlinAndroidPluginWrapper // This buildscript block supplies dependencies for this file's own import // declarations above. It exists solely for compatibility with projects that // have not migrated to declaratively apply the Flutter Gradle Plugin; // for those that have, FGP's `build.gradle.kts` takes care of this. buildscript { repositories { google() mavenCentral() } dependencies { // When bumping, also update: // * ndkVersion in FlutterExtension in packages/flutter_tools/gradle/src/main/groovy/flutter.groovy // * AGP version in the buildscript block in packages/flutter_tools/gradle/src/main/groovy/flutter.groovy // * AGP version constants in packages/flutter_tools/lib/src/android/gradle_utils.dart // * AGP version in dependencies block in packages/flutter_tools/gradle/build.gradle.kts classpath("com.android.tools.build:gradle:7.3.0") classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10") } } apply<FlutterDependencyCheckerPlugin>() class FlutterDependencyCheckerPlugin : Plugin<Project> { override fun apply(project: Project) { DependencyVersionChecker.checkDependencyVersions(project) } } class DependencyVersionChecker { companion object { private const val GRADLE_NAME: String = "Gradle" private const val JAVA_NAME: String = "Java" private const val AGP_NAME: String = "Android Gradle Plugin" private const val KGP_NAME: String = "Kotlin" // The following messages represent best effort guesses at where a Flutter developer should // look to upgrade a dependency that is below the corresponding threshold. Developers can // change some of these locations, so they are not guaranteed to be accurate. private fun getPotentialGradleFix(projectDirectory: String): String { return "Your project's gradle version is typically " + "defined in the gradle wrapper file. By default, this can be found at " + "$projectDirectory/gradle/wrapper/gradle-wrapper.properties. \n" + "For more information, see https://docs.gradle.org/current/userguide/gradle_wrapper.html.\n" } // The potential java fix does not make use of the project directory, // so it left as a constant. private const val POTENTIAL_JAVA_FIX: String = "The Java version used by Flutter can be " + "set with `flutter config --jdk-dir=<path>`. \nFor more information about how Flutter " + "chooses which version of Java to use, see the --jdk-dir section of the " + "output of `flutter config -h`.\n" private fun getPotentialAGPFix(projectDirectory: String): String { return "Your project's AGP version is typically " + "defined the plugins block of the `settings.gradle` file " + "($projectDirectory/settings.gradle), by a plugin with the id of " + "com.android.application. \nIf you don't see a plugins block, your project " + "was likely created with an older template version. In this case it is most " + "likely defined in the top-level build.gradle file " + "($projectDirectory/build.gradle) by the following line in the dependencies" + " block of the buildscript: \"classpath 'com.android.tools.build:gradle:<version>'\".\n" } private fun getPotentialKGPFix(projectDirectory: String): String { return "Your project's KGP version is typically " + "defined the plugins block of the `settings.gradle` file " + "($projectDirectory/settings.gradle), by a plugin with the id of " + "org.jetbrains.kotlin.android. \nIf you don't see a plugins block, your project " + "was likely created with an older template version, in which case it is most " + "likely defined in the top-level build.gradle file " + "($projectDirectory/build.gradle) by the ext.kotlin_version property.\n" } // The following versions define our support policy for Gradle, Java, AGP, and KGP. // All "error" versions are currently set to 0 as this policy is new. They will be increased // to match the current values of the "warn" versions in the next release. // Before updating any "error" version, ensure that you have updated the corresponding // "warn" version for a full release to provide advanced warning. See // flutter.dev/go/android-dependency-versions for more. // TODO(gmackall): https://github.com/flutter/flutter/issues/142653. val warnGradleVersion: Version = Version(7, 0, 2) val errorGradleVersion: Version = Version(0, 0, 0) val warnJavaVersion: JavaVersion = JavaVersion.VERSION_11 val errorJavaVersion: JavaVersion = JavaVersion.VERSION_1_1 val warnAGPVersion: Version = Version(7, 0, 0) val errorAGPVersion: Version = Version(0, 0, 0) val warnKGPVersion: Version = Version(1, 5, 0) val errorKGPVersion: Version = Version(0, 0, 0) /** * Checks if the project's Android build time dependencies are each within the respective * version range that we support. When we can't find a version for a given dependency * we treat it as within the range for the purpose of this check. */ fun checkDependencyVersions(project: Project) { var agpVersion: Version? = null var kgpVersion: Version? = null checkGradleVersion(getGradleVersion(project), project) checkJavaVersion(getJavaVersion(project), project) agpVersion = getAGPVersion(project) if (agpVersion != null) { checkAGPVersion(agpVersion, project) } else { project.logger.error( "Warning: unable to detect project AGP version. Skipping " + "version checking. \nThis may be because you have applied AGP after the Flutter Gradle Plugin.", ) } kgpVersion = getKGPVersion(project) if (kgpVersion != null) { checkKGPVersion(kgpVersion, project) } else { project.logger.error( "Warning: unable to detect project KGP version. Skipping " + "version checking. \nThis may be because you have applied KGP after the Flutter Gradle Plugin.", ) } } // https://docs.gradle.org/current/kotlin-dsl/gradle/org.gradle.api.invocation/-gradle/index.html#-837060600%2FFunctions%2F-1793262594 fun getGradleVersion(project: Project): Version { val untrimmedGradleVersion: String = project.gradle.getGradleVersion() // Trim to handle candidate gradle versions (example 7.6-rc-4). This means we treat all // candidate versions of gradle as the same as their base version // (i.e., "7.6"="7.6-rc-4"). return Version.fromString(untrimmedGradleVersion.substringBefore('-')) } // https://docs.gradle.org/current/kotlin-dsl/gradle/org.gradle.api/-java-version/index.html#-1790786897%2FFunctions%2F-1793262594 fun getJavaVersion(project: Project): JavaVersion { return JavaVersion.current() } // This approach is taken from AGP's own version checking plugin: // https://android.googlesource.com/platform/tools/base/+/1839aa23b8dc562005e2f0f0cc8e8b4c5caa37d0/build-system/gradle-core/src/main/java/com/android/build/gradle/internal/utils/agpVersionChecker.kt#58. fun getAGPVersion(project: Project): Version? { val agpPluginName: String = "com.android.base" val agpVersionFieldName: String = "ANDROID_GRADLE_PLUGIN_VERSION" var agpVersion: Version? = null try { agpVersion = Version.fromString( project.plugins.getPlugin(agpPluginName)::class.java.classLoader.loadClass( com.android.Version::class.java.name, ).fields.find { it.name == agpVersionFieldName }!! .get(null) as String, ) } catch (ignored: ClassNotFoundException) { // Use deprecated Version class as it exists in older AGP (com.android.Version) does // not exist in those versions. agpVersion = Version.fromString( project.plugins.getPlugin(agpPluginName)::class.java.classLoader.loadClass( com.android.builder.model.Version::class.java.name, ).fields.find { it.name == agpVersionFieldName }!! .get(null) as String, ) } return agpVersion } fun getKGPVersion(project: Project): Version? { val kotlinVersionProperty: String = "kotlin_version" val firstKotlinVersionFieldName: String = "pluginVersion" val secondKotlinVersionFieldName: String = "kotlinPluginVersion" // This property corresponds to application of the Kotlin Gradle plugin in the // top-level build.gradle file. if (project.hasProperty(kotlinVersionProperty)) { return Version.fromString(project.properties.get(kotlinVersionProperty) as String) } val kotlinPlugin = project.getPlugins() .findPlugin(KotlinAndroidPluginWrapper::class.java) val versionfield = kotlinPlugin?.javaClass?.kotlin?.members?.first { it.name == firstKotlinVersionFieldName || it.name == secondKotlinVersionFieldName } val versionString = versionfield?.call(kotlinPlugin) if (versionString == null) { return null } else { return Version.fromString(versionString!! as String) } } private fun getErrorMessage( dependencyName: String, versionString: String, errorVersion: String, potentialFix: String, ): String { return "Error: Your project's $dependencyName version ($versionString) is lower " + "than Flutter's minimum supported version of $errorVersion. Please upgrade " + "your $dependencyName version. \nAlternatively, use the flag " + "\"--android-skip-build-dependency-validation\" to bypass this check.\n\n" + "Potential fix: $potentialFix" } private fun getWarnMessage( dependencyName: String, versionString: String, warnVersion: String, potentialFix: String, ): String { return "Warning: Flutter support for your project's $dependencyName version " + "($versionString) will soon be dropped. Please upgrade your $dependencyName " + "version to a version of at least $warnVersion soon." + "\nAlternatively, use the flag \"--android-skip-build-dependency-validation\"" + " to bypass this check.\n\nPotential fix: $potentialFix" } fun checkGradleVersion( version: Version, project: Project, ) { if (version < errorGradleVersion) { val errorMessage: String = getErrorMessage( GRADLE_NAME, version.toString(), errorGradleVersion.toString(), getPotentialGradleFix(project.getRootDir().getPath()), ) throw GradleException(errorMessage) } else if (version < warnGradleVersion) { val warnMessage: String = getWarnMessage( GRADLE_NAME, version.toString(), warnGradleVersion.toString(), getPotentialGradleFix(project.getRootDir().getPath()), ) project.logger.error(warnMessage) } } fun checkJavaVersion( version: JavaVersion, project: Project, ) { if (version < errorJavaVersion) { val errorMessage: String = getErrorMessage( JAVA_NAME, version.toString(), errorJavaVersion.toString(), POTENTIAL_JAVA_FIX, ) throw GradleException(errorMessage) } else if (version < warnJavaVersion) { val warnMessage: String = getWarnMessage( JAVA_NAME, version.toString(), warnJavaVersion.toString(), POTENTIAL_JAVA_FIX, ) project.logger.error(warnMessage) } } fun checkAGPVersion( version: Version, project: Project, ) { if (version < errorAGPVersion) { val errorMessage: String = getErrorMessage( AGP_NAME, version.toString(), errorAGPVersion.toString(), getPotentialAGPFix(project.getRootDir().getPath()), ) throw GradleException(errorMessage) } else if (version < warnAGPVersion) { val warnMessage: String = getWarnMessage( AGP_NAME, version.toString(), warnAGPVersion.toString(), getPotentialAGPFix(project.getRootDir().getPath()), ) project.logger.error(warnMessage) } } fun checkKGPVersion( version: Version, project: Project, ) { if (version < errorKGPVersion) { val errorMessage: String = getErrorMessage( KGP_NAME, version.toString(), errorKGPVersion.toString(), getPotentialKGPFix(project.getRootDir().getPath()), ) throw GradleException(errorMessage) } else if (version < warnKGPVersion) { val warnMessage: String = getWarnMessage( KGP_NAME, version.toString(), warnKGPVersion.toString(), getPotentialKGPFix(project.getRootDir().getPath()), ) project.logger.error(warnMessage) } } } } // Helper class to parse the versions that are provided as plain strings (Gradle, Kotlin) and // perform easy comparisons. All versions will have a major, minor, and patch value. These values // default to 0 when they are not provided or are otherwise unparseable. // For example the version strings "8.2", "8.2.2hfd", and "8.2.0" would parse to the same version. class Version(val major: Int, val minor: Int, val patch: Int) : Comparable<Version> { companion object { fun fromString(version: String): Version { val asList: List<String> = version.split(".") val convertedToNumbers: List<Int> = asList.map { it.toIntOrNull() ?: 0 } return Version( major = convertedToNumbers.getOrElse(0, { 0 }), minor = convertedToNumbers.getOrElse(1, { 0 }), patch = convertedToNumbers.getOrElse(2, { 0 }), ) } } override fun compareTo(otherVersion: Version): Int { if (major != otherVersion.major) { return major - otherVersion.major } if (minor != otherVersion.minor) { return minor - otherVersion.minor } if (patch != otherVersion.patch) { return patch - otherVersion.patch } return 0 } override fun toString(): String { return major.toString() + "." + minor.toString() + "." + patch.toString() } }
flutter/packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts/0
{ "file_path": "flutter/packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts", "repo_id": "flutter", "token_count": 7793 }
735
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="layers - custom_render_box" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/layers/widgets/custom_render_box.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___custom_render_box.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___custom_render_box.xml.copy.tmpl", "repo_id": "flutter", "token_count": 99 }
736
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="manual_tests - overlay_geometry" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/overlay_geometry.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___overlay_geometry.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___overlay_geometry.xml.copy.tmpl", "repo_id": "flutter", "token_count": 100 }
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:collection'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'package:xml/xml.dart'; import '../application_package.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../base/user_messages.dart'; import '../build_info.dart'; import '../project.dart'; import 'android_sdk.dart'; import 'gradle.dart'; /// An application package created from an already built Android APK. class AndroidApk extends ApplicationPackage implements PrebuiltApplicationPackage { AndroidApk({ required super.id, required this.applicationPackage, required this.versionCode, required this.launchActivity, }); /// Creates a new AndroidApk from an existing APK. /// /// Returns `null` if the APK was invalid or any required tooling was missing. static AndroidApk? fromApk( File apk, { required AndroidSdk androidSdk, required ProcessManager processManager, required UserMessages userMessages, required Logger logger, required ProcessUtils processUtils, }) { final String? aaptPath = androidSdk.latestVersion?.aaptPath; if (aaptPath == null || !processManager.canRun(aaptPath)) { logger.printError(userMessages.aaptNotFound); return null; } String apptStdout; try { apptStdout = processUtils.runSync( <String>[ aaptPath, 'dump', 'xmltree', apk.path, 'AndroidManifest.xml', ], throwOnError: true, ).stdout.trim(); } on ProcessException catch (error) { logger.printError('Failed to extract manifest from APK: $error.'); return null; } final ApkManifestData? data = ApkManifestData.parseFromXmlDump(apptStdout, logger); if (data == null) { logger.printError('Unable to read manifest info from ${apk.path}.'); return null; } final String? packageName = data.packageName; if (packageName == null || data.launchableActivityName == null) { logger.printError('Unable to read manifest info from ${apk.path}.'); return null; } return AndroidApk( id: packageName, applicationPackage: apk, versionCode: data.versionCode == null ? null : int.tryParse(data.versionCode!), launchActivity: '${data.packageName}/${data.launchableActivityName}', ); } @override final FileSystemEntity applicationPackage; /// The path to the activity that should be launched. final String launchActivity; /// The version code of the APK. final int? versionCode; /// Creates a new AndroidApk based on the information in the Android manifest. static Future<AndroidApk?> fromAndroidProject( AndroidProject androidProject, { required AndroidSdk? androidSdk, required ProcessManager processManager, required UserMessages userMessages, required ProcessUtils processUtils, required Logger logger, required FileSystem fileSystem, BuildInfo? buildInfo, }) async { final File apkFile; final String filename; if (buildInfo == null) { filename = 'app.apk'; } else if (buildInfo.flavor == null) { filename = 'app-${buildInfo.mode.cliName}.apk'; } else { filename = 'app-${buildInfo.lowerCasedFlavor}-${buildInfo.mode.cliName}.apk'; } if (androidProject.isUsingGradle && androidProject.isSupportedVersion) { Directory apkDirectory = getApkDirectory(androidProject.parent); if (androidProject.parent.isModule) { // Module builds output the apk in a subdirectory that corresponds // to the buildmode of the apk. apkDirectory = apkDirectory.childDirectory(buildInfo!.mode.cliName); } apkFile = apkDirectory.childFile(filename); if (apkFile.existsSync()) { // Grab information from the .apk. The gradle build script might alter // the application Id, so we need to look at what was actually built. return AndroidApk.fromApk( apkFile, androidSdk: androidSdk!, processManager: processManager, logger: logger, userMessages: userMessages, processUtils: processUtils, ); } // The .apk hasn't been built yet, so we work with what we have. The run // command will grab a new AndroidApk after building, to get the updated // IDs. } else { apkFile = fileSystem.file(fileSystem.path.join(getAndroidBuildDirectory(), filename)); } final File manifest = androidProject.appManifestFile; if (!manifest.existsSync()) { logger.printError('AndroidManifest.xml could not be found.'); logger.printError('Please check ${manifest.path} for errors.'); return null; } final String manifestString = manifest.readAsStringSync(); XmlDocument document; try { document = XmlDocument.parse(manifestString); } on XmlException catch (exception) { String manifestLocation; if (androidProject.isUsingGradle) { manifestLocation = fileSystem.path.join(androidProject.hostAppGradleRoot.path, 'app', 'src', 'main', 'AndroidManifest.xml'); } else { manifestLocation = fileSystem.path.join(androidProject.hostAppGradleRoot.path, 'AndroidManifest.xml'); } logger.printError('AndroidManifest.xml is not a valid XML document.'); logger.printError('Please check $manifestLocation for errors.'); throwToolExit('XML Parser error message: $exception'); } final Iterable<XmlElement> manifests = document.findElements('manifest'); if (manifests.isEmpty) { logger.printError('AndroidManifest.xml has no manifest element.'); logger.printError('Please check ${manifest.path} for errors.'); return null; } // Starting from AGP version 7.3, the `package` attribute in Manifest.xml // can be replaced with the `namespace` attribute under the `android` section in `android/app/build.gradle`. final String? packageId = manifests.first.getAttribute('package') ?? androidProject.namespace; String? launchActivity; for (final XmlElement activity in document.findAllElements('activity')) { final String? enabled = activity.getAttribute('android:enabled'); if (enabled != null && enabled == 'false') { continue; } for (final XmlElement element in activity.findElements('intent-filter')) { String? actionName = ''; String? categoryName = ''; for (final XmlNode node in element.children) { if (node is! XmlElement) { continue; } final String? name = node.getAttribute('android:name'); if (name == 'android.intent.action.MAIN') { actionName = name; } else if (name == 'android.intent.category.LAUNCHER') { categoryName = name; } } if (actionName != null && categoryName != null && actionName.isNotEmpty && categoryName.isNotEmpty) { final String? activityName = activity.getAttribute('android:name'); launchActivity = '$packageId/$activityName'; break; } } } if (packageId == null || launchActivity == null) { logger.printError('package identifier or launch activity not found.'); logger.printError('Please check ${manifest.path} for errors.'); return null; } return AndroidApk( id: packageId, applicationPackage: apkFile, versionCode: null, launchActivity: launchActivity, ); } @override String get name => applicationPackage.basename; } abstract class _Entry { const _Entry(this.parent, this.level); final _Element? parent; final int level; } class _Element extends _Entry { _Element._(this.name, _Element? parent, int level) : super(parent, level); factory _Element.fromLine(String line, _Element? parent) { // E: application (line=29) final List<String> parts = line.trimLeft().split(' '); return _Element._(parts[1], parent, line.length - line.trimLeft().length); } final List<_Entry> children = <_Entry>[]; final String? name; void addChild(_Entry child) { children.add(child); } _Attribute? firstAttribute(String name) { for (final _Attribute child in children.whereType<_Attribute>()) { if (child.key?.startsWith(name) ?? false) { return child; } } return null; } _Element? firstElement(String name) { for (final _Element child in children.whereType<_Element>()) { if (child.name?.startsWith(name) ?? false) { return child; } } return null; } Iterable<_Element> allElements(String name) { return children.whereType<_Element>().where((_Element e) => e.name?.startsWith(name) ?? false); } } class _Attribute extends _Entry { const _Attribute._(this.key, this.value, _Element? parent, int level) : super(parent, level); factory _Attribute.fromLine(String line, _Element parent) { // A: android:label(0x01010001)="hello_world" (Raw: "hello_world") const String attributePrefix = 'A: '; final List<String> keyVal = line.substring(line.indexOf(attributePrefix) + attributePrefix.length).split('='); return _Attribute._(keyVal[0], keyVal[1], parent, line.length - line.trimLeft().length); } final String? key; final String? value; } class ApkManifestData { ApkManifestData._(this._data); static bool _isAttributeWithValuePresent( _Element baseElement, String childElement, String attributeName, String attributeValue) { final Iterable<_Element> allElements = baseElement.allElements(childElement); for (final _Element oneElement in allElements) { final String? elementAttributeValue = oneElement .firstAttribute(attributeName) ?.value; if (elementAttributeValue != null && elementAttributeValue.startsWith(attributeValue)) { return true; } } return false; } static ApkManifestData? parseFromXmlDump(String data, Logger logger) { if (data.trim().isEmpty) { return null; } final List<String> lines = data.split('\n'); assert(lines.length > 3); final int manifestLine = lines.indexWhere((String line) => line.contains('E: manifest')); final _Element manifest = _Element.fromLine(lines[manifestLine], null); _Element currentElement = manifest; for (final String line in lines.skip(manifestLine)) { final String trimLine = line.trimLeft(); final int level = line.length - trimLine.length; // Handle level out while (currentElement.parent != null && level <= currentElement.level) { currentElement = currentElement.parent!; } if (level > currentElement.level) { switch (trimLine[0]) { case 'A': currentElement .addChild(_Attribute.fromLine(line, currentElement)); case 'E': final _Element element = _Element.fromLine(line, currentElement); currentElement.addChild(element); currentElement = element; } } } final _Element? application = manifest.firstElement('application'); if (application == null) { return null; } final Iterable<_Element> activities = application.allElements('activity'); _Element? launchActivity; for (final _Element activity in activities) { final _Attribute? enabled = activity.firstAttribute('android:enabled'); final Iterable<_Element> intentFilters = activity.allElements('intent-filter'); final bool isEnabledByDefault = enabled == null; final bool isExplicitlyEnabled = enabled != null && (enabled.value?.contains('0xffffffff') ?? false); if (!(isEnabledByDefault || isExplicitlyEnabled)) { continue; } for (final _Element element in intentFilters) { final bool isMainAction = _isAttributeWithValuePresent( element, 'action', 'android:name', '"android.intent.action.MAIN"'); if (!isMainAction) { continue; } final bool isLauncherCategory = _isAttributeWithValuePresent( element, 'category', 'android:name', '"android.intent.category.LAUNCHER"'); if (!isLauncherCategory) { continue; } launchActivity = activity; break; } if (launchActivity != null) { break; } } final _Attribute? package = manifest.firstAttribute('package'); // "io.flutter.examples.hello_world" (Raw: "io.flutter.examples.hello_world") final String? packageName = package?.value?.substring(1, package.value?.indexOf('" ')); if (launchActivity == null) { logger.printError('Error running $packageName. Default activity not found'); return null; } final _Attribute? nameAttribute = launchActivity.firstAttribute('android:name'); // "io.flutter.examples.hello_world.MainActivity" (Raw: "io.flutter.examples.hello_world.MainActivity") final String? activityName = nameAttribute?.value?.substring(1, nameAttribute.value?.indexOf('" ')); // Example format: (type 0x10)0x1 final _Attribute? versionCodeAttr = manifest.firstAttribute('android:versionCode'); if (versionCodeAttr == null) { logger.printError('Error running $packageName. Manifest versionCode not found'); return null; } if (versionCodeAttr.value?.startsWith('(type 0x10)') != true) { logger.printError('Error running $packageName. Manifest versionCode invalid'); return null; } final int? versionCode = versionCodeAttr.value == null ? null : int.tryParse(versionCodeAttr.value!.substring(11)); if (versionCode == null) { logger.printError('Error running $packageName. Manifest versionCode invalid'); return null; } final Map<String, Map<String, String>> map = <String, Map<String, String>>{ if (packageName != null) 'package': <String, String>{'name': packageName}, 'version-code': <String, String>{'name': versionCode.toString()}, if (activityName != null) 'launchable-activity': <String, String>{'name': activityName}, }; return ApkManifestData._(map); } final Map<String, Map<String, String>> _data; @visibleForTesting Map<String, Map<String, String>> get data => UnmodifiableMapView<String, Map<String, String>>(_data); String? get packageName => _data['package'] == null ? null : _data['package']?['name']; String? get versionCode => _data['version-code'] == null ? null : _data['version-code']?['name']; String? get launchableActivityName { return _data['launchable-activity'] == null ? null : _data['launchable-activity']?['name']; } @override String toString() => _data.toString(); }
flutter/packages/flutter_tools/lib/src/android/application_package.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/application_package.dart", "repo_id": "flutter", "token_count": 5446 }
738
// 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'; /// Runs [fn] with special handling of asynchronous errors. /// /// If the execution of [fn] does not throw a synchronous exception, and if the /// [Future] returned by [fn] is completed with a value, then the [Future] /// returned by [asyncGuard] is completed with that value if it has not already /// been completed with an error. /// /// If the execution of [fn] throws a synchronous exception, and no [onError] /// callback is provided, then the [Future] returned by [asyncGuard] is /// completed with an error whose object and stack trace are given by the /// synchronous exception. If an [onError] callback is provided, then the /// [Future] returned by [asyncGuard] is completed with its result when passed /// the error object and stack trace. /// /// If the execution of [fn] results in an asynchronous exception that would /// otherwise be unhandled, and no [onError] callback is provided, then the /// [Future] returned by [asyncGuard] is completed with an error whose object /// and stack trace are given by the asynchronous exception. If an [onError] /// callback is provided, then the [Future] returned by [asyncGuard] is /// completed with its result when passed the error object and stack trace. /// /// After the returned [Future] is completed, whether it be with a value or an /// error, all further errors resulting from the execution of [fn] are ignored. /// /// Rationale: /// /// Consider the following snippet: /// ``` /// try { /// await foo(); /// ... /// } catch (e) { /// ... /// } /// ``` /// If the [Future] returned by `foo` is completed with an error, that error is /// handled by the catch block. However, if `foo` spawns an asynchronous /// operation whose errors are unhandled, those errors will not be caught by /// the catch block, and will instead propagate to the containing [Zone]. This /// behavior is non-intuitive to programmers expecting the `catch` to catch all /// the errors resulting from the code under the `try`. /// /// As such, it would be convenient if the `try {} catch {}` here could handle /// not only errors completing the awaited [Future]s it contains, but also /// any otherwise unhandled asynchronous errors occurring as a result of awaited /// expressions. This is how `await` is often assumed to work, which leads to /// unexpected unhandled exceptions. /// /// [asyncGuard] is intended to wrap awaited expressions occurring in a `try` /// block. The behavior described above gives the behavior that users /// intuitively expect from `await`. Consider the snippet: /// ``` /// try { /// await asyncGuard(() async { /// var c = Completer(); /// c.completeError('Error'); /// }); /// } catch (e) { /// // e is 'Error'; /// } /// ``` /// Without the [asyncGuard] the error 'Error' would be propagated to the /// error handler of the containing [Zone]. With the [asyncGuard], the error /// 'Error' is instead caught by the `catch`. /// /// [asyncGuard] also accepts an [onError] callback for situations in which /// completing the returned [Future] with an error is not appropriate. /// For example, it is not always possible to immediately await the returned /// [Future]. In these cases, an [onError] callback is needed to prevent an /// error from propagating to the containing [Zone]. /// /// [onError] must have type `FutureOr<T> Function(Object error)` or /// `FutureOr<T> Function(Object error, StackTrace stackTrace)` otherwise an /// [ArgumentError] will be thrown synchronously. Future<T> asyncGuard<T>( Future<T> Function() fn, { Function? onError, }) { if (onError != null && onError is! _UnaryOnError<T> && onError is! _BinaryOnError<T>) { throw ArgumentError('onError must be a unary function accepting an Object, ' 'or a binary function accepting an Object and ' 'StackTrace. onError must return a T'); } final Completer<T> completer = Completer<T>(); void handleError(Object e, StackTrace s) { if (completer.isCompleted) { return; } if (onError == null) { completer.completeError(e, s); return; } if (onError is _BinaryOnError<T>) { completer.complete(onError(e, s)); } else if (onError is _UnaryOnError<T>) { completer.complete(onError(e)); } } runZoned<void>(() async { try { final T result = await fn(); if (!completer.isCompleted) { completer.complete(result); } // This catches all exceptions so that they can be propagated to the // caller-supplied error handling or the completer. } catch (e, s) { // ignore: avoid_catches_without_on_clauses, forwards to Future handleError(e, s); } }, onError: (Object e, StackTrace s) { handleError(e, s); }); return completer.future; } typedef _UnaryOnError<T> = FutureOr<T> Function(Object error); typedef _BinaryOnError<T> = FutureOr<T> Function(Object error, StackTrace stackTrace);
flutter/packages/flutter_tools/lib/src/base/async_guard.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/async_guard.dart", "repo_id": "flutter", "token_count": 1539 }
739
// 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:ffi' show Abi; import 'package:archive/archive.dart'; import 'package:file/file.dart'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'common.dart'; import 'file_system.dart'; import 'io.dart'; import 'logger.dart'; import 'platform.dart'; import 'process.dart'; abstract class OperatingSystemUtils { factory OperatingSystemUtils({ required FileSystem fileSystem, required Logger logger, required Platform platform, required ProcessManager processManager, }) { if (platform.isWindows) { return _WindowsUtils( fileSystem: fileSystem, logger: logger, platform: platform, processManager: processManager, ); } else if (platform.isMacOS) { return _MacOSUtils( fileSystem: fileSystem, logger: logger, platform: platform, processManager: processManager, ); } else if (platform.isLinux) { return _LinuxUtils( fileSystem: fileSystem, logger: logger, platform: platform, processManager: processManager, ); } else { return _PosixUtils( fileSystem: fileSystem, logger: logger, platform: platform, processManager: processManager, ); } } OperatingSystemUtils._private({ required FileSystem fileSystem, required Logger logger, required Platform platform, required ProcessManager processManager, }) : _fileSystem = fileSystem, _logger = logger, _platform = platform, _processManager = processManager, _processUtils = ProcessUtils( logger: logger, processManager: processManager, ); @visibleForTesting static final GZipCodec gzipLevel1 = GZipCodec(level: 1); final FileSystem _fileSystem; final Logger _logger; final Platform _platform; final ProcessManager _processManager; final ProcessUtils _processUtils; /// Make the given file executable. This may be a no-op on some platforms. void makeExecutable(File file); /// Updates the specified file system [entity] to have the file mode /// bits set to the value defined by [mode], which can be specified in octal /// (e.g. `644`) or symbolically (e.g. `u+x`). /// /// On operating systems that do not support file mode bits, this will be a /// no-op. void chmod(FileSystemEntity entity, String mode); /// Return the path (with symlinks resolved) to the given executable, or null /// if `which` was not able to locate the binary. File? which(String execName) { final List<File> result = _which(execName); if (result.isEmpty) { return null; } return result.first; } /// Return a list of all paths to `execName` found on the system. Uses the /// PATH environment variable. List<File> whichAll(String execName) => _which(execName, all: true); /// Return the File representing a new pipe. File makePipe(String path); void unzip(File file, Directory targetDirectory); void unpack(File gzippedTarFile, Directory targetDirectory); /// Compresses a stream using gzip level 1 (faster but larger). Stream<List<int>> gzipLevel1Stream(Stream<List<int>> stream) { return stream.cast<List<int>>().transform<List<int>>(gzipLevel1.encoder); } /// Returns a pretty name string for the current operating system. /// /// If available, the detailed version of the OS is included. String get name { const Map<String, String> osNames = <String, String>{ 'macos': 'Mac OS', 'linux': 'Linux', 'windows': 'Windows', }; final String osName = _platform.operatingSystem; return osNames[osName] ?? osName; } HostPlatform get hostPlatform; List<File> _which(String execName, { bool all = false }); /// Returns the separator between items in the PATH environment variable. String get pathVarSeparator; /// Returns an unused network port. /// /// Returns 0 if an unused port cannot be found. /// /// The port returned by this function may become used before it is bound by /// its intended user. Future<int> findFreePort({bool ipv6 = false}) async { int port = 0; ServerSocket? serverSocket; final InternetAddress loopback = ipv6 ? InternetAddress.loopbackIPv6 : InternetAddress.loopbackIPv4; try { serverSocket = await ServerSocket.bind(loopback, 0); port = serverSocket.port; } on SocketException catch (e) { // If ipv4 loopback bind fails, try ipv6. if (!ipv6) { return findFreePort(ipv6: true); } _logger.printTrace('findFreePort failed: $e'); } on Exception catch (e) { // Failures are signaled by a return value of 0 from this function. _logger.printTrace('findFreePort failed: $e'); } finally { if (serverSocket != null) { await serverSocket.close(); } } return port; } } class _PosixUtils extends OperatingSystemUtils { _PosixUtils({ required super.fileSystem, required super.logger, required super.platform, required super.processManager, }) : super._private(); @override void makeExecutable(File file) { chmod(file, 'a+x'); } @override void chmod(FileSystemEntity entity, String mode) { // Errors here are silently ignored (except when tracing). try { final ProcessResult result = _processManager.runSync( <String>['chmod', mode, entity.path], ); if (result.exitCode != 0) { _logger.printTrace( 'Error trying to run "chmod $mode ${entity.path}":\n' ' exit code: ${result.exitCode}\n' ' stdout: ${result.stdout.toString().trimRight()}\n' ' stderr: ${result.stderr.toString().trimRight()}' ); } } on ProcessException catch (error) { _logger.printTrace( 'Error trying to run "chmod $mode ${entity.path}": $error', ); } } @override List<File> _which(String execName, { bool all = false }) { final List<String> command = <String>[ 'which', if (all) '-a', execName, ]; final ProcessResult result = _processManager.runSync(command); if (result.exitCode != 0) { return const <File>[]; } final String stdout = result.stdout as String; return stdout.trim().split('\n').map<File>( (String path) => _fileSystem.file(path.trim()), ).toList(); } // unzip -o -q zipfile -d dest @override void unzip(File file, Directory targetDirectory) { if (!_processManager.canRun('unzip')) { // unzip is not available. this error message is modeled after the download // error in bin/internal/update_dart_sdk.sh String message = 'Please install unzip.'; if (_platform.isMacOS) { message = 'Consider running "brew install unzip".'; } else if (_platform.isLinux) { message = 'Consider running "sudo apt-get install unzip".'; } throwToolExit( 'Missing "unzip" tool. Unable to extract ${file.path}.\n$message' ); } _processUtils.runSync( <String>['unzip', '-o', '-q', file.path, '-d', targetDirectory.path], throwOnError: true, verboseExceptions: true, ); } // tar -xzf tarball -C dest @override void unpack(File gzippedTarFile, Directory targetDirectory) { _processUtils.runSync( <String>['tar', '-xzf', gzippedTarFile.path, '-C', targetDirectory.path], throwOnError: true, ); } @override File makePipe(String path) { _processUtils.runSync( <String>['mkfifo', path], throwOnError: true, ); return _fileSystem.file(path); } @override String get pathVarSeparator => ':'; HostPlatform? _hostPlatform; @override HostPlatform get hostPlatform { if (_hostPlatform == null) { final RunResult hostPlatformCheck = _processUtils.runSync(<String>['uname', '-m']); // On x64 stdout is "uname -m: x86_64" // On arm64 stdout is "uname -m: aarch64, arm64_v8a" if (hostPlatformCheck.exitCode != 0) { _hostPlatform = HostPlatform.linux_x64; _logger.printError( 'Encountered an error trying to run "uname -m":\n' ' exit code: ${hostPlatformCheck.exitCode}\n' ' stdout: ${hostPlatformCheck.stdout.trimRight()}\n' ' stderr: ${hostPlatformCheck.stderr.trimRight()}\n' 'Assuming host platform is ${getNameForHostPlatform(_hostPlatform!)}.', ); } else if (hostPlatformCheck.stdout.trim().endsWith('x86_64')) { _hostPlatform = HostPlatform.linux_x64; } else { // We default to ARM if it's not x86_64 and we did not get an error. _hostPlatform = HostPlatform.linux_arm64; } } return _hostPlatform!; } } class _LinuxUtils extends _PosixUtils { _LinuxUtils({ required super.fileSystem, required super.logger, required super.platform, required super.processManager, }); String? _name; @override String get name { if (_name == null) { const String prettyNameKey = 'PRETTY_NAME'; // If "/etc/os-release" doesn't exist, fallback to "/usr/lib/os-release". final String osReleasePath = _fileSystem.file('/etc/os-release').existsSync() ? '/etc/os-release' : '/usr/lib/os-release'; String prettyName; String kernelRelease; try { final String osRelease = _fileSystem.file(osReleasePath).readAsStringSync(); prettyName = _getOsReleaseValueForKey(osRelease, prettyNameKey); } on Exception catch (e) { _logger.printTrace('Failed obtaining PRETTY_NAME for Linux: $e'); prettyName = ''; } try { // Split the operating system version which should be formatted as // "Linux kernelRelease build", by spaces. final List<String> osVersionSplit = _platform.operatingSystemVersion.split(' '); if (osVersionSplit.length < 3) { // The operating system version didn't have the expected format. // Initialize as an empty string. kernelRelease = ''; } else { kernelRelease = ' ${osVersionSplit[1]}'; } } on Exception catch (e) { _logger.printTrace('Failed obtaining kernel release for Linux: $e'); kernelRelease = ''; } _name = '${prettyName.isEmpty ? super.name : prettyName}$kernelRelease'; } return _name!; } String _getOsReleaseValueForKey(String osRelease, String key) { final List<String> osReleaseSplit = osRelease.split('\n'); for (String entry in osReleaseSplit) { entry = entry.trim(); final List<String> entryKeyValuePair = entry.split('='); if (entryKeyValuePair[0] == key) { final String value = entryKeyValuePair[1]; // Remove quotes from either end of the value if they exist final String quote = value[0]; if (quote == "'" || quote == '"') { return value.substring(0, value.length - 1).substring(1); } else { return value; } } } return ''; } } class _MacOSUtils extends _PosixUtils { _MacOSUtils({ required super.fileSystem, required super.logger, required super.platform, required super.processManager, }); String? _name; @override String get name { if (_name == null) { final List<RunResult> results = <RunResult>[ _processUtils.runSync(<String>['sw_vers', '-productName']), _processUtils.runSync(<String>['sw_vers', '-productVersion']), _processUtils.runSync(<String>['sw_vers', '-buildVersion']), _processUtils.runSync(<String>['uname', '-m']), ]; if (results.every((RunResult result) => result.exitCode == 0)) { String osName = getNameForHostPlatform(hostPlatform); // If the script is running in Rosetta, "uname -m" will return x86_64. if (hostPlatform == HostPlatform.darwin_arm64 && results[3].stdout.contains('x86_64')) { osName = '$osName (Rosetta)'; } _name = '${results[0].stdout.trim()} ${results[1].stdout.trim()} ${results[2].stdout.trim()} $osName'; } _name ??= super.name; } return _name!; } // On ARM returns arm64, even when this process is running in Rosetta. @override HostPlatform get hostPlatform { if (_hostPlatform == null) { String? sysctlPath; if (which('sysctl') == null) { // Fallback to known install locations. for (final String path in <String>[ '/usr/sbin/sysctl', '/sbin/sysctl', ]) { if (_fileSystem.isFileSync(path)) { sysctlPath = path; } } } else { sysctlPath = 'sysctl'; } if (sysctlPath == null) { throwToolExit('sysctl not found. Try adding it to your PATH environment variable.'); } final RunResult arm64Check = _processUtils.runSync(<String>[sysctlPath, 'hw.optional.arm64']); // On arm64 stdout is "sysctl hw.optional.arm64: 1" // On x86 hw.optional.arm64 is unavailable and exits with 1. if (arm64Check.exitCode == 0 && arm64Check.stdout.trim().endsWith('1')) { _hostPlatform = HostPlatform.darwin_arm64; } else { _hostPlatform = HostPlatform.darwin_x64; } } return _hostPlatform!; } // unzip, then rsync @override void unzip(File file, Directory targetDirectory) { if (!_processManager.canRun('unzip')) { // unzip is not available. this error message is modeled after the download // error in bin/internal/update_dart_sdk.sh throwToolExit('Missing "unzip" tool. Unable to extract ${file.path}.\nConsider running "brew install unzip".'); } if (_processManager.canRun('rsync')) { final Directory tempDirectory = _fileSystem.systemTempDirectory.createTempSync('flutter_${file.basename}.'); try { // Unzip to a temporary directory. _processUtils.runSync( <String>['unzip', '-o', '-q', file.path, '-d', tempDirectory.path], throwOnError: true, verboseExceptions: true, ); for (final FileSystemEntity unzippedFile in tempDirectory.listSync(followLinks: false)) { // rsync --delete the unzipped files so files removed from the archive are also removed from the target. // Add the '-8' parameter to avoid mangling filenames with encodings that do not match the current locale. _processUtils.runSync( <String>['rsync', '-8', '-av', '--delete', unzippedFile.path, targetDirectory.path], throwOnError: true, verboseExceptions: true, ); } } finally { tempDirectory.deleteSync(recursive: true); } } else { // Fall back to just unzipping. _logger.printTrace('Unable to find rsync, falling back to direct unzipping.'); _processUtils.runSync( <String>['unzip', '-o', '-q', file.path, '-d', targetDirectory.path], throwOnError: true, verboseExceptions: true, ); } } } class _WindowsUtils extends OperatingSystemUtils { _WindowsUtils({ required super.fileSystem, required super.logger, required super.platform, required super.processManager, }) : super._private(); HostPlatform? _hostPlatform; @override HostPlatform get hostPlatform { if (_hostPlatform == null) { final Abi abi = Abi.current(); _hostPlatform = (abi == Abi.windowsArm64) ? HostPlatform.windows_arm64 : HostPlatform.windows_x64; } return _hostPlatform!; } @override void makeExecutable(File file) {} @override void chmod(FileSystemEntity entity, String mode) {} @override List<File> _which(String execName, { bool all = false }) { if (!_processManager.canRun('where')) { // `where` could be missing if system32 is not on the PATH. throwToolExit( 'Cannot find the executable for `where`. This can happen if the System32 ' r'folder (e.g. C:\Windows\System32 ) is removed from the PATH environment ' 'variable. Ensure that this is present and then try again after restarting ' 'the terminal and/or IDE.' ); } // `where` always returns all matches, not just the first one. final ProcessResult result = _processManager.runSync(<String>['where', execName]); if (result.exitCode != 0) { return const <File>[]; } final List<String> lines = (result.stdout as String).trim().split('\n'); if (all) { return lines.map<File>((String path) => _fileSystem.file(path.trim())).toList(); } return <File>[_fileSystem.file(lines.first.trim())]; } @override void unzip(File file, Directory targetDirectory) { final Archive archive = ZipDecoder().decodeBytes(file.readAsBytesSync()); _unpackArchive(archive, targetDirectory); } @override void unpack(File gzippedTarFile, Directory targetDirectory) { final Archive archive = TarDecoder().decodeBytes( GZipDecoder().decodeBytes(gzippedTarFile.readAsBytesSync()), ); _unpackArchive(archive, targetDirectory); } void _unpackArchive(Archive archive, Directory targetDirectory) { for (final ArchiveFile archiveFile in archive.files) { // The archive package doesn't correctly set isFile. if (!archiveFile.isFile || archiveFile.name.endsWith('/')) { continue; } final File destFile = _fileSystem.file( _fileSystem.path.canonicalize( _fileSystem.path.join( targetDirectory.path, archiveFile.name, ), ), ); // Validate that the destFile is within the targetDirectory we want to // extract to. // // See https://snyk.io/research/zip-slip-vulnerability for more context. final String destinationFileCanonicalPath = _fileSystem.path.canonicalize( destFile.path, ); final String targetDirectoryCanonicalPath = _fileSystem.path.canonicalize( targetDirectory.path, ); if (!destinationFileCanonicalPath.startsWith(targetDirectoryCanonicalPath)) { throw StateError( 'Tried to extract the file $destinationFileCanonicalPath outside of the ' 'target directory $targetDirectoryCanonicalPath', ); } if (!destFile.parent.existsSync()) { destFile.parent.createSync(recursive: true); } destFile.writeAsBytesSync(archiveFile.content as List<int>); } } @override File makePipe(String path) { throw UnsupportedError('makePipe is not implemented on Windows.'); } String? _name; @override String get name { if (_name == null) { final ProcessResult result = _processManager.runSync( <String>['ver'], runInShell: true); if (result.exitCode == 0) { _name = (result.stdout as String).trim(); } else { _name = super.name; } } return _name!; } @override String get pathVarSeparator => ';'; } /// Find and return the project root directory relative to the specified /// directory or the current working directory if none specified. /// Return null if the project root could not be found /// or if the project root is the flutter repository root. String? findProjectRoot(FileSystem fileSystem, [ String? directory ]) { const String kProjectRootSentinel = 'pubspec.yaml'; directory ??= fileSystem.currentDirectory.path; Directory currentDirectory = fileSystem.directory(directory).absolute; while (true) { if (currentDirectory.childFile(kProjectRootSentinel).existsSync()) { return currentDirectory.path; } if (!currentDirectory.existsSync() || currentDirectory.parent.path == currentDirectory.path) { return null; } currentDirectory = currentDirectory.parent; } } enum HostPlatform { darwin_x64, darwin_arm64, linux_x64, linux_arm64, windows_x64, windows_arm64; String get platformName { return switch (this) { HostPlatform.darwin_x64 => 'x64', HostPlatform.darwin_arm64 => 'arm64', HostPlatform.linux_x64 => 'x64', HostPlatform.linux_arm64 => 'arm64', HostPlatform.windows_x64 => 'x64', HostPlatform.windows_arm64 => 'arm64', }; } } String getNameForHostPlatform(HostPlatform platform) { return switch (platform) { HostPlatform.darwin_x64 => 'darwin-x64', HostPlatform.darwin_arm64 => 'darwin-arm64', HostPlatform.linux_x64 => 'linux-x64', HostPlatform.linux_arm64 => 'linux-arm64', HostPlatform.windows_x64 => 'windows-x64', HostPlatform.windows_arm64 => 'windows-arm64', }; }
flutter/packages/flutter_tools/lib/src/base/os.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/os.dart", "repo_id": "flutter", "token_count": 8032 }
740
// 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/error_handling_io.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; /// A service for creating and parsing [Depfile]s. class DepfileService { DepfileService({ required Logger logger, required FileSystem fileSystem, }) : _logger = logger, _fileSystem = fileSystem; final Logger _logger; final FileSystem _fileSystem; static final RegExp _separatorExpr = RegExp(r'([^\\]) '); static final RegExp _escapeExpr = RegExp(r'\\(.)'); /// Given an [depfile] File, write the depfile contents. /// /// If both [inputs] and [outputs] are empty, ensures the file does not /// exist. This can be overridden with the [writeEmpty] parameter when /// both static and runtime dependencies exist and it is not desired /// to force a rerun due to no depfile. void writeToFile(Depfile depfile, File output, {bool writeEmpty = false}) { if (depfile.inputs.isEmpty && depfile.outputs.isEmpty && !writeEmpty) { ErrorHandlingFileSystem.deleteIfExists(output); return; } final StringBuffer buffer = StringBuffer(); _writeFilesToBuffer(depfile.outputs, buffer); buffer.write(': '); _writeFilesToBuffer(depfile.inputs, buffer); output.writeAsStringSync(buffer.toString()); } /// Parse the depfile contents from [file]. /// /// If the syntax is invalid, returns an empty [Depfile]. Depfile parse(File file) { final String contents = file.readAsStringSync(); final List<String> colonSeparated = contents.split(': '); if (colonSeparated.length != 2) { _logger.printError('Invalid depfile: ${file.path}'); return const Depfile(<File>[], <File>[]); } final List<File> inputs = _processList(colonSeparated[1].trim()); final List<File> outputs = _processList(colonSeparated[0].trim()); return Depfile(inputs, outputs); } /// Parse the output of dart2js's used dependencies. /// /// The [file] contains a list of newline separated file URIs. The output /// file must be manually specified. Depfile parseDart2js(File file, File output) { final List<File> inputs = <File>[]; for (final String rawUri in file.readAsLinesSync()) { if (rawUri.trim().isEmpty) { continue; } final Uri? fileUri = Uri.tryParse(rawUri); if (fileUri == null) { continue; } if (fileUri.scheme != 'file') { continue; } inputs.add(_fileSystem.file(fileUri)); } return Depfile(inputs, <File>[output]); } void _writeFilesToBuffer(List<File> files, StringBuffer buffer) { for (final File outputFile in files) { if (_fileSystem.path.style.separator == r'\') { // backslashes and spaces in a depfile have to be escaped if the // platform separator is a backslash. final String path = outputFile.path .replaceAll(r'\', r'\\') .replaceAll(r' ', r'\ '); buffer.write(' $path'); } else { final String path = outputFile.path .replaceAll(r' ', r'\ '); buffer.write(' $path'); } } } List<File> _processList(String rawText) { return rawText // Put every file on right-hand side on the separate line .replaceAllMapped(_separatorExpr, (Match match) => '${match.group(1)}\n') .split('\n') // Expand escape sequences, so that '\ ', for example,ß becomes ' ' .map<String>((String path) => path.replaceAllMapped(_escapeExpr, (Match match) => match.group(1)!).trim()) .where((String path) => path.isNotEmpty) // The tool doesn't write duplicates to these lists. This call is an attempt to // be resilient to the outputs of other tools which write or user edits to depfiles. .toSet() .map(_fileSystem.file) .toList(); } } /// A class for representing depfile formats. class Depfile { /// Create a [Depfile] from a list of [input] files and [output] files. const Depfile(this.inputs, this.outputs); /// The input files for this depfile. final List<File> inputs; /// The output files for this depfile. final List<File> outputs; }
flutter/packages/flutter_tools/lib/src/build_system/depfile.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/depfile.dart", "repo_id": "flutter", "token_count": 1557 }
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:meta/meta.dart'; import 'package:native_assets_builder/native_assets_builder.dart' hide NativeAssetsBuildRunner; import 'package:package_config/package_config_types.dart'; import '../../android/gradle_utils.dart'; import '../../base/common.dart'; import '../../base/file_system.dart'; import '../../base/platform.dart'; import '../../build_info.dart'; import '../../dart/package_map.dart'; import '../../isolated/native_assets/android/native_assets.dart'; import '../../isolated/native_assets/ios/native_assets.dart'; import '../../isolated/native_assets/linux/native_assets.dart'; import '../../isolated/native_assets/macos/native_assets.dart'; import '../../isolated/native_assets/native_assets.dart'; import '../../isolated/native_assets/windows/native_assets.dart'; import '../../macos/xcode.dart'; import '../build_system.dart'; import '../depfile.dart'; import '../exceptions.dart'; import 'common.dart'; /// Builds the right native assets for a Flutter app. /// /// The build mode and target architecture can be changed from the /// native build project (Xcode etc.), so only `flutter assemble` has the /// information about build-mode and target architecture. /// Invocations of flutter_tools other than `flutter assemble` are dry runs. /// /// This step needs to be consistent with the dry run invocations in `flutter /// run`s so that the kernel mapping of asset id to dylib lines up after hot /// restart. /// /// [KernelSnapshot] depends on this target. We produce a native_assets.yaml /// here, and embed that mapping inside the kernel snapshot. /// /// The build always produces a valid native_assets.yaml and a native_assets.d /// even if there are no native assets. This way the caching logic won't try to /// rebuild. class NativeAssets extends Target { const NativeAssets({ @visibleForTesting NativeAssetsBuildRunner? buildRunner, }) : _buildRunner = buildRunner; final NativeAssetsBuildRunner? _buildRunner; @override Future<void> build(Environment environment) async { final String? nativeAssetsEnvironment = environment.defines[kNativeAssets]; final List<Uri> dependencies; final FileSystem fileSystem = environment.fileSystem; final File nativeAssetsFile = environment.buildDir.childFile('native_assets.yaml'); if (nativeAssetsEnvironment == 'false') { dependencies = <Uri>[]; await writeNativeAssetsYaml(KernelAssets(), environment.buildDir.uri, fileSystem); } else { final String? targetPlatformEnvironment = environment.defines[kTargetPlatform]; if (targetPlatformEnvironment == null) { throw MissingDefineException(kTargetPlatform, name); } final TargetPlatform targetPlatform = getTargetPlatformForName(targetPlatformEnvironment); final Uri projectUri = environment.projectDir.uri; final File packagesFile = fileSystem .directory(projectUri) .childDirectory('.dart_tool') .childFile('package_config.json'); final PackageConfig packageConfig = await loadPackageConfigWithLogging( packagesFile, logger: environment.logger, ); final NativeAssetsBuildRunner buildRunner = _buildRunner ?? NativeAssetsBuildRunnerImpl( projectUri, packageConfig, fileSystem, environment.logger, ); switch (targetPlatform) { case TargetPlatform.ios: dependencies = await _buildIOS( environment, projectUri, fileSystem, buildRunner, ); case TargetPlatform.darwin: dependencies = await _buildMacOS( environment, projectUri, fileSystem, buildRunner, ); case TargetPlatform.linux_arm64: case TargetPlatform.linux_x64: dependencies = await _buildLinux( environment, targetPlatform, projectUri, fileSystem, buildRunner, ); case TargetPlatform.windows_arm64: case TargetPlatform.windows_x64: dependencies = await _buildWindows( environment, targetPlatform, projectUri, fileSystem, buildRunner, ); case TargetPlatform.tester: if (const LocalPlatform().isMacOS) { (_, dependencies) = await buildNativeAssetsMacOS( buildMode: BuildMode.debug, projectUri: projectUri, codesignIdentity: environment.defines[kCodesignIdentity], yamlParentDirectory: environment.buildDir.uri, fileSystem: fileSystem, buildRunner: buildRunner, flutterTester: true, ); } else if (const LocalPlatform().isLinux) { (_, dependencies) = await buildNativeAssetsLinux( buildMode: BuildMode.debug, projectUri: projectUri, yamlParentDirectory: environment.buildDir.uri, fileSystem: fileSystem, buildRunner: buildRunner, flutterTester: true, ); } else if (const LocalPlatform().isWindows) { (_, dependencies) = await buildNativeAssetsWindows( buildMode: BuildMode.debug, projectUri: projectUri, yamlParentDirectory: environment.buildDir.uri, fileSystem: fileSystem, buildRunner: buildRunner, flutterTester: true, ); } else { // TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757 // Write the file we claim to have in the [outputs]. await writeNativeAssetsYaml(KernelAssets(), environment.buildDir.uri, fileSystem); dependencies = <Uri>[]; } case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.android: (_, dependencies) = await _buildAndroid( environment, targetPlatform, projectUri, fileSystem, buildRunner, ); case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.web_javascript: // TODO(dacoharkes): Implement other OSes. https://github.com/flutter/flutter/issues/129757 // Write the file we claim to have in the [outputs]. await writeNativeAssetsYaml(KernelAssets(), environment.buildDir.uri, fileSystem); dependencies = <Uri>[]; } } final Depfile depfile = Depfile( <File>[ for (final Uri dependency in dependencies) fileSystem.file(dependency), ], <File>[ nativeAssetsFile, ], ); final File outputDepfile = environment.buildDir.childFile('native_assets.d'); if (!outputDepfile.parent.existsSync()) { outputDepfile.parent.createSync(recursive: true); } environment.depFileService.writeToFile(depfile, outputDepfile); if (!await nativeAssetsFile.exists()) { throwToolExit("${nativeAssetsFile.path} doesn't exist."); } if (!await outputDepfile.exists()) { throwToolExit("${outputDepfile.path} doesn't exist."); } } Future<List<Uri>> _buildWindows( Environment environment, TargetPlatform targetPlatform, Uri projectUri, FileSystem fileSystem, NativeAssetsBuildRunner buildRunner, ) async { final String? environmentBuildMode = environment.defines[kBuildMode]; if (environmentBuildMode == null) { throw MissingDefineException(kBuildMode, name); } final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode); final (_, List<Uri> dependencies) = await buildNativeAssetsWindows( targetPlatform: targetPlatform, buildMode: buildMode, projectUri: projectUri, yamlParentDirectory: environment.buildDir.uri, fileSystem: fileSystem, buildRunner: buildRunner, ); return dependencies; } Future<List<Uri>> _buildLinux( Environment environment, TargetPlatform targetPlatform, Uri projectUri, FileSystem fileSystem, NativeAssetsBuildRunner buildRunner, ) async { final String? environmentBuildMode = environment.defines[kBuildMode]; if (environmentBuildMode == null) { throw MissingDefineException(kBuildMode, name); } final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode); final (_, List<Uri> dependencies) = await buildNativeAssetsLinux( targetPlatform: targetPlatform, buildMode: buildMode, projectUri: projectUri, yamlParentDirectory: environment.buildDir.uri, fileSystem: fileSystem, buildRunner: buildRunner, ); return dependencies; } Future<List<Uri>> _buildMacOS( Environment environment, Uri projectUri, FileSystem fileSystem, NativeAssetsBuildRunner buildRunner, ) async { final List<DarwinArch> darwinArchs = _emptyToNull(environment.defines[kDarwinArchs]) ?.split(' ') .map(getDarwinArchForName) .toList() ?? <DarwinArch>[DarwinArch.x86_64, DarwinArch.arm64]; final String? environmentBuildMode = environment.defines[kBuildMode]; if (environmentBuildMode == null) { throw MissingDefineException(kBuildMode, name); } final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode); final (_, List<Uri> dependencies) = await buildNativeAssetsMacOS( darwinArchs: darwinArchs, buildMode: buildMode, projectUri: projectUri, codesignIdentity: environment.defines[kCodesignIdentity], yamlParentDirectory: environment.buildDir.uri, fileSystem: fileSystem, buildRunner: buildRunner, ); return dependencies; } Future<List<Uri>> _buildIOS( Environment environment, Uri projectUri, FileSystem fileSystem, NativeAssetsBuildRunner buildRunner, ) { final List<DarwinArch> iosArchs = _emptyToNull(environment.defines[kIosArchs]) ?.split(' ') .map(getIOSArchForName) .toList() ?? <DarwinArch>[DarwinArch.arm64]; final String? environmentBuildMode = environment.defines[kBuildMode]; if (environmentBuildMode == null) { throw MissingDefineException(kBuildMode, name); } final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode); final String? sdkRoot = environment.defines[kSdkRoot]; if (sdkRoot == null) { throw MissingDefineException(kSdkRoot, name); } final EnvironmentType environmentType = environmentTypeFromSdkroot(sdkRoot, environment.fileSystem)!; return buildNativeAssetsIOS( environmentType: environmentType, darwinArchs: iosArchs, buildMode: buildMode, projectUri: projectUri, codesignIdentity: environment.defines[kCodesignIdentity], fileSystem: fileSystem, buildRunner: buildRunner, yamlParentDirectory: environment.buildDir.uri, ); } Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> _buildAndroid( Environment environment, TargetPlatform targetPlatform, Uri projectUri, FileSystem fileSystem, NativeAssetsBuildRunner buildRunner) { final String? androidArchsEnvironment = environment.defines[kAndroidArchs]; final List<AndroidArch> androidArchs = _androidArchs( targetPlatform, androidArchsEnvironment, ); final int targetAndroidNdkApi = int.parse(environment.defines[kMinSdkVersion] ?? minSdkVersion); final String? environmentBuildMode = environment.defines[kBuildMode]; if (environmentBuildMode == null) { throw MissingDefineException(kBuildMode, name); } final BuildMode buildMode = BuildMode.fromCliName(environmentBuildMode); return buildNativeAssetsAndroid( buildMode: buildMode, projectUri: projectUri, yamlParentDirectory: environment.buildDir.uri, fileSystem: fileSystem, buildRunner: buildRunner, androidArchs: androidArchs, targetAndroidNdkApi: targetAndroidNdkApi, ); } List<AndroidArch> _androidArchs( TargetPlatform targetPlatform, String? androidArchsEnvironment, ) { switch (targetPlatform) { case TargetPlatform.android_arm: return <AndroidArch>[AndroidArch.armeabi_v7a]; case TargetPlatform.android_arm64: return <AndroidArch>[AndroidArch.arm64_v8a]; case TargetPlatform.android_x64: return <AndroidArch>[AndroidArch.x86_64]; case TargetPlatform.android_x86: return <AndroidArch>[AndroidArch.x86]; case TargetPlatform.android: if (androidArchsEnvironment == null) { throw MissingDefineException(kAndroidArchs, name); } return androidArchsEnvironment .split(' ') .map(getAndroidArchForName) .toList(); case TargetPlatform.darwin: case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.ios: case TargetPlatform.linux_arm64: case TargetPlatform.linux_x64: case TargetPlatform.tester: case TargetPlatform.web_javascript: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: throwToolExit('Unsupported Android target platform: $targetPlatform.'); } } @override List<String> get depfiles => <String>[ 'native_assets.d', ]; @override List<Target> get dependencies => <Target>[]; @override List<Source> get inputs => const <Source>[ Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart'), // If different packages are resolved, different native assets might need to be built. Source.pattern('{PROJECT_DIR}/.dart_tool/package_config_subset'), ]; @override String get name => 'native_assets'; @override List<Source> get outputs => const <Source>[ Source.pattern('{BUILD_DIR}/native_assets.yaml'), ]; } String? _emptyToNull(String? input) { if (input == null || input.isEmpty) { return null; } return input; }
flutter/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/native_assets.dart", "repo_id": "flutter", "token_count": 5601 }
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:args/args.dart'; import 'package:meta/meta.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../build_info.dart'; import '../build_system/build_system.dart'; import '../build_system/depfile.dart'; import '../build_system/targets/android.dart'; import '../build_system/targets/assets.dart'; import '../build_system/targets/common.dart'; import '../build_system/targets/deferred_components.dart'; import '../build_system/targets/ios.dart'; import '../build_system/targets/linux.dart'; import '../build_system/targets/macos.dart'; import '../build_system/targets/windows.dart'; import '../cache.dart'; import '../convert.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; /// All currently implemented targets. List<Target> _kDefaultTargets = <Target>[ // Shared targets const CopyAssets(), const KernelSnapshot(), const AotElfProfile(TargetPlatform.android_arm), const AotElfRelease(TargetPlatform.android_arm), const AotAssemblyProfile(), const AotAssemblyRelease(), // macOS targets const DebugMacOSFramework(), const DebugMacOSBundleFlutterAssets(), const ProfileMacOSBundleFlutterAssets(), const ReleaseMacOSBundleFlutterAssets(), // Linux targets const DebugBundleLinuxAssets(TargetPlatform.linux_x64), const DebugBundleLinuxAssets(TargetPlatform.linux_arm64), const ProfileBundleLinuxAssets(TargetPlatform.linux_x64), const ProfileBundleLinuxAssets(TargetPlatform.linux_arm64), const ReleaseBundleLinuxAssets(TargetPlatform.linux_x64), const ReleaseBundleLinuxAssets(TargetPlatform.linux_arm64), const ReleaseAndroidApplication(), // This is a one-off rule for bundle and aot compat. const CopyFlutterBundle(), // Android targets, const DebugAndroidApplication(), const ProfileAndroidApplication(), // Android ABI specific AOT rules. androidArmProfileBundle, androidArm64ProfileBundle, androidx64ProfileBundle, androidArmReleaseBundle, androidArm64ReleaseBundle, androidx64ReleaseBundle, // Deferred component enabled AOT rules androidArmProfileDeferredComponentsBundle, androidArm64ProfileDeferredComponentsBundle, androidx64ProfileDeferredComponentsBundle, androidArmReleaseDeferredComponentsBundle, androidArm64ReleaseDeferredComponentsBundle, androidx64ReleaseDeferredComponentsBundle, // iOS targets const DebugIosApplicationBundle(), const ProfileIosApplicationBundle(), const ReleaseIosApplicationBundle(), // Windows targets const UnpackWindows(TargetPlatform.windows_x64), const UnpackWindows(TargetPlatform.windows_arm64), const DebugBundleWindowsAssets(TargetPlatform.windows_x64), const DebugBundleWindowsAssets(TargetPlatform.windows_arm64), const ProfileBundleWindowsAssets(TargetPlatform.windows_x64), const ProfileBundleWindowsAssets(TargetPlatform.windows_arm64), const ReleaseBundleWindowsAssets(TargetPlatform.windows_x64), const ReleaseBundleWindowsAssets(TargetPlatform.windows_arm64), ]; /// Assemble provides a low level API to interact with the flutter tool build /// system. class AssembleCommand extends FlutterCommand { AssembleCommand({ bool verboseHelp = false, required BuildSystem buildSystem }) : _buildSystem = buildSystem { argParser.addMultiOption( 'define', abbr: 'd', valueHelp: 'target=key=value', help: 'Allows passing configuration to a target, as in "--define=target=key=value".', ); argParser.addOption( 'performance-measurement-file', help: 'Output individual target performance to a JSON file.' ); argParser.addMultiOption( 'input', abbr: 'i', help: 'Allows passing additional inputs with "--input=key=value". Unlike ' 'defines, additional inputs do not generate a new configuration; instead ' 'they are treated as dependencies of the targets that use them.' ); argParser.addOption('depfile', help: 'A file path where a depfile will be written. ' 'This contains all build inputs and outputs in a Make-style syntax.' ); argParser.addOption('build-inputs', help: 'A file path where a newline-separated ' 'file containing all inputs used will be written after a build. ' 'This file is not included as a build input or output. This file is not ' 'written if the build fails for any reason.'); argParser.addOption('build-outputs', help: 'A file path where a newline-separated ' 'file containing all outputs created will be written after a build. ' 'This file is not included as a build input or output. This file is not ' 'written if the build fails for any reason.'); argParser.addOption('output', abbr: 'o', help: 'A directory where output ' 'files will be written. Must be either absolute or relative from the ' 'root of the current Flutter project.', ); usesExtraDartFlagOptions(verboseHelp: verboseHelp); usesDartDefineOption(); argParser.addOption( 'resource-pool-size', help: 'The maximum number of concurrent tasks the build system will run.', ); } final BuildSystem _buildSystem; late final FlutterProject _flutterProject = FlutterProject.current(); @override String get description => 'Assemble and build Flutter resources.'; @override String get name => 'assemble'; @override String get category => FlutterCommandCategory.project; @override Future<CustomDimensions> get usageValues async => CustomDimensions( commandBuildBundleTargetPlatform: _environment.defines[kTargetPlatform], commandBuildBundleIsModule: _flutterProject.isModule, ); @override Future<Event> unifiedAnalyticsUsageValues(String commandPath) async => Event.commandUsageValues( workflow: commandPath, commandHasTerminal: hasTerminal, buildBundleTargetPlatform: _environment.defines[kTargetPlatform], buildBundleIsModule: _flutterProject.isModule, ); @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async { final String? platform = _environment.defines[kTargetPlatform]; if (platform == null) { return super.requiredArtifacts; } final TargetPlatform targetPlatform = getTargetPlatformForName(platform); final DevelopmentArtifact? artifact = artifactFromTargetPlatform(targetPlatform); if (artifact != null) { return <DevelopmentArtifact>{artifact}; } return super.requiredArtifacts; } /// The target(s) we are building. List<Target> createTargets() { final ArgResults argumentResults = argResults!; if (argumentResults.rest.isEmpty) { throwToolExit('missing target name for flutter assemble.'); } final String name = argumentResults.rest.first; final Map<String, Target> targetMap = <String, Target>{ for (final Target target in _kDefaultTargets) target.name: target, }; final List<Target> results = <Target>[ for (final String targetName in argumentResults.rest) if (targetMap.containsKey(targetName)) targetMap[targetName]!, ]; if (results.isEmpty) { throwToolExit('No target named "$name" defined.'); } return results; } bool isDeferredComponentsTargets() { for (final String targetName in argResults!.rest) { if (deferredComponentsTargets.contains(targetName)) { return true; } } return false; } bool isDebug() { for (final String targetName in argResults!.rest) { if (targetName.contains('debug')) { return true; } } return false; } late final Environment _environment = _createEnvironment(); /// The environmental configuration for a build invocation. Environment _createEnvironment() { String? output = stringArg('output'); if (output == null) { throwToolExit('--output directory is required for assemble.'); } // If path is relative, make it absolute from flutter project. if (globals.fs.path.isRelative(output)) { output = globals.fs.path.join(_flutterProject.directory.path, output); } final Artifacts artifacts = globals.artifacts!; final Environment result = Environment( outputDir: globals.fs.directory(output), buildDir: _flutterProject.directory .childDirectory('.dart_tool') .childDirectory('flutter_build'), projectDir: _flutterProject.directory, defines: _parseDefines(stringsArg('define')), inputs: _parseDefines(stringsArg('input')), cacheDir: globals.cache.getRoot(), flutterRootDir: globals.fs.directory(Cache.flutterRoot), artifacts: artifacts, fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, analytics: globals.analytics, platform: globals.platform, engineVersion: artifacts.isLocalEngine ? null : globals.flutterVersion.engineRevision, generateDartPluginRegistry: true, ); return result; } Map<String, String> _parseDefines(List<String> values) { final Map<String, String> results = <String, String>{}; for (final String chunk in values) { final int indexEquals = chunk.indexOf('='); if (indexEquals == -1) { throwToolExit('Improperly formatted define flag: $chunk'); } final String key = chunk.substring(0, indexEquals); final String value = chunk.substring(indexEquals + 1); results[key] = value; } final ArgResults argumentResults = argResults!; if (argumentResults.wasParsed(FlutterOptions.kExtraGenSnapshotOptions)) { results[kExtraGenSnapshotOptions] = (argumentResults[FlutterOptions.kExtraGenSnapshotOptions] as List<String>).join(','); } final Map<String, Object?> defineConfigJsonMap = extractDartDefineConfigJsonMap(); final List<String> dartDefines = extractDartDefines(defineConfigJsonMap: defineConfigJsonMap); if (dartDefines.isNotEmpty) { results[kDartDefines] = dartDefines.join(','); } results[kDeferredComponents] = 'false'; if (_flutterProject.manifest.deferredComponents != null && isDeferredComponentsTargets() && !isDebug()) { results[kDeferredComponents] = 'true'; } if (argumentResults.wasParsed(FlutterOptions.kExtraFrontEndOptions)) { results[kExtraFrontEndOptions] = (argumentResults[FlutterOptions.kExtraFrontEndOptions] as List<String>).join(','); } return results; } @override Future<FlutterCommandResult> runCommand() async { final List<Target> targets = createTargets(); final List<Target> nonDeferredTargets = <Target>[]; final List<Target> deferredTargets = <AndroidAotDeferredComponentsBundle>[]; for (final Target target in targets) { if (deferredComponentsTargets.contains(target.name)) { deferredTargets.add(target); } else { nonDeferredTargets.add(target); } } Target? target; List<String> decodedDefines; try { decodedDefines = decodeDartDefines(_environment.defines, kDartDefines); } on FormatException { throwToolExit( 'Error parsing assemble command: your generated configuration may be out of date. ' "Try re-running 'flutter build ios' or the appropriate build command." ); } if (_flutterProject.manifest.deferredComponents != null && decodedDefines.contains('validate-deferred-components=true') && deferredTargets.isNotEmpty && !isDebug()) { // Add deferred components validation target that require loading units. target = DeferredComponentsGenSnapshotValidatorTarget( deferredComponentsDependencies: deferredTargets.cast<AndroidAotDeferredComponentsBundle>(), nonDeferredComponentsDependencies: nonDeferredTargets, title: 'Deferred components gen_snapshot validation', ); } else if (targets.length > 1) { target = CompositeTarget(targets); } else if (targets.isNotEmpty) { target = targets.single; } final ArgResults argumentResults = argResults!; final BuildResult result = await _buildSystem.build( target!, _environment, buildSystemConfig: BuildSystemConfig( resourcePoolSize: argumentResults.wasParsed('resource-pool-size') ? int.tryParse(stringArg('resource-pool-size')!) : null, ), ); if (!result.success) { for (final ExceptionMeasurement measurement in result.exceptions.values) { if (measurement.fatal || globals.logger.isVerbose) { globals.printError('Target ${measurement.target} failed: ${measurement.exception}', stackTrace: globals.logger.isVerbose ? measurement.stackTrace : null, ); } } throwToolExit(''); } globals.printTrace('build succeeded.'); if (argumentResults.wasParsed('build-inputs')) { writeListIfChanged(result.inputFiles, stringArg('build-inputs')!); } if (argumentResults.wasParsed('build-outputs')) { writeListIfChanged(result.outputFiles, stringArg('build-outputs')!); } if (argumentResults.wasParsed('performance-measurement-file')) { final File outFile = globals.fs.file(argumentResults['performance-measurement-file']); writePerformanceData(result.performance.values, outFile); } if (argumentResults.wasParsed('depfile')) { final File depfileFile = globals.fs.file(stringArg('depfile')); final Depfile depfile = Depfile(result.inputFiles, result.outputFiles); _environment.depFileService.writeToFile(depfile, globals.fs.file(depfileFile)); } return FlutterCommandResult.success(); } } @visibleForTesting void writeListIfChanged(List<File> files, String path) { final File file = globals.fs.file(path); final StringBuffer buffer = StringBuffer(); // These files are already sorted. for (final File file in files) { buffer.writeln(file.path); } final String newContents = buffer.toString(); if (!file.existsSync()) { file.writeAsStringSync(newContents); } final String currentContents = file.readAsStringSync(); if (currentContents != newContents) { file.writeAsStringSync(newContents); } } /// Output performance measurement data in [outFile]. @visibleForTesting void writePerformanceData(Iterable<PerformanceMeasurement> measurements, File outFile) { final Map<String, Object> jsonData = <String, Object>{ 'targets': <Object>[ for (final PerformanceMeasurement measurement in measurements) <String, Object>{ 'name': measurement.analyticsName, 'skipped': measurement.skipped, 'succeeded': measurement.succeeded, 'elapsedMilliseconds': measurement.elapsedMilliseconds, }, ], }; if (!outFile.parent.existsSync()) { outFile.parent.createSync(recursive: true); } outFile.writeAsStringSync(json.encode(jsonData)); }
flutter/packages/flutter_tools/lib/src/commands/assemble.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/assemble.dart", "repo_id": "flutter", "token_count": 5201 }
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:meta/meta.dart'; import '../../src/macos/xcode.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../build_info.dart'; import '../globals.dart' as globals; import '../ios/xcodeproj.dart'; import '../project.dart'; import '../runner/flutter_command.dart'; class CleanCommand extends FlutterCommand { CleanCommand({ bool verbose = false, }) : _verbose = verbose { requiresPubspecYaml(); argParser.addOption( 'scheme', help: 'When cleaning Xcode schemes, clean only the specified scheme.', ); } final bool _verbose; @override final String name = 'clean'; @override final String description = 'Delete the build/ and .dart_tool/ directories.'; @override String get category => FlutterCommandCategory.project; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{}; @override Future<FlutterCommandResult> runCommand() async { // Clean Xcode to remove intermediate DerivedData artifacts. // Do this before removing ephemeral directory, which would delete the xcworkspace. final FlutterProject flutterProject = FlutterProject.current(); final Xcode? xcode = globals.xcode; if (xcode != null && xcode.isInstalledAndMeetsVersionCheck) { await _cleanXcode(flutterProject.ios); await _cleanXcode(flutterProject.macos); } final Directory buildDir = globals.fs.directory(getBuildDirectory()); deleteFile(buildDir); deleteFile(flutterProject.dartTool); deleteFile(flutterProject.packagesFile); deleteFile(flutterProject.android.ephemeralDirectory); deleteFile(flutterProject.ios.ephemeralDirectory); deleteFile(flutterProject.ios.ephemeralModuleDirectory); deleteFile(flutterProject.ios.generatedXcodePropertiesFile); deleteFile(flutterProject.ios.generatedEnvironmentVariableExportScript); deleteFile(flutterProject.ios.deprecatedCompiledDartFramework); deleteFile(flutterProject.ios.deprecatedProjectFlutterFramework); deleteFile(flutterProject.ios.flutterPodspec); deleteFile(flutterProject.linux.ephemeralDirectory); deleteFile(flutterProject.macos.ephemeralDirectory); deleteFile(flutterProject.windows.ephemeralDirectory); deleteFile(flutterProject.flutterPluginsDependenciesFile); deleteFile(flutterProject.flutterPluginsFile); return const FlutterCommandResult(ExitStatus.success); } Future<void> _cleanXcode(XcodeBasedProject xcodeProject) async { final Directory? xcodeWorkspace = xcodeProject.xcodeWorkspace; if (xcodeWorkspace == null) { return; } final Status xcodeStatus = globals.logger.startProgress( 'Cleaning Xcode workspace...', ); try { final XcodeProjectInterpreter xcodeProjectInterpreter = globals.xcodeProjectInterpreter!; final XcodeProjectInfo projectInfo = (await xcodeProjectInterpreter.getInfo(xcodeWorkspace.parent.path))!; if (argResults?.wasParsed('scheme') ?? false) { final String scheme = argResults!['scheme'] as String; if (scheme.isEmpty) { throwToolExit('No scheme was specified for --scheme'); } if (!projectInfo.schemes.contains(scheme)) { throwToolExit('Scheme "$scheme" not found in ${projectInfo.schemes}'); } await xcodeProjectInterpreter.cleanWorkspace(xcodeWorkspace.path, scheme, verbose: _verbose); } else { for (final String scheme in projectInfo.schemes) { await xcodeProjectInterpreter.cleanWorkspace(xcodeWorkspace.path, scheme, verbose: _verbose); } } } on Exception catch (error) { final String message = 'Could not clean Xcode workspace: $error'; if (argResults?.wasParsed('scheme') ?? false) { throwToolExit(message); } else { globals.printTrace(message); } } finally { xcodeStatus.stop(); } } @visibleForTesting void deleteFile(FileSystemEntity file) { // This will throw a FileSystemException if the directory is missing permissions. try { if (!file.existsSync()) { return; } } on FileSystemException catch (err) { globals.printError('Cannot clean ${file.path}.\n$err'); return; } final Status deletionStatus = globals.logger.startProgress( 'Deleting ${file.basename}...', ); try { file.deleteSync(recursive: true); } on FileSystemException catch (error) { final String path = file.path; if (globals.platform.isWindows) { globals.printError('Failed to remove $path. ' 'A program may still be using a file in the directory or the directory itself. ' 'To find and stop such a program, see: ' 'https://superuser.com/questions/1333118/cant-delete-empty-folder-because-it-is-used'); } else { globals.printError('Failed to remove $path: $error'); } } finally { deletionStatus.stop(); } } }
flutter/packages/flutter_tools/lib/src/commands/clean.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/clean.dart", "repo_id": "flutter", "token_count": 1864 }
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 '../base/logger.dart'; import '../convert.dart'; import '../ios/xcodeproj.dart'; import '../project.dart'; /// The type of analysis to perform. enum IOSAnalyzeOption { /// Prints out available build variants of the iOS Xcode sub-project. /// /// An example output: /// /// {"configurations":["Debug","Release","Profile"],"targets":["Runner","RunnerTests"]} listBuildOptions, /// Outputs universal link settings of the iOS Xcode sub-project into a file. /// /// The file path will be printed after the command is run successfully. outputUniversalLinkSettings, } /// Analyze the iOS Xcode sub-project of a Flutter project. /// /// The [userPath] must be point to a flutter project. class IOSAnalyze { IOSAnalyze({ required this.project, required this.option, this.configuration, this.target, required this.logger, }) : assert(option == IOSAnalyzeOption.listBuildOptions || (configuration != null && target != null)); final FlutterProject project; final IOSAnalyzeOption option; final String? configuration; final String? target; final Logger logger; Future<void> analyze() async { switch (option) { case IOSAnalyzeOption.listBuildOptions: final XcodeProjectInfo? info = await project.ios.projectInfo(); final Map<String, List<String>> result; if (info == null) { result = const <String, List<String>>{}; } else { result = <String, List<String>>{ 'configurations': info.buildConfigurations, 'targets': info.targets, }; } logger.printStatus(jsonEncode(result)); case IOSAnalyzeOption.outputUniversalLinkSettings: final String filePath = await project.ios.outputsUniversalLinkSettings( configuration: configuration!, target: target!, ); logger.printStatus('result saved in $filePath'); } } }
flutter/packages/flutter_tools/lib/src/commands/ios_analyze.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/ios_analyze.dart", "repo_id": "flutter", "token_count": 741 }
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 'dart:async'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../application_package.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../bundle.dart'; import '../bundle_builder.dart'; import '../convert.dart'; import '../device.dart'; import '../device_port_forwarder.dart'; import '../features.dart'; import '../project.dart'; import '../protocol_discovery.dart'; import 'custom_device_config.dart'; import 'custom_device_workflow.dart'; import 'custom_devices_config.dart'; /// Replace all occurrences of `${someName}` with the value found for that /// name inside replacementValues or additionalReplacementValues. /// /// The replacement value is first looked for in [replacementValues] and then /// [additionalReplacementValues]. If no value is found, an empty string will be /// substituted instead. List<String> interpolateCommand( List<String> command, Map<String, String> replacementValues, { Map<String, String> additionalReplacementValues = const <String, String>{} }) { return interpolateStringList( command, Map<String, String>.of(additionalReplacementValues) ..addAll(replacementValues) ); } /// A log reader that can listen to a process' stdout / stderr or another log line /// Stream. class CustomDeviceLogReader extends DeviceLogReader { CustomDeviceLogReader(this.name); /// The name of the device this log reader is associated with. @override final String name; @visibleForTesting final StreamController<String> logLinesController = StreamController<String>.broadcast(); @visibleForTesting final List<StreamSubscription<String>> subscriptions = <StreamSubscription<String>>[]; /// Listen to [process]' stdout and stderr, decode them using [SystemEncoding] /// and add each decoded line to [logLines]. /// /// However, [logLines] will not be done when the [process]' stdout and stderr /// streams are done. So [logLines] will still be alive after the process has /// finished. /// /// See [CustomDeviceLogReader.dispose] to end the [logLines] stream. void listenToProcessOutput(Process process, {Encoding encoding = systemEncoding}) { final Converter<List<int>, String> decoder = encoding.decoder; subscriptions.add( process.stdout.transform<String>(decoder) .transform<String>(const LineSplitter()) .listen(logLinesController.add), ); subscriptions.add( process.stderr.transform<String>(decoder) .transform<String>(const LineSplitter()) .listen(logLinesController.add) ); } /// Add all lines emitted by [lines] to this [CustomDeviceLogReader]s [logLines] /// stream. /// /// Similar to [listenToProcessOutput], [logLines] will not be marked as done /// when the argument stream is done. /// /// Useful when you want to combine the contents of multiple log readers. void listenToLinesStream(Stream<String> lines) { subscriptions.add( lines.listen(logLinesController.add) ); } /// Dispose this log reader, freeing all associated resources and marking /// [logLines] as done. @override Future<void> dispose() async { final List<Future<void>> futures = <Future<void>>[]; for (final StreamSubscription<String> subscription in subscriptions) { futures.add(subscription.cancel()); } futures.add(logLinesController.close()); await Future.wait(futures); } @override Stream<String> get logLines => logLinesController.stream; } /// A [DevicePortForwarder] that uses commands to forward / unforward a port. class CustomDevicePortForwarder extends DevicePortForwarder { CustomDevicePortForwarder({ required String deviceName, required List<String> forwardPortCommand, required RegExp forwardPortSuccessRegex, this.numTries, required ProcessManager processManager, required Logger logger, Map<String, String> additionalReplacementValues = const <String, String>{} }) : _deviceName = deviceName, _forwardPortCommand = forwardPortCommand, _forwardPortSuccessRegex = forwardPortSuccessRegex, _processManager = processManager, _processUtils = ProcessUtils( processManager: processManager, logger: logger ), _additionalReplacementValues = additionalReplacementValues; final String _deviceName; final List<String> _forwardPortCommand; final RegExp _forwardPortSuccessRegex; final ProcessManager _processManager; final ProcessUtils _processUtils; final int? numTries; final Map<String, String> _additionalReplacementValues; final List<ForwardedPort> _forwardedPorts = <ForwardedPort>[]; @override Future<void> dispose() async { // copy the list so we don't modify it concurrently await Future.wait(List<ForwardedPort>.of(_forwardedPorts).map(unforward)); } Future<ForwardedPort?> tryForward(int devicePort, int hostPort) async { final List<String> interpolated = interpolateCommand( _forwardPortCommand, <String, String>{ 'devicePort': '$devicePort', 'hostPort': '$hostPort', }, additionalReplacementValues: _additionalReplacementValues ); // launch the forwarding command final Process process = await _processUtils.start(interpolated); final Completer<ForwardedPort?> completer = Completer<ForwardedPort?>(); // Read the outputs of the process; if we find a line that matches // the configs forwardPortSuccessRegex, we complete with a successfully // forwarded port. // If that regex never matches, this will potentially run forever // and the forwarding will never complete. final CustomDeviceLogReader reader = CustomDeviceLogReader(_deviceName)..listenToProcessOutput(process); final StreamSubscription<String> logLinesSubscription = reader.logLines.listen((String line) { if (_forwardPortSuccessRegex.hasMatch(line) && !completer.isCompleted) { completer.complete( ForwardedPort.withContext(hostPort, devicePort, process) ); } }); // if the process exits (even with exitCode == 0), that is considered // a port forwarding failure and we complete with a null value. unawaited(process.exitCode.whenComplete(() { if (!completer.isCompleted) { completer.complete(); } })); unawaited(completer.future.whenComplete(() { unawaited(logLinesSubscription.cancel()); unawaited(reader.dispose()); })); return completer.future; } @override Future<int> forward(int devicePort, {int? hostPort}) async { int actualHostPort = (hostPort == 0 || hostPort == null) ? devicePort : hostPort; int tries = 0; while ((numTries == null) || (tries < numTries!)) { // when the desired host port is already forwarded by this Forwarder, // choose another one while (_forwardedPorts.any((ForwardedPort port) => port.hostPort == actualHostPort)) { actualHostPort += 1; } final ForwardedPort? port = await tryForward(devicePort, actualHostPort); if (port != null) { _forwardedPorts.add(port); return actualHostPort; } else { // null value means the forwarding failed (for whatever reason) // increase port by one and try again actualHostPort += 1; tries += 1; } } throw ToolExit('Forwarding port for custom device $_deviceName failed after $tries tries.'); } @override List<ForwardedPort> get forwardedPorts => List<ForwardedPort>.unmodifiable(_forwardedPorts); @override Future<void> unforward(ForwardedPort forwardedPort) async { assert(_forwardedPorts.contains(forwardedPort)); // since a forwarded port represents a running process launched with // the forwardPortCommand, unforwarding is as easy as killing the process final int? pid = forwardedPort.context?.pid; if (pid != null) { _processManager.killPid(pid); } _forwardedPorts.remove(forwardedPort); } } /// A combination of [ApplicationPackage] and a [CustomDevice]. Can only start, /// stop this specific app package with this specific device. Useful because we /// often need to store additional context to an app that is running on a device, /// like any forwarded ports we need to unforward later, the process we need to /// kill to stop the app, maybe other things in the future. class CustomDeviceAppSession { CustomDeviceAppSession({ required this.name, required CustomDevice device, required ApplicationPackage appPackage, required Logger logger, required ProcessManager processManager }) : _appPackage = appPackage, _device = device, _logger = logger, _processManager = processManager, _processUtils = ProcessUtils( processManager: processManager, logger: logger ), logReader = CustomDeviceLogReader(name); final String name; final CustomDevice _device; final ApplicationPackage _appPackage; final Logger _logger; final ProcessManager _processManager; final ProcessUtils _processUtils; final CustomDeviceLogReader logReader; Process? _process; int? _forwardedHostPort; /// Get the engine options for the given [debuggingOptions], /// [traceStartup] and [route]. /// /// [debuggingOptions] and [route] can be null. /// /// For example, `_getEngineOptions(null, false, null)` will return /// `['enable-dart-profiling=true']` List<String> _getEngineOptions(DebuggingOptions debuggingOptions, bool traceStartup, String? route) { final String dartVmFlags = computeDartVmFlags(debuggingOptions); return <String>[ if (traceStartup) 'trace-startup=true', if (route != null) 'route=$route', if (debuggingOptions.enableDartProfiling) 'enable-dart-profiling=true', if (debuggingOptions.enableSoftwareRendering) 'enable-software-rendering=true', if (debuggingOptions.skiaDeterministicRendering) 'skia-deterministic-rendering=true', if (debuggingOptions.traceSkia) 'trace-skia=true', if (debuggingOptions.traceAllowlist != null) 'trace-allowlist=${debuggingOptions.traceAllowlist}', if (debuggingOptions.traceSystrace) 'trace-systrace=true', if (debuggingOptions.traceToFile != null) 'trace-to-file=${debuggingOptions.traceToFile}', if (debuggingOptions.endlessTraceBuffer) 'endless-trace-buffer=true', if (debuggingOptions.dumpSkpOnShaderCompilation) 'dump-skp-on-shader-compilation=true', if (debuggingOptions.cacheSkSL) 'cache-sksl=true', if (debuggingOptions.purgePersistentCache) 'purge-persistent-cache=true', if (debuggingOptions.debuggingEnabled) ...<String>[ if (debuggingOptions.deviceVmServicePort != null) 'vm-service-port=${debuggingOptions.deviceVmServicePort}', if (debuggingOptions.buildInfo.isDebug) ...<String>[ 'enable-checked-mode=true', 'verify-entry-points=true', ], if (debuggingOptions.startPaused) 'start-paused=true', if (debuggingOptions.disableServiceAuthCodes) 'disable-service-auth-codes=true', if (dartVmFlags.isNotEmpty) 'dart-flags=$dartVmFlags', if (debuggingOptions.useTestFonts) 'use-test-fonts=true', if (debuggingOptions.verboseSystemLogs) 'verbose-logging=true', ], ]; } /// Get the engine options for the given [debuggingOptions], /// [traceStartup] and [route]. /// /// [debuggingOptions] and [route] can be null. /// /// For example, `_getEngineOptionsForCmdline(null, false, null)` will return /// `--enable-dart-profiling=true` String _getEngineOptionsForCmdline(DebuggingOptions debuggingOptions, bool traceStartup, String? route) { return _getEngineOptions(debuggingOptions, traceStartup, route).map((String e) => '--$e').join(' '); } /// Start the app on the device. /// Needs the app to be installed on the device and not running already. /// /// [mainPath], [route], [debuggingOptions], [platformArgs] and /// [userIdentifier] may be null. /// /// [ipv6] may not be respected since it depends on the device config whether /// it uses ipv6 or ipv4 Future<LaunchResult> start({ String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, Object?> platformArgs = const <String, Object>{}, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier }) async { final bool traceStartup = platformArgs['trace-startup'] as bool? ?? false; final String? packageName = _appPackage.name; if (packageName == null) { throw ToolExit('Could not start app, name for $_appPackage is unknown.'); } final List<String> interpolated = interpolateCommand( _device._config.runDebugCommand, <String, String>{ 'remotePath': '/tmp/', 'appName': packageName, 'engineOptions': _getEngineOptionsForCmdline(debuggingOptions, traceStartup, route), } ); final Process process = await _processUtils.start(interpolated); assert(_process == null); _process = process; final ProtocolDiscovery discovery = ProtocolDiscovery.vmService( logReader, portForwarder: _device._config.usesPortForwarding ? _device.portForwarder : null, logger: _logger, ipv6: ipv6, ); // We need to make the discovery listen to the logReader before the logReader // listens to the process output since logReader.lines is a broadcast stream // and events may be discarded. // Whether that actually happens is another thing since this is all executed // in the same microtask AFAICT but this way we're on the safe side. logReader.listenToProcessOutput(process); final Uri? vmServiceUri = await discovery.uri; await discovery.cancel(); if (_device._config.usesPortForwarding) { _forwardedHostPort = vmServiceUri?.port; } return LaunchResult.succeeded(vmServiceUri: vmServiceUri); } void _maybeUnforwardPort() { if (_forwardedHostPort != null) { final ForwardedPort forwardedPort = _device.portForwarder.forwardedPorts.singleWhere((ForwardedPort forwardedPort) { return forwardedPort.hostPort == _forwardedHostPort; }); _forwardedHostPort = null; _device.portForwarder.unforward(forwardedPort); } } /// Stop the app on the device. /// Returns false if the app is not yet running. Also unforwards any /// forwarded ports. Future<bool> stop() async { if (_process == null) { return false; } _maybeUnforwardPort(); final bool result = _processManager.killPid(_process!.pid); _process = null; return result; } void dispose() { if (_process != null) { _maybeUnforwardPort(); _processManager.killPid(_process!.pid); _process = null; } unawaited(logReader.dispose()); } } /// A device that uses user-configured actions for the common device methods. /// The exact actions are defined by the contents of the [CustomDeviceConfig] /// used to construct it. class CustomDevice extends Device { CustomDevice({ required CustomDeviceConfig config, required Logger logger, required ProcessManager processManager, }) : _config = config, _logger = logger, _processManager = processManager, _processUtils = ProcessUtils( processManager: processManager, logger: logger ), _globalLogReader = CustomDeviceLogReader(config.label), portForwarder = config.usesPortForwarding ? CustomDevicePortForwarder( deviceName: config.label, forwardPortCommand: config.forwardPortCommand!, forwardPortSuccessRegex: config.forwardPortSuccessRegex!, processManager: processManager, logger: logger, ) : const NoOpDevicePortForwarder(), super( config.id, category: Category.mobile, ephemeral: true, platformType: PlatformType.custom ); final CustomDeviceConfig _config; final Logger _logger; final ProcessManager _processManager; final ProcessUtils _processUtils; final Map<ApplicationPackage, CustomDeviceAppSession> _sessions = <ApplicationPackage, CustomDeviceAppSession>{}; final CustomDeviceLogReader _globalLogReader; @override final DevicePortForwarder portForwarder; CustomDeviceAppSession _getOrCreateAppSession(ApplicationPackage app) { return _sessions.putIfAbsent( app, () { /// create a new session and add its logging to the global log reader. /// (needed bc it's possible the infra requests a global log in [getLogReader] final CustomDeviceAppSession session = CustomDeviceAppSession( name: name, device: this, appPackage: app, logger: _logger, processManager: _processManager ); _globalLogReader.listenToLinesStream(session.logReader.logLines); return session; } ); } /// Tries to ping the device using the ping command given in the config. /// All string interpolation occurrences inside the ping command will be replaced /// using the entries in [replacementValues]. /// /// If the process finishes with an exit code != 0, false will be returned and /// the error (with the process' stdout and stderr) will be logged using /// [_logger.printError]. /// /// If [timeout] is not null and the process doesn't finish in time, /// it will be killed with a SIGTERM, false will be returned and the timeout /// will be reported in the log using [_logger.printError]. If [timeout] /// is null, it's treated as if it's an infinite timeout. Future<bool> tryPing({ Duration? timeout, Map<String, String> replacementValues = const <String, String>{} }) async { final List<String> interpolated = interpolateCommand( _config.pingCommand, replacementValues ); final RunResult result = await _processUtils.run( interpolated, timeout: timeout ); if (result.exitCode != 0) { return false; } // If the user doesn't configure a ping success regex, any ping with exitCode zero // is good enough. Otherwise we check if either stdout or stderr have a match of // the pingSuccessRegex. final RegExp? pingSuccessRegex = _config.pingSuccessRegex; return pingSuccessRegex == null || pingSuccessRegex.hasMatch(result.stdout) || pingSuccessRegex.hasMatch(result.stderr); } /// Tries to execute the configs postBuild command using [appName] for the /// `${appName}` and [localPath] for the `${localPath}` interpolations, /// any additional string interpolation occurrences will be replaced using the /// entries in [additionalReplacementValues]. /// /// Calling this when the config doesn't have a configured postBuild command /// is an error. /// /// If [timeout] is not null and the process doesn't finish in time, it /// will be killed with a SIGTERM, false will be returned and the timeout /// will be reported in the log using [_logger.printError]. If [timeout] /// is null, it's treated as if it's an infinite timeout. Future<bool> _tryPostBuild({ required String appName, required String localPath, Duration? timeout, Map<String, String> additionalReplacementValues = const <String, String>{} }) async { assert(_config.postBuildCommand != null); final List<String> interpolated = interpolateCommand( _config.postBuildCommand!, <String, String>{ 'appName': appName, 'localPath': localPath, }, additionalReplacementValues: additionalReplacementValues ); try { await _processUtils.run( interpolated, throwOnError: true, timeout: timeout ); return true; } on ProcessException catch (e) { _logger.printError('Error executing postBuild command for custom device $id: $e'); return false; } } /// Tries to execute the configs uninstall command. /// /// [appName] is the name of the app to be installed. /// /// If [timeout] is not null and the process doesn't finish in time, it /// will be killed with a SIGTERM, false will be returned and the timeout /// will be reported in the log using [_logger.printError]. If [timeout] /// is null, it's treated as if it's an infinite timeout. Future<bool> tryUninstall({ required String appName, Duration? timeout, Map<String, String> additionalReplacementValues = const <String, String>{} }) async { final List<String> interpolated = interpolateCommand( _config.uninstallCommand, <String, String>{ 'appName': appName, }, additionalReplacementValues: additionalReplacementValues ); try { await _processUtils.run( interpolated, throwOnError: true, timeout: timeout ); return true; } on ProcessException catch (e) { _logger.printError('Error executing uninstall command for custom device $id: $e'); return false; } } /// Tries to install the app to the custom device. /// /// [localPath] is the file / directory on the local device that will be /// copied over to the target custom device. This is substituted for any occurrence /// of `${localPath}` in the custom device configs `install` command. /// /// [appName] is the name of the app to be installed. Substituted for any occurrence /// of `${appName}` in the custom device configs `install` command. Future<bool> tryInstall({ required String localPath, required String appName, Duration? timeout, Map<String, String> additionalReplacementValues = const <String, String>{} }) async { final List<String> interpolated = interpolateCommand( _config.installCommand, <String, String>{ 'localPath': localPath, 'appName': appName, }, additionalReplacementValues: additionalReplacementValues ); try { await _processUtils.run( interpolated, throwOnError: true, timeout: timeout ); return true; } on ProcessException catch (e) { _logger.printError('Error executing install command for custom device $id: $e'); return false; } } @override void clearLogs() {} @override Future<void> dispose() async { _sessions ..forEach((_, CustomDeviceAppSession session) => session.dispose()) ..clear(); } @override Future<String?> get emulatorId async => null; @override FutureOr<DeviceLogReader> getLogReader({ ApplicationPackage? app, bool includePastLogs = false }) { if (app != null) { return _getOrCreateAppSession(app).logReader; } return _globalLogReader; } @override Future<bool> installApp(ApplicationPackage app, {String? userIdentifier}) async { final String? appName = app.name; if (appName == null || !await tryUninstall(appName: appName)) { return false; } final bool result = await tryInstall( localPath: getAssetBuildDirectory(), appName: appName, ); return result; } @override Future<bool> isAppInstalled(ApplicationPackage app, {String? userIdentifier}) async { return false; } @override Future<bool> isLatestBuildInstalled(ApplicationPackage app) async { return false; } @override Future<bool> get isLocalEmulator async => false; @override bool get supportsScreenshot => _config.supportsScreenshotting; @override Future<void> takeScreenshot(File outputFile) async { if (!supportsScreenshot) { throw UnsupportedError('Screenshotting is not supported for this device.'); } final List<String> interpolated = interpolateCommand( _config.screenshotCommand!, <String, String>{}, ); final RunResult result = await _processUtils.run(interpolated, throwOnError: true); await outputFile.writeAsBytes(base64Decode(result.stdout)); } @override bool isSupported() { return true; } @override bool isSupportedForProject(FlutterProject flutterProject) { return true; } @override FutureOr<bool> supportsRuntimeMode(BuildMode buildMode) { return buildMode == BuildMode.debug; } @override String get name => _config.label; @override Future<String> get sdkNameAndVersion => Future<String>.value(_config.sdkNameAndVersion); @override Future<LaunchResult> startApp( ApplicationPackage package, { String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, Object?> platformArgs = const <String, Object>{}, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, BundleBuilder? bundleBuilder, }) async { if (!prebuiltApplication) { final String assetBundleDir = getAssetBuildDirectory(); bundleBuilder ??= BundleBuilder(); // this just builds the asset bundle, it's the same as `flutter build bundle` await bundleBuilder.build( platform: await targetPlatform, buildInfo: debuggingOptions.buildInfo, mainPath: mainPath, depfilePath: defaultDepfilePath, assetDirPath: assetBundleDir, ); // if we have a post build step (needed for some embedders), execute it if (_config.postBuildCommand != null) { final String? packageName = package.name; if (packageName == null) { throw ToolExit('Could not start app, name for $package is unknown.'); } await _tryPostBuild( appName: packageName, localPath: assetBundleDir, ); } } // install the app on the device // (will invoke the uninstall and then the install command internally) await installApp(package, userIdentifier: userIdentifier); // finally launch the app return _getOrCreateAppSession(package).start( mainPath: mainPath, route: route, debuggingOptions: debuggingOptions, platformArgs: platformArgs, prebuiltApplication: prebuiltApplication, ipv6: ipv6, userIdentifier: userIdentifier, ); } @override Future<bool> stopApp(ApplicationPackage? app, {String? userIdentifier}) async { if (app == null) { return false; } return _getOrCreateAppSession(app).stop(); } @override Future<TargetPlatform> get targetPlatform async => _config.platform ?? TargetPlatform.linux_arm64; @override Future<bool> uninstallApp(ApplicationPackage app, {String? userIdentifier}) async { final String? appName = app.name; if (appName == null) { return false; } return tryUninstall(appName: appName); } } /// A [PollingDeviceDiscovery] that'll try to ping all enabled devices in the argument /// [CustomDevicesConfig] and report the ones that were actually reachable. class CustomDevices extends PollingDeviceDiscovery { /// Create a custom device discovery that pings all enabled devices in the /// given [CustomDevicesConfig]. CustomDevices({ required FeatureFlags featureFlags, required ProcessManager processManager, required Logger logger, required CustomDevicesConfig config }) : _customDeviceWorkflow = CustomDeviceWorkflow( featureFlags: featureFlags, ), _logger = logger, _processManager = processManager, _config = config, super('custom devices'); final CustomDeviceWorkflow _customDeviceWorkflow; final ProcessManager _processManager; final Logger _logger; final CustomDevicesConfig _config; @override bool get supportsPlatform => true; @override bool get canListAnything => _customDeviceWorkflow.canListDevices; CustomDevicesConfig get _customDevicesConfig => _config; List<CustomDevice> get _enabledCustomDevices { return _customDevicesConfig.tryGetDevices() .where((CustomDeviceConfig element) => element.enabled) .map( (CustomDeviceConfig config) => CustomDevice( config: config, logger: _logger, processManager: _processManager ) ).toList(); } @override Future<List<Device>> pollingGetDevices({Duration? timeout}) async { if (!canListAnything) { return const <Device>[]; } final List<CustomDevice> devices = _enabledCustomDevices; // maps any custom device to whether its reachable or not. final Map<CustomDevice, bool> pingedDevices = Map<CustomDevice, bool>.fromIterables( devices, await Future.wait(devices.map((CustomDevice e) => e.tryPing(timeout: timeout))) ); // remove all the devices we couldn't reach. pingedDevices.removeWhere((_, bool value) => !value); // return only the devices. return pingedDevices.keys.toList(); } @override Future<List<String>> getDiagnostics() async => const <String>[]; @override List<String> get wellKnownIds => const <String>[]; }
flutter/packages/flutter_tools/lib/src/custom_devices/custom_device.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/custom_devices/custom_device.dart", "repo_id": "flutter", "token_count": 9962 }
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 'dart:async'; import 'dart:math' as math; import 'package:dds/dap.dart' hide PidTracker; import '../base/io.dart'; import '../cache.dart'; import '../convert.dart'; import 'flutter_adapter_args.dart'; import 'flutter_base_adapter.dart'; /// A DAP Debug Adapter for running and debugging Flutter tests. class FlutterTestDebugAdapter extends FlutterBaseDebugAdapter with TestAdapter { FlutterTestDebugAdapter( super.channel, { required super.fileSystem, required super.platform, super.ipv6, super.enableFlutterDds = true, super.enableAuthCodes, super.logger, super.onError, }); /// Called by [attachRequest] to request that we actually connect to the app to be debugged. @override Future<void> attachImpl() async { sendOutput('console', '\nAttach is not currently supported'); handleSessionTerminate(); } /// Called by [launchRequest] to request that we actually start the tests to be run/debugged. /// /// For debugging, this should start paused, connect to the VM Service, set /// breakpoints, and resume. @override Future<void> launchImpl() async { final FlutterLaunchRequestArguments args = this.args as FlutterLaunchRequestArguments; final bool debug = enableDebugger; final String? program = args.program; final List<String> toolArgs = <String>[ 'test', '--machine', if (!enableFlutterDds) '--no-dds', if (debug) '--start-paused', ]; // Handle customTool and deletion of any arguments for it. final String executable = args.customTool ?? fileSystem.path.join(Cache.flutterRoot!, 'bin', platform.isWindows ? 'flutter.bat' : 'flutter'); final int? removeArgs = args.customToolReplacesArgs; if (args.customTool != null && removeArgs != null) { toolArgs.removeRange(0, math.min(removeArgs, toolArgs.length)); } final List<String> processArgs = <String>[ ...toolArgs, ...?args.toolArgs, if (program != null) program, ...?args.args, ]; await launchAsProcess( executable: executable, processArgs: processArgs, env: args.env, ); // Delay responding until the debugger is connected. if (debug) { await debuggerInitialized; } } /// Called by [terminateRequest] to request that we gracefully shut down the app being run (or in the case of an attach, disconnect). @override Future<void> terminateImpl() async { terminatePids(ProcessSignal.sigterm); await process?.exitCode; } /// Handles the Flutter process exiting, terminating the debug session if it has not already begun terminating. @override void handleExitCode(int code) { final String codeSuffix = code == 0 ? '' : ' ($code)'; logger?.call('Process exited ($code)'); handleSessionTerminate(codeSuffix); } /// Handles incoming JSON events from `flutter test --machine`. bool _handleJsonEvent(String event, Map<String, Object?>? params) { params ??= <String, Object?>{}; switch (event) { case 'test.startedProcess': _handleTestStartedProcess(params); return true; } return false; } @override void handleStderr(List<int> data) { logger?.call('stderr: $data'); sendOutput('stderr', utf8.decode(data)); } /// Handles stdout from the `flutter test --machine` process, decoding the JSON and calling the appropriate handlers. @override void handleStdout(String data) { // Output to stdout from `flutter test --machine` is either: // 1. JSON output from flutter_tools (eg. "test.startedProcess") which is // wrapped in [] brackets and has an event/params. // 2. JSON output from package:test (not wrapped in brackets). // 3. Non-JSON output (user messages, or flutter_tools printing things like // call stacks/error information). logger?.call('stdout: $data'); Object? jsonData; try { jsonData = jsonDecode(data); } on FormatException { // If the output wasn't valid JSON, it was standard stdout that should // be passed through to the user. sendOutput('stdout', data); return; } // Check for valid flutter_tools JSON output (1) first. final Map<String, Object?>? flutterPayload = jsonData is List && jsonData.length == 1 && jsonData.first is Map<String, Object?> ? jsonData.first as Map<String, Object?> : null; final Object? event = flutterPayload?['event']; final Object? params = flutterPayload?['params']; if (event is String && params is Map<String, Object?>?) { _handleJsonEvent(event, params); } else if (jsonData != null) { // Handle package:test output (2). sendTestEvents(jsonData); } else { // Other output should just be passed straight through. sendOutput('stdout', data); } } /// Handles the test.processStarted event from Flutter that provides the VM Service URL. void _handleTestStartedProcess(Map<String, Object?> params) { final String? vmServiceUriString = params['vmServiceUri'] as String?; // For no-debug mode, this event may be still sent so ignore it if we know // we're not debugging, or its URI is null. if (!enableDebugger || vmServiceUriString == null) { return; } final Uri vmServiceUri = Uri.parse(vmServiceUriString); connectDebugger(vmServiceUri); } }
flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_test_adapter.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/debug_adapters/flutter_test_adapter.dart", "repo_id": "flutter", "token_count": 1909 }
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 'package:process/process.dart'; import 'android/android_device_discovery.dart'; import 'android/android_sdk.dart'; import 'android/android_workflow.dart'; import 'artifacts.dart'; import 'base/file_system.dart'; import 'base/os.dart'; import 'base/platform.dart'; import 'base/user_messages.dart'; import 'custom_devices/custom_device.dart'; import 'custom_devices/custom_devices_config.dart'; import 'device.dart'; import 'features.dart'; import 'fuchsia/fuchsia_device.dart'; import 'fuchsia/fuchsia_sdk.dart'; import 'fuchsia/fuchsia_workflow.dart'; import 'ios/devices.dart'; import 'ios/ios_workflow.dart'; import 'ios/simulators.dart'; import 'linux/linux_device.dart'; import 'macos/macos_device.dart'; import 'macos/macos_ipad_device.dart'; import 'macos/macos_workflow.dart'; import 'macos/xcdevice.dart'; import 'preview_device.dart'; import 'tester/flutter_tester.dart'; import 'version.dart'; import 'web/web_device.dart'; import 'windows/windows_device.dart'; import 'windows/windows_workflow.dart'; /// A provider for all of the device discovery instances. class FlutterDeviceManager extends DeviceManager { FlutterDeviceManager({ required super.logger, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required AndroidSdk? androidSdk, required FeatureFlags featureFlags, required IOSSimulatorUtils iosSimulatorUtils, required XCDevice xcDevice, required AndroidWorkflow androidWorkflow, required IOSWorkflow iosWorkflow, required FuchsiaWorkflow fuchsiaWorkflow, required FlutterVersion flutterVersion, required Artifacts artifacts, required MacOSWorkflow macOSWorkflow, required FuchsiaSdk fuchsiaSdk, required UserMessages userMessages, required OperatingSystemUtils operatingSystemUtils, required WindowsWorkflow windowsWorkflow, required CustomDevicesConfig customDevicesConfig, }) : deviceDiscoverers = <DeviceDiscovery>[ AndroidDevices( logger: logger, androidSdk: androidSdk, androidWorkflow: androidWorkflow, processManager: processManager, fileSystem: fileSystem, platform: platform, userMessages: userMessages, ), IOSDevices( platform: platform, xcdevice: xcDevice, iosWorkflow: iosWorkflow, logger: logger, ), IOSSimulators( iosSimulatorUtils: iosSimulatorUtils, ), FuchsiaDevices( fuchsiaSdk: fuchsiaSdk, logger: logger, fuchsiaWorkflow: fuchsiaWorkflow, platform: platform, ), FlutterTesterDevices( fileSystem: fileSystem, flutterVersion: flutterVersion, processManager: processManager, logger: logger, artifacts: artifacts, ), MacOSDevices( processManager: processManager, macOSWorkflow: macOSWorkflow, logger: logger, platform: platform, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ), MacOSDesignedForIPadDevices( processManager: processManager, iosWorkflow: iosWorkflow, logger: logger, platform: platform, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ), PreviewDeviceDiscovery( platform: platform, artifacts: artifacts, fileSystem: fileSystem, logger: logger, processManager: processManager, featureFlags: featureFlags, ), LinuxDevices( platform: platform, featureFlags: featureFlags, processManager: processManager, logger: logger, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ), WindowsDevices( processManager: processManager, operatingSystemUtils: operatingSystemUtils, logger: logger, fileSystem: fileSystem, windowsWorkflow: windowsWorkflow, ), WebDevices( featureFlags: featureFlags, fileSystem: fileSystem, platform: platform, processManager: processManager, logger: logger, ), CustomDevices( featureFlags: featureFlags, processManager: processManager, logger: logger, config: customDevicesConfig ), ]; @override final List<DeviceDiscovery> deviceDiscoverers; }
flutter/packages/flutter_tools/lib/src/flutter_device_manager.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/flutter_device_manager.dart", "repo_id": "flutter", "token_count": 1621 }
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 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/user_messages.dart'; import '../base/version.dart'; import '../convert.dart'; import '../doctor_validator.dart'; import '../ios/plist_parser.dart'; import 'intellij.dart'; const String _ultimateEditionTitle = 'IntelliJ IDEA Ultimate Edition'; const String _ultimateEditionId = 'IntelliJIdea'; const String _communityEditionTitle = 'IntelliJ IDEA Community Edition'; const String _communityEditionId = 'IdeaIC'; /// A doctor validator for both Intellij and Android Studio. abstract class IntelliJValidator extends DoctorValidator { IntelliJValidator(super.title, this.installPath, { required FileSystem fileSystem, required UserMessages userMessages, }) : _fileSystem = fileSystem, _userMessages = userMessages; final String installPath; final FileSystem _fileSystem; final UserMessages _userMessages; String get version; String? get pluginsPath; static const Map<String, String> _idToTitle = <String, String>{ _ultimateEditionId: _ultimateEditionTitle, _communityEditionId: _communityEditionTitle, }; static final Version kMinIdeaVersion = Version(2017, 1, 0); /// Create a [DoctorValidator] for each installation of Intellij. /// /// On platforms other than macOS, Linux, and Windows this returns an /// empty list. static Iterable<DoctorValidator> installedValidators({ required FileSystem fileSystem, required Platform platform, required Logger logger, required UserMessages userMessages, required PlistParser plistParser, required ProcessManager processManager, }) { final FileSystemUtils fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform); if (platform.isWindows) { return IntelliJValidatorOnWindows.installed( fileSystem: fileSystem, fileSystemUtils: fileSystemUtils, platform: platform, userMessages: userMessages, ); } if (platform.isLinux) { return IntelliJValidatorOnLinux.installed( fileSystem: fileSystem, fileSystemUtils: fileSystemUtils, userMessages: userMessages, ); } if (platform.isMacOS) { return IntelliJValidatorOnMac.installed( fileSystem: fileSystem, fileSystemUtils: fileSystemUtils, userMessages: userMessages, plistParser: plistParser, processManager: processManager, logger: logger, ); } return <DoctorValidator>[]; } @override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[]; if (pluginsPath == null) { messages.add(const ValidationMessage.error('Invalid IntelliJ version number.')); } else { messages.add(ValidationMessage(_userMessages.intellijLocation(installPath))); final IntelliJPlugins plugins = IntelliJPlugins(pluginsPath!, fileSystem: _fileSystem); plugins.validatePackage( messages, <String>['flutter-intellij', 'flutter-intellij.jar'], 'Flutter', IntelliJPlugins.kIntellijFlutterPluginUrl, minVersion: IntelliJPlugins.kMinFlutterPluginVersion, ); plugins.validatePackage( messages, <String>['Dart'], 'Dart', IntelliJPlugins.kIntellijDartPluginUrl, ); if (_hasIssues(messages)) { messages.add(ValidationMessage(_userMessages.intellijPluginInfo)); } _validateIntelliJVersion(messages, kMinIdeaVersion); } return ValidationResult( _hasIssues(messages) ? ValidationType.partial : ValidationType.success, messages, statusInfo: _userMessages.intellijStatusInfo(version), ); } bool _hasIssues(List<ValidationMessage> messages) { return messages.any((ValidationMessage message) => message.isError); } void _validateIntelliJVersion(List<ValidationMessage> messages, Version minVersion) { final Version? installedVersion = Version.parse(version); if (installedVersion == null) { return; } if (installedVersion < minVersion) { messages.add(ValidationMessage.error(_userMessages.intellijMinimumVersion(minVersion.toString()))); } } } /// A windows specific implementation of the intellij validator. class IntelliJValidatorOnWindows extends IntelliJValidator { IntelliJValidatorOnWindows(String title, this.version, String installPath, this.pluginsPath, { required FileSystem fileSystem, required UserMessages userMessages, }) : super(title, installPath, fileSystem: fileSystem, userMessages: userMessages); @override final String version; @override final String pluginsPath; static Iterable<DoctorValidator> installed({ required FileSystem fileSystem, required FileSystemUtils fileSystemUtils, required Platform platform, required UserMessages userMessages, }) { final List<DoctorValidator> validators = <DoctorValidator>[]; if (fileSystemUtils.homeDirPath == null) { return validators; } void addValidator(String title, String version, String installPath, String pluginsPath) { final IntelliJValidatorOnWindows validator = IntelliJValidatorOnWindows( title, version, installPath, pluginsPath, fileSystem: fileSystem, userMessages: userMessages, ); for (int index = 0; index < validators.length; index += 1) { final DoctorValidator other = validators[index]; if (other is IntelliJValidatorOnWindows && validator.installPath == other.installPath) { if (validator.version.compareTo(other.version) > 0) { validators[index] = validator; } return; } } validators.add(validator); } // before IntelliJ 2019 final Directory homeDir = fileSystem.directory(fileSystemUtils.homeDirPath); for (final Directory dir in homeDir.listSync().whereType<Directory>()) { final String name = fileSystem.path.basename(dir.path); IntelliJValidator._idToTitle.forEach((String id, String title) { if (name.startsWith('.$id')) { final String version = name.substring(id.length + 1); String? installPath; try { installPath = fileSystem.file(fileSystem.path.join(dir.path, 'system', '.home')).readAsStringSync(); } on FileSystemException { // ignored } if (installPath != null && fileSystem.isDirectorySync(installPath)) { final String pluginsPath = fileSystem.path.join(dir.path, 'config', 'plugins'); addValidator(title, version, installPath, pluginsPath); } } }); } // after IntelliJ 2020 if (!platform.environment.containsKey('LOCALAPPDATA')) { return validators; } final Directory cacheDir = fileSystem.directory(fileSystem.path.join(platform.environment['LOCALAPPDATA']!, 'JetBrains')); if (!cacheDir.existsSync()) { return validators; } for (final Directory dir in cacheDir.listSync().whereType<Directory>()) { final String name = fileSystem.path.basename(dir.path); IntelliJValidator._idToTitle.forEach((String id, String title) { if (name.startsWith(id)) { final String version = name.substring(id.length); String? installPath; try { installPath = fileSystem.file(fileSystem.path.join(dir.path, '.home')).readAsStringSync(); } on FileSystemException { // ignored } if (installPath != null && fileSystem.isDirectorySync(installPath)) { String pluginsPath; if (fileSystem.isDirectorySync('$installPath.plugins')) { // IntelliJ 2020.3 pluginsPath = '$installPath.plugins'; addValidator(title, version, installPath, pluginsPath); } else if (platform.environment.containsKey('APPDATA')) { final String pluginsPathInAppData = fileSystem.path.join( platform.environment['APPDATA']!, 'JetBrains', name, 'plugins'); if (fileSystem.isDirectorySync(pluginsPathInAppData)) { // IntelliJ 2020.1 ~ 2020.2 pluginsPath = pluginsPathInAppData; addValidator(title, version, installPath, pluginsPath); } } } } }); } return validators; } } /// A linux specific implementation of the intellij validator. class IntelliJValidatorOnLinux extends IntelliJValidator { IntelliJValidatorOnLinux(String title, this.version, String installPath, this.pluginsPath, { required FileSystem fileSystem, required UserMessages userMessages, }) : super(title, installPath, fileSystem: fileSystem, userMessages: userMessages); @override final String version; @override final String pluginsPath; static Iterable<DoctorValidator> installed({ required FileSystem fileSystem, required FileSystemUtils fileSystemUtils, required UserMessages userMessages, }) { final List<DoctorValidator> validators = <DoctorValidator>[]; final String? homeDirPath = fileSystemUtils.homeDirPath; if (homeDirPath == null) { return validators; } void addValidator(String title, String version, String installPath, String pluginsPath) { final IntelliJValidatorOnLinux validator = IntelliJValidatorOnLinux( title, version, installPath, pluginsPath, fileSystem: fileSystem, userMessages: userMessages, ); for (int index = 0; index < validators.length; index += 1) { final DoctorValidator other = validators[index]; if (other is IntelliJValidatorOnLinux && validator.installPath == other.installPath) { if (validator.version.compareTo(other.version) > 0) { validators[index] = validator; } return; } } validators.add(validator); } // before IntelliJ 2019 final Directory homeDir = fileSystem.directory(homeDirPath); for (final Directory dir in homeDir.listSync().whereType<Directory>()) { final String name = fileSystem.path.basename(dir.path); IntelliJValidator._idToTitle.forEach((String id, String title) { if (name.startsWith('.$id')) { final String version = name.substring(id.length + 1); String? installPath; try { installPath = fileSystem.file(fileSystem.path.join(dir.path, 'system', '.home')).readAsStringSync(); } on FileSystemException { // ignored } if (installPath != null && fileSystem.isDirectorySync(installPath)) { final String pluginsPath = fileSystem.path.join(dir.path, 'config', 'plugins'); addValidator(title, version, installPath, pluginsPath); } } }); } // after IntelliJ 2020 ~ final Directory cacheDir = fileSystem.directory(fileSystem.path.join(homeDirPath, '.cache', 'JetBrains')); if (!cacheDir.existsSync()) { return validators; } for (final Directory dir in cacheDir.listSync().whereType<Directory>()) { final String name = fileSystem.path.basename(dir.path); IntelliJValidator._idToTitle.forEach((String id, String title) { if (name.startsWith(id)) { final String version = name.substring(id.length); String? installPath; try { installPath = fileSystem.file(fileSystem.path.join(dir.path, '.home')).readAsStringSync(); } on FileSystemException { // ignored } if (installPath != null && fileSystem.isDirectorySync(installPath)) { final String pluginsPathInUserHomeDir = fileSystem.path.join( homeDirPath, '.local', 'share', 'JetBrains', name); if (installPath.contains(fileSystem.path.join('JetBrains','Toolbox','apps'))) { // via JetBrains ToolBox app final String pluginsPathInInstallDir = '$installPath.plugins'; if (fileSystem.isDirectorySync(pluginsPathInUserHomeDir)) { // after 2020.2.x final String pluginsPath = pluginsPathInUserHomeDir; addValidator(title, version, installPath, pluginsPath); } else if (fileSystem.isDirectorySync(pluginsPathInInstallDir)) { // only 2020.1.X final String pluginsPath = pluginsPathInInstallDir; addValidator(title, version, installPath, pluginsPath); } } else { // via tar.gz final String pluginsPath = pluginsPathInUserHomeDir; addValidator(title, version, installPath, pluginsPath); } } } }); } return validators; } } /// A macOS specific implementation of the intellij validator. class IntelliJValidatorOnMac extends IntelliJValidator { IntelliJValidatorOnMac(String title, this.id, String installPath, { required FileSystem fileSystem, required UserMessages userMessages, required PlistParser plistParser, required String? homeDirPath, }) : _plistParser = plistParser, _homeDirPath = homeDirPath, super(title, installPath, fileSystem: fileSystem, userMessages: userMessages); final String id; final PlistParser _plistParser; final String? _homeDirPath; static const Map<String, String> _dirNameToId = <String, String>{ 'IntelliJ IDEA.app': _ultimateEditionId, 'IntelliJ IDEA Ultimate.app': _ultimateEditionId, 'IntelliJ IDEA CE.app': _communityEditionId, 'IntelliJ IDEA Community Edition.app': _communityEditionId, }; static Iterable<DoctorValidator> installed({ required FileSystem fileSystem, required FileSystemUtils fileSystemUtils, required Logger logger, required UserMessages userMessages, required PlistParser plistParser, required ProcessManager processManager, }) { final List<DoctorValidator> validators = <DoctorValidator>[]; final String? homeDirPath = fileSystemUtils.homeDirPath; final List<String> installPaths = <String>[ '/Applications', if (homeDirPath != null) fileSystem.path.join(homeDirPath, 'Applications'), ]; void checkForIntelliJ(Directory dir) { final String name = fileSystem.path.basename(dir.path); _dirNameToId.forEach((String dirName, String id) { if (name == dirName) { assert(IntelliJValidator._idToTitle.containsKey(id)); final String title = IntelliJValidator._idToTitle[id]!; validators.add(IntelliJValidatorOnMac( title, id, dir.path, fileSystem: fileSystem, userMessages: userMessages, plistParser: plistParser, homeDirPath: homeDirPath, )); } }); } try { final Iterable<Directory> installDirs = installPaths .map(fileSystem.directory) .map<List<FileSystemEntity>>((Directory dir) => dir.existsSync() ? dir.listSync() : <FileSystemEntity>[]) .expand<FileSystemEntity>((List<FileSystemEntity> mappedDirs) => mappedDirs) .whereType<Directory>(); for (final Directory dir in installDirs) { checkForIntelliJ(dir); if (!dir.path.endsWith('.app')) { for (final FileSystemEntity subdirectory in dir.listSync()) { if (subdirectory is Directory) { checkForIntelliJ(subdirectory); } } } } // Query Spotlight for unexpected installation locations. String ceSpotlightResult = ''; String ultimateSpotlightResult = ''; try { final ProcessResult ceQueryResult = processManager.runSync(<String>[ 'mdfind', 'kMDItemCFBundleIdentifier="com.jetbrains.intellij.ce"', ]); ceSpotlightResult = ceQueryResult.stdout as String; final ProcessResult ultimateQueryResult = processManager.runSync(<String>[ 'mdfind', 'kMDItemCFBundleIdentifier="com.jetbrains.intellij*"', ]); ultimateSpotlightResult = ultimateQueryResult.stdout as String; } on ProcessException { // The Spotlight query is a nice-to-have, continue checking known installation locations. } for (final String installPath in LineSplitter.split(ceSpotlightResult)) { if (!validators.whereType<IntelliJValidatorOnMac>().any((IntelliJValidatorOnMac e) => e.installPath == installPath)) { validators.add(IntelliJValidatorOnMac( _communityEditionTitle, _communityEditionId, installPath, fileSystem: fileSystem, userMessages: userMessages, plistParser: plistParser, homeDirPath: homeDirPath, )); } } for (final String installPath in LineSplitter.split(ultimateSpotlightResult)) { if (!validators.whereType<IntelliJValidatorOnMac>().any((IntelliJValidatorOnMac e) => e.installPath == installPath)) { validators.add(IntelliJValidatorOnMac( _ultimateEditionTitle, _ultimateEditionId, installPath, fileSystem: fileSystem, userMessages: userMessages, plistParser: plistParser, homeDirPath: homeDirPath, )); } } } on FileSystemException catch (e) { validators.add(ValidatorWithResult( userMessages.intellijMacUnknownResult, ValidationResult(ValidationType.missing, <ValidationMessage>[ ValidationMessage.error(e.message), ]), )); } // Remove JetBrains Toolbox link apps. These tiny apps just // link to the full app, will get detected elsewhere in our search. validators.removeWhere((DoctorValidator validator) { if (validator is! IntelliJValidatorOnMac) { return false; } final String? identifierKey = plistParser.getValueFromFile<String>( validator.plistFile, PlistParser.kCFBundleIdentifierKey, ); if (identifierKey == null) { logger.printTrace('Android Studio/IntelliJ installation at ' '${validator.installPath} has a null CFBundleIdentifierKey, ' 'which is a required field.'); return false; } return identifierKey.contains('com.jetbrains.toolbox.linkapp'); }); return validators; } @visibleForTesting String get plistFile { _plistFile ??= _fileSystem.path.join(installPath, 'Contents', 'Info.plist'); return _plistFile!; } String? _plistFile; @override String get version { return _version ??= _plistParser.getValueFromFile<String>( plistFile, PlistParser.kCFBundleShortVersionStringKey, ) ?? 'unknown'; } String? _version; @override String? get pluginsPath { if (_pluginsPath != null) { return _pluginsPath!; } final String? altLocation = _plistParser .getValueFromFile<String>(plistFile, 'JetBrainsToolboxApp'); if (altLocation != null) { _pluginsPath = '$altLocation.plugins'; return _pluginsPath!; } final List<String> split = version.split('.'); if (split.length < 2) { return null; } final String major = split[0]; final String minor = split[1]; final String? homeDirPath = _homeDirPath; if (homeDirPath != null) { String pluginsPath = _fileSystem.path.join( homeDirPath, 'Library', 'Application Support', 'JetBrains', '$id$major.$minor', 'plugins', ); // Fallback to legacy location from < 2020. if (!_fileSystem.isDirectorySync(pluginsPath)) { pluginsPath = _fileSystem.path.join( homeDirPath, 'Library', 'Application Support', '$id$major.$minor', ); } _pluginsPath = pluginsPath; } return _pluginsPath; } String? _pluginsPath; }
flutter/packages/flutter_tools/lib/src/intellij/intellij_validator.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/intellij/intellij_validator.dart", "repo_id": "flutter", "token_count": 8105 }
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 '../../base/file_system.dart'; import '../../base/project_migrator.dart'; import '../../xcode_project.dart'; // Xcode legacy build system no longer supported by Xcode. // Set in https://github.com/flutter/flutter/pull/21901/. // Removed in https://github.com/flutter/flutter/pull/33684. class XcodeBuildSystemMigration extends ProjectMigrator { XcodeBuildSystemMigration( IosProject project, super.logger, ) : _xcodeWorkspaceSharedSettings = project.xcodeWorkspaceSharedSettings; final File? _xcodeWorkspaceSharedSettings; @override void migrate() { final File? xcodeWorkspaceSharedSettings = _xcodeWorkspaceSharedSettings; if (xcodeWorkspaceSharedSettings == null || !xcodeWorkspaceSharedSettings.existsSync()) { logger.printTrace('Xcode workspace settings not found, skipping build system migration'); return; } final String contents = xcodeWorkspaceSharedSettings.readAsStringSync(); // Only delete this file when it is pointing to the legacy build system. const String legacyBuildSettingsWorkspace = ''' <key>BuildSystemType</key> <string>Original</string>'''; // contains instead of equals to ignore newline file ending variance. if (contents.contains(legacyBuildSettingsWorkspace)) { logger.printStatus('Legacy build system detected, removing ${xcodeWorkspaceSharedSettings.path}'); xcodeWorkspaceSharedSettings.deleteSync(); } } }
flutter/packages/flutter_tools/lib/src/ios/migrations/xcode_build_system_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/migrations/xcode_build_system_migration.dart", "repo_id": "flutter", "token_count": 492 }
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. // Logic for native assets shared between all host OSes. import 'package:logging/logging.dart' as logging; import 'package:native_assets_builder/native_assets_builder.dart' as native_assets_builder show NativeAssetsBuildRunner; import 'package:native_assets_builder/native_assets_builder.dart' hide NativeAssetsBuildRunner; import 'package:native_assets_cli/native_assets_cli_internal.dart'; import 'package:package_config/package_config_types.dart'; import '../../base/common.dart'; import '../../base/file_system.dart'; import '../../base/logger.dart'; import '../../base/platform.dart'; import '../../build_info.dart' as build_info; import '../../cache.dart'; import '../../features.dart'; import '../../globals.dart' as globals; import '../../resident_runner.dart'; import '../../run_hot.dart'; import 'android/native_assets.dart'; import 'ios/native_assets.dart'; import 'linux/native_assets.dart'; import 'macos/native_assets.dart'; import 'macos/native_assets_host.dart'; import 'windows/native_assets.dart'; /// Programmatic API to be used by Dart launchers to invoke native builds. /// /// It enables mocking `package:native_assets_builder` package. /// It also enables mocking native toolchain discovery via [cCompilerConfig]. abstract class NativeAssetsBuildRunner { /// Whether the project has a `.dart_tools/package_config.json`. /// /// If there is no package config, [packagesWithNativeAssets], [build], and /// [dryRun] must not be invoked. Future<bool> hasPackageConfig(); /// All packages in the transitive dependencies that have a `build.dart`. Future<List<Package>> packagesWithNativeAssets(); /// Runs all [packagesWithNativeAssets] `build.dart` in dry run. Future<DryRunResult> dryRun({ required bool includeParentEnvironment, required LinkModePreference linkModePreference, required OS targetOS, required Uri workingDirectory, }); /// Runs all [packagesWithNativeAssets] `build.dart`. Future<BuildResult> build({ required bool includeParentEnvironment, required BuildMode buildMode, required LinkModePreference linkModePreference, required Target target, required Uri workingDirectory, CCompilerConfig? cCompilerConfig, int? targetAndroidNdkApi, IOSSdk? targetIOSSdk, }); /// The C compiler config to use for compilation. Future<CCompilerConfig> get cCompilerConfig; /// The NDK compiler to use to use for compilation for Android. Future<CCompilerConfig> get ndkCCompilerConfig; } /// Uses `package:native_assets_builder` for its implementation. class NativeAssetsBuildRunnerImpl implements NativeAssetsBuildRunner { NativeAssetsBuildRunnerImpl( this.projectUri, this.packageConfig, this.fileSystem, this.logger, ); final Uri projectUri; final PackageConfig packageConfig; final FileSystem fileSystem; final Logger logger; late final logging.Logger _logger = logging.Logger('') ..onRecord.listen((logging.LogRecord record) { final int levelValue = record.level.value; final String message = record.message; if (levelValue >= logging.Level.SEVERE.value) { logger.printError(message); } else if (levelValue >= logging.Level.WARNING.value) { logger.printWarning(message); } else if (levelValue >= logging.Level.INFO.value) { logger.printTrace(message); } else { logger.printTrace(message); } }); late final Uri _dartExecutable = fileSystem.directory(Cache.flutterRoot).uri.resolve('bin/dart'); late final native_assets_builder.NativeAssetsBuildRunner _buildRunner = native_assets_builder.NativeAssetsBuildRunner( logger: _logger, dartExecutable: _dartExecutable, ); @override Future<bool> hasPackageConfig() { final File packageConfigJson = fileSystem.directory(projectUri.toFilePath()).childDirectory('.dart_tool').childFile('package_config.json'); return packageConfigJson.exists(); } @override Future<List<Package>> packagesWithNativeAssets() async { final PackageLayout packageLayout = PackageLayout.fromPackageConfig( packageConfig, projectUri.resolve('.dart_tool/package_config.json'), ); return packageLayout.packagesWithNativeAssets; } @override Future<DryRunResult> dryRun({ required bool includeParentEnvironment, required LinkModePreference linkModePreference, required OS targetOS, required Uri workingDirectory, }) { final PackageLayout packageLayout = PackageLayout.fromPackageConfig( packageConfig, projectUri.resolve('.dart_tool/package_config.json'), ); return _buildRunner.dryRun( includeParentEnvironment: includeParentEnvironment, linkModePreference: linkModePreference, targetOs: targetOS, workingDirectory: workingDirectory, packageLayout: packageLayout, ); } @override Future<BuildResult> build({ required bool includeParentEnvironment, required BuildMode buildMode, required LinkModePreference linkModePreference, required Target target, required Uri workingDirectory, CCompilerConfig? cCompilerConfig, int? targetAndroidNdkApi, IOSSdk? targetIOSSdk, }) { final PackageLayout packageLayout = PackageLayout.fromPackageConfig( packageConfig, projectUri.resolve('.dart_tool/package_config.json'), ); return _buildRunner.build( buildMode: buildMode, cCompilerConfig: cCompilerConfig, includeParentEnvironment: includeParentEnvironment, linkModePreference: linkModePreference, target: target, targetAndroidNdkApi: targetAndroidNdkApi, targetIOSSdk: targetIOSSdk, workingDirectory: workingDirectory, packageLayout: packageLayout, ); } @override late final Future<CCompilerConfig> cCompilerConfig = () { if (globals.platform.isMacOS || globals.platform.isIOS) { return cCompilerConfigMacOS(); } if (globals.platform.isLinux) { return cCompilerConfigLinux(); } if (globals.platform.isWindows) { return cCompilerConfigWindows(); } if (globals.platform.isAndroid) { throwToolExit('Should use ndkCCompilerConfig for Android.'); } throwToolExit('Unknown target OS.'); }(); @override late final Future<CCompilerConfig> ndkCCompilerConfig = () { return cCompilerConfigAndroid(); }(); } /// Write [assets] to `native_assets.yaml` in [yamlParentDirectory]. Future<Uri> writeNativeAssetsYaml( KernelAssets assets, Uri yamlParentDirectory, FileSystem fileSystem, ) async { globals.logger.printTrace('Writing native_assets.yaml.'); final String nativeAssetsDartContents = assets.toNativeAssetsFile(); final Directory parentDirectory = fileSystem.directory(yamlParentDirectory); if (!await parentDirectory.exists()) { await parentDirectory.create(recursive: true); } final File nativeAssetsFile = parentDirectory.childFile('native_assets.yaml'); await nativeAssetsFile.writeAsString(nativeAssetsDartContents); globals.logger.printTrace('Writing ${nativeAssetsFile.path} done.'); return nativeAssetsFile.uri; } /// Select the native asset build mode for a given Flutter build mode. BuildMode nativeAssetsBuildMode(build_info.BuildMode buildMode) { switch (buildMode) { case build_info.BuildMode.debug: return BuildMode.debug; case build_info.BuildMode.jitRelease: case build_info.BuildMode.profile: case build_info.BuildMode.release: return BuildMode.release; } } /// Checks whether this project does not yet have a package config file. /// /// A project has no package config when `pub get` has not yet been run. /// /// Native asset builds cannot be run without a package config. If there is /// no package config, leave a logging trace about that. Future<bool> _hasNoPackageConfig(NativeAssetsBuildRunner buildRunner) async { final bool packageConfigExists = await buildRunner.hasPackageConfig(); if (!packageConfigExists) { globals.logger.printTrace('No package config found. Skipping native assets compilation.'); } return !packageConfigExists; } Future<bool> nativeBuildRequired(NativeAssetsBuildRunner buildRunner) async { if (await _hasNoPackageConfig(buildRunner)) { return false; } final List<Package> packagesWithNativeAssets = await buildRunner.packagesWithNativeAssets(); if (packagesWithNativeAssets.isEmpty) { globals.logger.printTrace( 'No packages with native assets. Skipping native assets compilation.', ); return false; } if (!featureFlags.isNativeAssetsEnabled) { final String packageNames = packagesWithNativeAssets.map((Package p) => p.name).join(' '); throwToolExit( 'Package(s) $packageNames require the native assets feature to be enabled. ' 'Enable using `flutter config --enable-native-assets`.', ); } return true; } /// Ensures that either this project has no native assets, or that native assets /// are supported on that operating system. /// /// Exits the tool if the above condition is not satisfied. Future<void> ensureNoNativeAssetsOrOsIsSupported( Uri workingDirectory, String os, FileSystem fileSystem, NativeAssetsBuildRunner buildRunner, ) async { if (await _hasNoPackageConfig(buildRunner)) { return; } final List<Package> packagesWithNativeAssets = await buildRunner.packagesWithNativeAssets(); if (packagesWithNativeAssets.isEmpty) { globals.logger.printTrace( 'No packages with native assets. Skipping native assets compilation.', ); return; } final String packageNames = packagesWithNativeAssets.map((Package p) => p.name).join(' '); throwToolExit( 'Package(s) $packageNames require the native assets feature. ' 'This feature has not yet been implemented for `$os`. ' 'For more info see https://github.com/flutter/flutter/issues/129757.', ); } /// Ensure all native assets have a linkmode declared to be dynamic loading. /// /// In JIT, the link mode must always be dynamic linking. /// In AOT, the static linking has not yet been implemented in Dart: /// https://github.com/dart-lang/sdk/issues/49418. /// /// Therefore, ensure all `build.dart` scripts return only dynamic libraries. void ensureNoLinkModeStatic(List<Asset> nativeAssets) { final Iterable<Asset> staticAssets = nativeAssets.where((Asset e) => e.linkMode == LinkMode.static); if (staticAssets.isNotEmpty) { final String assetIds = staticAssets.map((Asset a) => a.id).toSet().join(', '); throwToolExit( 'Native asset(s) $assetIds have their link mode set to static, ' 'but this is not yet supported. ' 'For more info see https://github.com/dart-lang/sdk/issues/49418.', ); } } /// This should be the same for different archs, debug/release, etc. /// It should work for all macOS. Uri nativeAssetsBuildUri(Uri projectUri, OS os) { final String buildDir = build_info.getBuildDirectory(); return projectUri.resolve('$buildDir/native_assets/$os/'); } class HotRunnerNativeAssetsBuilderImpl implements HotRunnerNativeAssetsBuilder { const HotRunnerNativeAssetsBuilderImpl(); @override Future<Uri?> dryRun({ required Uri projectUri, required FileSystem fileSystem, required List<FlutterDevice> flutterDevices, required PackageConfig packageConfig, required Logger logger, }) async { final NativeAssetsBuildRunner buildRunner = NativeAssetsBuildRunnerImpl( projectUri, packageConfig, fileSystem, globals.logger, ); return dryRunNativeAssets( projectUri: projectUri, fileSystem: fileSystem, buildRunner: buildRunner, flutterDevices: flutterDevices, ); } } /// Gets the native asset id to dylib mapping to embed in the kernel file. /// /// Run hot compiles a kernel file that is pushed to the device after hot /// restart. We need to embed the native assets mapping in order to access /// native assets after hot restart. Future<Uri?> dryRunNativeAssets({ required Uri projectUri, required FileSystem fileSystem, required NativeAssetsBuildRunner buildRunner, required List<FlutterDevice> flutterDevices, }) async { if (flutterDevices.length != 1) { return dryRunNativeAssetsMultipleOSes( projectUri: projectUri, fileSystem: fileSystem, targetPlatforms: flutterDevices.map((FlutterDevice d) => d.targetPlatform).nonNulls, buildRunner: buildRunner, ); } final FlutterDevice flutterDevice = flutterDevices.single; final build_info.TargetPlatform targetPlatform = flutterDevice.targetPlatform!; final Uri? nativeAssetsYaml; switch (targetPlatform) { case build_info.TargetPlatform.darwin: nativeAssetsYaml = await dryRunNativeAssetsMacOS( projectUri: projectUri, fileSystem: fileSystem, buildRunner: buildRunner, ); case build_info.TargetPlatform.ios: nativeAssetsYaml = await dryRunNativeAssetsIOS( projectUri: projectUri, fileSystem: fileSystem, buildRunner: buildRunner, ); case build_info.TargetPlatform.tester: if (const LocalPlatform().isMacOS) { nativeAssetsYaml = await dryRunNativeAssetsMacOS( projectUri: projectUri, flutterTester: true, fileSystem: fileSystem, buildRunner: buildRunner, ); } else if (const LocalPlatform().isLinux) { nativeAssetsYaml = await dryRunNativeAssetsLinux( projectUri: projectUri, flutterTester: true, fileSystem: fileSystem, buildRunner: buildRunner, ); } else if (const LocalPlatform().isWindows) { nativeAssetsYaml = await dryRunNativeAssetsWindows( projectUri: projectUri, flutterTester: true, fileSystem: fileSystem, buildRunner: buildRunner, ); } else { await nativeBuildRequired(buildRunner); nativeAssetsYaml = null; } case build_info.TargetPlatform.linux_arm64: case build_info.TargetPlatform.linux_x64: nativeAssetsYaml = await dryRunNativeAssetsLinux( projectUri: projectUri, fileSystem: fileSystem, buildRunner: buildRunner, ); case build_info.TargetPlatform.windows_arm64: case build_info.TargetPlatform.windows_x64: nativeAssetsYaml = await dryRunNativeAssetsWindows( projectUri: projectUri, fileSystem: fileSystem, buildRunner: buildRunner, ); case build_info.TargetPlatform.android_arm: case build_info.TargetPlatform.android_arm64: case build_info.TargetPlatform.android_x64: case build_info.TargetPlatform.android_x86: case build_info.TargetPlatform.android: nativeAssetsYaml = await dryRunNativeAssetsAndroid( projectUri: projectUri, fileSystem: fileSystem, buildRunner: buildRunner, ); case build_info.TargetPlatform.fuchsia_arm64: case build_info.TargetPlatform.fuchsia_x64: case build_info.TargetPlatform.web_javascript: await ensureNoNativeAssetsOrOsIsSupported( projectUri, targetPlatform.toString(), fileSystem, buildRunner, ); nativeAssetsYaml = null; } return nativeAssetsYaml; } /// Dry run the native builds for multiple OSes. /// /// Needed for `flutter run -d all`. Future<Uri?> dryRunNativeAssetsMultipleOSes({ required NativeAssetsBuildRunner buildRunner, required Uri projectUri, required FileSystem fileSystem, required Iterable<build_info.TargetPlatform> targetPlatforms, }) async { if (await nativeBuildRequired(buildRunner)) { return null; } final Uri buildUri = buildUriMultiple(projectUri); final Iterable<KernelAsset> nativeAssetPaths = <KernelAsset>[ if (targetPlatforms.contains(build_info.TargetPlatform.darwin) || (targetPlatforms.contains(build_info.TargetPlatform.tester) && OS.current == OS.macOS)) ...await dryRunNativeAssetsMacOSInternal( fileSystem, projectUri, false, buildRunner, ), if (targetPlatforms.contains(build_info.TargetPlatform.linux_arm64) || targetPlatforms.contains(build_info.TargetPlatform.linux_x64) || (targetPlatforms.contains(build_info.TargetPlatform.tester) && OS.current == OS.linux)) ...await dryRunNativeAssetsLinuxInternal( fileSystem, projectUri, false, buildRunner, ), if (targetPlatforms.contains(build_info.TargetPlatform.windows_arm64) || targetPlatforms.contains(build_info.TargetPlatform.windows_x64) || (targetPlatforms.contains(build_info.TargetPlatform.tester) && OS.current == OS.windows)) ...await dryRunNativeAssetsWindowsInternal( fileSystem, projectUri, false, buildRunner, ), if (targetPlatforms.contains(build_info.TargetPlatform.ios)) ...await dryRunNativeAssetsIOSInternal( fileSystem, projectUri, buildRunner, ), if (targetPlatforms.contains(build_info.TargetPlatform.android) || targetPlatforms.contains(build_info.TargetPlatform.android_arm) || targetPlatforms.contains(build_info.TargetPlatform.android_arm64) || targetPlatforms.contains(build_info.TargetPlatform.android_x64) || targetPlatforms.contains(build_info.TargetPlatform.android_x86)) ...await dryRunNativeAssetsAndroidInternal( fileSystem, projectUri, buildRunner, ), ]; final Uri nativeAssetsUri = await writeNativeAssetsYaml( KernelAssets(nativeAssetPaths), buildUri, fileSystem, ); return nativeAssetsUri; } /// With `flutter run -d all` we need a place to store the native assets /// mapping for multiple OSes combined. Uri buildUriMultiple(Uri projectUri) { final String buildDir = build_info.getBuildDirectory(); return projectUri.resolve('$buildDir/native_assets/multiple/'); } /// Dry run the native builds. /// /// This does not build native assets, it only simulates what the final paths /// of all assets will be so that this can be embedded in the kernel file. Future<Uri?> dryRunNativeAssetsSingleArchitecture({ required NativeAssetsBuildRunner buildRunner, required Uri projectUri, bool flutterTester = false, required FileSystem fileSystem, required OS os, }) async { if (!await nativeBuildRequired(buildRunner)) { return null; } final Uri buildUri = nativeAssetsBuildUri(projectUri, os); final Iterable<KernelAsset> nativeAssetPaths = await dryRunNativeAssetsSingleArchitectureInternal( fileSystem, projectUri, flutterTester, buildRunner, os, ); final Uri nativeAssetsUri = await writeNativeAssetsYaml( KernelAssets(nativeAssetPaths.toList()), buildUri, fileSystem, ); return nativeAssetsUri; } Future<Iterable<KernelAsset>> dryRunNativeAssetsSingleArchitectureInternal( FileSystem fileSystem, Uri projectUri, bool flutterTester, NativeAssetsBuildRunner buildRunner, OS targetOS, ) async { final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); globals.logger.printTrace('Dry running native assets for $targetOS.'); final DryRunResult dryRunResult = await buildRunner.dryRun( linkModePreference: LinkModePreference.dynamic, targetOS: targetOS, workingDirectory: projectUri, includeParentEnvironment: true, ); ensureNativeAssetsBuildSucceed(dryRunResult); final List<Asset> nativeAssets = dryRunResult.assets; ensureNoLinkModeStatic(nativeAssets); globals.logger.printTrace('Dry running native assets for $targetOS done.'); final Uri? absolutePath = flutterTester ? buildUri : null; final Map<Asset, KernelAsset> assetTargetLocations = _assetTargetLocationsSingleArchitecture( nativeAssets, absolutePath, ); return assetTargetLocations.values; } /// Builds native assets. /// /// If [targetPlatform] is omitted, the current target architecture is used. /// /// If [flutterTester] is true, absolute paths are emitted in the native /// assets mapping. This can be used for JIT mode without sandbox on the host. /// This is used in `flutter test` and `flutter run -d flutter-tester`. Future<(Uri? nativeAssetsYaml, List<Uri> dependencies)> buildNativeAssetsSingleArchitecture({ required NativeAssetsBuildRunner buildRunner, build_info.TargetPlatform? targetPlatform, required Uri projectUri, required build_info.BuildMode buildMode, bool flutterTester = false, Uri? yamlParentDirectory, required FileSystem fileSystem, }) async { final Target target = targetPlatform != null ? _getNativeTarget(targetPlatform) : Target.current; final OS targetOS = target.os; final Uri buildUri = nativeAssetsBuildUri(projectUri, targetOS); final Directory buildDir = fileSystem.directory(buildUri); if (!await buildDir.exists()) { // CMake requires the folder to exist to do copying. await buildDir.create(recursive: true); } if (!await nativeBuildRequired(buildRunner)) { final Uri nativeAssetsYaml = await writeNativeAssetsYaml( KernelAssets(), yamlParentDirectory ?? buildUri, fileSystem, ); return (nativeAssetsYaml, <Uri>[]); } final BuildMode buildModeCli = nativeAssetsBuildMode(buildMode); globals.logger.printTrace('Building native assets for $target $buildModeCli.'); final BuildResult result = await buildRunner.build( linkModePreference: LinkModePreference.dynamic, target: target, buildMode: buildModeCli, workingDirectory: projectUri, includeParentEnvironment: true, cCompilerConfig: await buildRunner.cCompilerConfig, ); ensureNativeAssetsBuildSucceed(result); final List<Asset> nativeAssets = result.assets; final Set<Uri> dependencies = result.dependencies.toSet(); ensureNoLinkModeStatic(nativeAssets); globals.logger.printTrace('Building native assets for $target done.'); final Uri? absolutePath = flutterTester ? buildUri : null; final Map<Asset, KernelAsset> assetTargetLocations = _assetTargetLocationsSingleArchitecture(nativeAssets, absolutePath); await _copyNativeAssetsSingleArchitecture( buildUri, assetTargetLocations, buildMode, fileSystem, ); final Uri nativeAssetsUri = await writeNativeAssetsYaml( KernelAssets(assetTargetLocations.values.toList()), yamlParentDirectory ?? buildUri, fileSystem, ); return (nativeAssetsUri, dependencies.toList()); } Map<Asset, KernelAsset> _assetTargetLocationsSingleArchitecture( List<Asset> nativeAssets, Uri? absolutePath, ) { return <Asset, KernelAsset>{ for (final Asset asset in nativeAssets) asset: _targetLocationSingleArchitecture( asset, absolutePath, ), }; } KernelAsset _targetLocationSingleArchitecture(Asset asset, Uri? absolutePath) { final AssetPath path = asset.path; final KernelAssetPath kernelAssetPath; switch (path) { case AssetSystemPath _: kernelAssetPath = KernelAssetSystemPath(path.uri); case AssetInExecutable _: kernelAssetPath = KernelAssetInExecutable(); case AssetInProcess _: kernelAssetPath = KernelAssetInProcess(); case AssetAbsolutePath _: final String fileName = path.uri.pathSegments.last; Uri uri; if (absolutePath != null) { // Flutter tester needs full host paths. uri = absolutePath.resolve(fileName); } else { // Flutter Desktop needs "absolute" paths inside the app. // "relative" in the context of native assets would be relative to the // kernel or aot snapshot. uri = Uri(path: fileName); } kernelAssetPath = KernelAssetAbsolutePath(uri); default: throw Exception( 'Unsupported asset path type ${path.runtimeType} in asset $asset', ); } return KernelAsset( id: asset.id, target: asset.target, path: kernelAssetPath, ); } /// Extract the [Target] from a [TargetPlatform]. /// /// Does not cover MacOS, iOS, and Android as these pass the architecture /// in other enums. Target _getNativeTarget(build_info.TargetPlatform targetPlatform) { switch (targetPlatform) { case build_info.TargetPlatform.linux_x64: return Target.linuxX64; case build_info.TargetPlatform.linux_arm64: return Target.linuxArm64; case build_info.TargetPlatform.windows_x64: return Target.windowsX64; case build_info.TargetPlatform.windows_arm64: return Target.windowsArm64; case build_info.TargetPlatform.android: case build_info.TargetPlatform.ios: case build_info.TargetPlatform.darwin: case build_info.TargetPlatform.fuchsia_arm64: case build_info.TargetPlatform.fuchsia_x64: case build_info.TargetPlatform.tester: case build_info.TargetPlatform.web_javascript: case build_info.TargetPlatform.android_arm: case build_info.TargetPlatform.android_arm64: case build_info.TargetPlatform.android_x64: case build_info.TargetPlatform.android_x86: throw Exception('Unknown targetPlatform: $targetPlatform.'); } } Future<void> _copyNativeAssetsSingleArchitecture( Uri buildUri, Map<Asset, KernelAsset> assetTargetLocations, build_info.BuildMode buildMode, FileSystem fileSystem, ) async { if (assetTargetLocations.isNotEmpty) { globals.logger.printTrace('Copying native assets to ${buildUri.toFilePath()}.'); final Directory buildDir = fileSystem.directory(buildUri.toFilePath()); if (!buildDir.existsSync()) { buildDir.createSync(recursive: true); } for (final MapEntry<Asset, KernelAsset> assetMapping in assetTargetLocations.entries) { final Uri source = (assetMapping.key.path as AssetAbsolutePath).uri; final Uri target = (assetMapping.value.path as KernelAssetAbsolutePath).uri; final Uri targetUri = buildUri.resolveUri(target); final String targetFullPath = targetUri.toFilePath(); await fileSystem.file(source).copy(targetFullPath); } globals.logger.printTrace('Copying native assets done.'); } } void ensureNativeAssetsBuildSucceed(DryRunResult result) { if (!result.success) { throwToolExit( 'Building native assets failed. See the logs for more details.', ); } }
flutter/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/isolated/native_assets/native_assets.dart", "repo_id": "flutter", "token_count": 8966 }
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 '../application_package.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../globals.dart' as globals; import '../ios/plist_parser.dart'; import '../xcode_project.dart'; /// Tests whether a [FileSystemEntity] is an macOS bundle directory. bool _isBundleDirectory(FileSystemEntity entity) => entity is Directory && entity.path.endsWith('.app'); abstract class MacOSApp extends ApplicationPackage { MacOSApp({required String projectBundleId}) : super(id: projectBundleId); /// Creates a new [MacOSApp] from a macOS project directory. factory MacOSApp.fromMacOSProject(MacOSProject project) { // projectBundleId is unused for macOS apps. Use a placeholder bundle ID. return BuildableMacOSApp(project, 'com.example.placeholder'); } /// Creates a new [MacOSApp] from an existing app bundle. /// /// `applicationBinary` is the path to the framework directory created by an /// Xcode build. By default, this is located under /// "~/Library/Developer/Xcode/DerivedData/" and contains an executable /// which is expected to start the application and send the vmService /// port over stdout. static MacOSApp? fromPrebuiltApp(FileSystemEntity applicationBinary) { final _BundleInfo? bundleInfo = _executableFromBundle(applicationBinary); if (bundleInfo == null) { return null; } return PrebuiltMacOSApp( uncompressedBundle: bundleInfo.uncompressedBundle, bundleName: bundleInfo.uncompressedBundle.path, projectBundleId: bundleInfo.id, executable: bundleInfo.executable, applicationPackage: applicationBinary, ); } /// Look up the executable name for a macOS application bundle. static _BundleInfo? _executableFromBundle(FileSystemEntity applicationBundle) { final FileSystemEntityType entityType = globals.fs.typeSync(applicationBundle.path); if (entityType == FileSystemEntityType.notFound) { globals.printError('File "${applicationBundle.path}" does not exist.'); return null; } Directory uncompressedBundle; if (entityType == FileSystemEntityType.directory) { final Directory directory = globals.fs.directory(applicationBundle); if (!_isBundleDirectory(directory)) { globals.printError('Folder "${applicationBundle.path}" is not an app bundle.'); return null; } uncompressedBundle = globals.fs.directory(applicationBundle); } else { // Try to unpack as a zip. final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_app.'); try { globals.os.unzip(globals.fs.file(applicationBundle), tempDir); } on ProcessException { globals.printError('Invalid prebuilt macOS app. Unable to extract bundle from archive.'); return null; } try { uncompressedBundle = tempDir .listSync() .whereType<Directory>() .singleWhere(_isBundleDirectory); } on StateError { globals.printError('Archive "${applicationBundle.path}" does not contain a single app bundle.'); return null; } } final String plistPath = globals.fs.path.join(uncompressedBundle.path, 'Contents', 'Info.plist'); if (!globals.fs.file(plistPath).existsSync()) { globals.printError('Invalid prebuilt macOS app. Does not contain Info.plist.'); return null; } final Map<String, dynamic> propertyValues = globals.plistParser.parseFile(plistPath); final String? id = propertyValues[PlistParser.kCFBundleIdentifierKey] as String?; final String? executableName = propertyValues[PlistParser.kCFBundleExecutableKey] as String?; if (id == null) { globals.printError('Invalid prebuilt macOS app. Info.plist does not contain bundle identifier'); return null; } if (executableName == null) { globals.printError('Invalid prebuilt macOS app. Info.plist does not contain bundle executable'); return null; } final String executable = globals.fs.path.join(uncompressedBundle.path, 'Contents', 'MacOS', executableName); if (!globals.fs.file(executable).existsSync()) { globals.printError('Could not find macOS binary at $executable'); } return _BundleInfo(executable, id, uncompressedBundle); } @override String get displayName => id; String? applicationBundle(BuildInfo buildInfo); String? executable(BuildInfo buildInfo); } class PrebuiltMacOSApp extends MacOSApp implements PrebuiltApplicationPackage { PrebuiltMacOSApp({ required this.uncompressedBundle, required this.bundleName, required this.projectBundleId, required String executable, required this.applicationPackage, }) : _executable = executable, super(projectBundleId: projectBundleId); /// The uncompressed bundle of the application. /// /// [MacOSApp.fromPrebuiltApp] will uncompress the application into a temporary /// directory even when an `.zip` file was used to create the [MacOSApp] instance. final Directory uncompressedBundle; final String bundleName; final String projectBundleId; final String _executable; @override String get name => bundleName; @override String? applicationBundle(BuildInfo buildInfo) => uncompressedBundle.path; @override String? executable(BuildInfo buildInfo) => _executable; /// A [File] or [Directory] pointing to the application bundle. /// /// This can be either a `.zip` file or an uncompressed `.app` directory. @override final FileSystemEntity applicationPackage; } class BuildableMacOSApp extends MacOSApp { BuildableMacOSApp(this.project, String projectBundleId): super(projectBundleId: projectBundleId); final MacOSProject project; @override String get name => 'macOS'; @override String? applicationBundle(BuildInfo buildInfo) { final File appBundleNameFile = project.nameFile; if (!appBundleNameFile.existsSync()) { globals.printError('Unable to find app name. ${appBundleNameFile.path} does not exist'); return null; } return globals.fs.path.join( getMacOSBuildDirectory(), 'Build', 'Products', bundleDirectory(buildInfo), appBundleNameFile.readAsStringSync().trim()); } String bundleDirectory(BuildInfo buildInfo) { return sentenceCase(buildInfo.mode.cliName) + (buildInfo.flavor != null ? '-${buildInfo.flavor!}' : ''); } @override String? executable(BuildInfo buildInfo) { final String? directory = applicationBundle(buildInfo); if (directory == null) { return null; } final _BundleInfo? bundleInfo = MacOSApp._executableFromBundle(globals.fs.directory(directory)); return bundleInfo?.executable; } } class _BundleInfo { _BundleInfo(this.executable, this.id, this.uncompressedBundle); final Directory uncompressedBundle; final String executable; final String id; }
flutter/packages/flutter_tools/lib/src/macos/application_package.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/macos/application_package.dart", "repo_id": "flutter", "token_count": 2370 }
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 '../base/file_system.dart'; import '../base/project_migrator.dart'; import '../cmake_project.dart'; /// Adds the snippet to the CMake file that copies the native assets. /// /// ```cmake /// # Copy the native assets provided by the build.dart from all packages. /// set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") /// install(DIRECTORY "${NATIVE_ASSETS_DIR}" /// DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" /// COMPONENT Runtime) /// ``` class CmakeNativeAssetsMigration extends ProjectMigrator { CmakeNativeAssetsMigration(CmakeBasedProject project, this.os, super.logger) : _cmakeFile = project.managedCmakeFile; final File _cmakeFile; final String os; @override void migrate() { if (!_cmakeFile.existsSync()) { logger.printTrace('CMake project not found, skipping install() NATIVE_ASSETS_DIR migration.'); return; } final String originalProjectContents = _cmakeFile.readAsStringSync(); if (originalProjectContents.contains('set(NATIVE_ASSETS_DIR')) { // Command is already present. return; } final String copyNativeAssetsCommand = ''' # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "\${PROJECT_BUILD_DIR}native_assets/$os/") install(DIRECTORY "\${NATIVE_ASSETS_DIR}" DESTINATION "\${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) '''; // Insert the new command after the bundled libraries loop. const String bundleLibrariesCommandEnd = r''' endforeach(bundled_library) '''; String newProjectContents = originalProjectContents; newProjectContents = originalProjectContents.replaceFirst( bundleLibrariesCommandEnd, '$bundleLibrariesCommandEnd$copyNativeAssetsCommand', ); if (originalProjectContents != newProjectContents) { logger.printStatus('CMake missing install() NATIVE_ASSETS_DIR command, updating.'); _cmakeFile.writeAsStringSync(newProjectContents); } } }
flutter/packages/flutter_tools/lib/src/migrations/cmake_native_assets_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/migrations/cmake_native_assets_migration.dart", "repo_id": "flutter", "token_count": 710 }
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 'dart:async'; import 'dart:typed_data'; /// Merges the values in a stream that are sent less than [duration] apart. /// /// To minimize latency, the merged stream will always emit the first value that /// is sent after a pause of at least [duration] long. After the first message, /// all values that are sent within [duration] will be merged into one. Stream<Uint8List> debounceDataStream(Stream<Uint8List> stream, [Duration duration = const Duration(milliseconds: 100)]) { final StreamController<Uint8List> controller = StreamController<Uint8List>(); final BytesBuilder buffer = BytesBuilder(copy: false); bool isDone = false; Timer? timer; // Called when timer triggers, sends out the buffered messages. void onTimer() { if (buffer.isNotEmpty) { controller.add(buffer.toBytes()); buffer.clear(); if (isDone) { controller.close(); } else { // Start another timer even if we have nothing to send right now, so // that outgoing messages are at least [duration] apart. timer = Timer(duration, onTimer); } } else { timer = null; } } controller.onListen = () { final StreamSubscription<Uint8List> subscription = stream.listen((Uint8List data) { if (timer == null) { controller.add(data); // Start the timer to make sure that the next message is at least [duration] apart. timer = Timer(duration, onTimer); } else { buffer.add(data); } }, onError: (Object error, StackTrace stackTrace) { // Forward the error. controller.addError(error, stackTrace); }, onDone: () { isDone = true; // Delay closing the channel if we still have buffered data. if (timer == null) { controller.close(); } }); controller.onCancel = () { subscription.cancel(); }; }; return controller.stream; }
flutter/packages/flutter_tools/lib/src/proxied_devices/debounce_data_stream.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/proxied_devices/debounce_data_stream.dart", "repo_id": "flutter", "token_count": 717 }
754
// 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/logger.dart'; import 'build_info.dart'; import 'globals.dart' as globals; import 'resident_runner.dart'; import 'tracing.dart'; import 'vmservice.dart'; const String kFlutterTestOutputsDirEnvName = 'FLUTTER_TEST_OUTPUTS_DIR'; class ColdRunner extends ResidentRunner { ColdRunner( super.flutterDevices, { required super.target, required super.debuggingOptions, this.traceStartup = false, this.awaitFirstFrameWhenTracing = true, this.applicationBinary, bool super.ipv6 = false, super.stayResident, super.machine, super.devtoolsHandler, }) : super( hotMode: false, ); final bool traceStartup; final bool awaitFirstFrameWhenTracing; final File? applicationBinary; bool _didAttach = false; @override bool get canHotReload => false; @override Logger get logger => globals.logger; @override FileSystem get fileSystem => globals.fs; @override Future<int> run({ Completer<DebugConnectionInfo>? connectionInfoCompleter, Completer<void>? appStartedCompleter, bool enableDevTools = false, String? route, }) async { try { for (final FlutterDevice? device in flutterDevices) { final int result = await device!.runCold( coldRunner: this, route: route, ); if (result != 0) { appFailedToStart(); return result; } } } on Exception catch (err, stack) { globals.printError('$err\n$stack'); appFailedToStart(); return 1; } // Connect to the VM Service. if (debuggingEnabled) { try { await connectToServiceProtocol(allowExistingDdsInstance: false); } on Exception catch (exception) { globals.printError(exception.toString()); appFailedToStart(); return 2; } } if (debuggingEnabled) { if (enableDevTools) { // The method below is guaranteed never to return a failing future. unawaited(residentDevtoolsHandler!.serveAndAnnounceDevTools( devToolsServerAddress: debuggingOptions.devToolsServerAddress, flutterDevices: flutterDevices, isStartPaused: debuggingOptions.startPaused, )); } if (debuggingOptions.serveObservatory) { await enableObservatory(); } } if (flutterDevices.first.vmServiceUris != null) { // For now, only support one debugger connection. connectionInfoCompleter?.complete(DebugConnectionInfo( httpUri: flutterDevices.first.vmService!.httpAddress, wsUri: flutterDevices.first.vmService!.wsAddress, )); } globals.printTrace('Application running.'); for (final FlutterDevice? device in flutterDevices) { if (device!.vmService == null) { continue; } await device.initLogReader(); globals.printTrace('Connected to ${device.device!.name}'); } if (traceStartup) { // Only trace startup for the first device. final FlutterDevice device = flutterDevices.first; if (device.vmService != null) { globals.printStatus('Tracing startup on ${device.device!.name}.'); final String outputPath = globals.platform.environment[kFlutterTestOutputsDirEnvName] ?? getBuildDirectory(); await downloadStartupTrace( device.vmService!, awaitFirstFrame: awaitFirstFrameWhenTracing, logger: globals.logger, output: globals.fs.directory(outputPath), ); } appFinished(); } appStartedCompleter?.complete(); writeVmServiceFile(); if (stayResident && !traceStartup) { return waitForAppToFinish(); } await cleanupAtFinish(); return 0; } @override Future<int> attach({ Completer<DebugConnectionInfo>? connectionInfoCompleter, Completer<void>? appStartedCompleter, bool allowExistingDdsInstance = false, bool enableDevTools = false, bool needsFullRestart = true, }) async { _didAttach = true; try { await connectToServiceProtocol( getSkSLMethod: writeSkSL, allowExistingDdsInstance: allowExistingDdsInstance, ); } on Exception catch (error) { globals.printError('Error connecting to the service protocol: $error'); return 2; } for (final FlutterDevice? device in flutterDevices) { await device!.initLogReader(); } for (final FlutterDevice? device in flutterDevices) { final List<FlutterView> views = await device!.vmService!.getFlutterViews(); for (final FlutterView view in views) { globals.printTrace('Connected to $view.'); } } if (debuggingEnabled) { if (enableDevTools) { // The method below is guaranteed never to return a failing future. unawaited(residentDevtoolsHandler!.serveAndAnnounceDevTools( devToolsServerAddress: debuggingOptions.devToolsServerAddress, flutterDevices: flutterDevices, isStartPaused: debuggingOptions.startPaused, )); } if (debuggingOptions.serveObservatory) { await enableObservatory(); } } appStartedCompleter?.complete(); if (stayResident) { return waitForAppToFinish(); } await cleanupAtFinish(); return 0; } @override Future<void> cleanupAfterSignal() async { await stopEchoingDeviceLog(); if (_didAttach) { appFinished(); } await exitApp(); } @override Future<void> cleanupAtFinish() async { for (final FlutterDevice? flutterDevice in flutterDevices) { await flutterDevice!.device!.dispose(); } await residentDevtoolsHandler!.shutdown(); await stopEchoingDeviceLog(); } @override void printHelp({ required bool details }) { globals.printStatus('Flutter run key commands.'); if (details) { printHelpDetails(); commandHelp.hWithDetails.print(); } else { commandHelp.hWithoutDetails.print(); } if (_didAttach) { commandHelp.d.print(); } commandHelp.c.print(); commandHelp.q.print(); printDebuggerList(); } @override Future<void> preExit() async { for (final FlutterDevice? device in flutterDevices) { // If we're running in release mode, stop the app using the device logic. if (device!.vmService == null) { await device.device!.stopApp(device.package, userIdentifier: device.userIdentifier); } } await super.preExit(); } }
flutter/packages/flutter_tools/lib/src/run_cold.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/run_cold.dart", "repo_id": "flutter", "token_count": 2596 }
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:package_config/package_config.dart'; import '../artifacts.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../build_info.dart'; import '../cache.dart'; import '../compile.dart'; import '../convert.dart'; import '../device.dart'; import '../globals.dart' as globals; import '../native_assets.dart'; import '../project.dart'; import '../web/chrome.dart'; import '../web/memory_fs.dart'; import 'flutter_platform.dart' as loader; import 'flutter_web_platform.dart'; import 'font_config_manager.dart'; import 'test_config.dart'; import 'test_time_recorder.dart'; import 'test_wrapper.dart'; import 'watcher.dart'; import 'web_test_compiler.dart'; /// A class that abstracts launching the test process from the test runner. abstract class FlutterTestRunner { const factory FlutterTestRunner() = _FlutterTestRunnerImpl; /// Runs tests using package:test and the Flutter engine. Future<int> runTests( TestWrapper testWrapper, List<Uri> testFiles, { required DebuggingOptions debuggingOptions, List<String> names = const <String>[], List<String> plainNames = const <String>[], String? tags, String? excludeTags, bool enableVmService = false, bool ipv6 = false, bool machine = false, String? precompiledDillPath, Map<String, String>? precompiledDillFiles, bool updateGoldens = false, TestWatcher? watcher, required int? concurrency, String? testAssetDirectory, FlutterProject? flutterProject, String? icudtlPath, Directory? coverageDirectory, bool web = false, String? randomSeed, String? reporter, String? fileReporter, String? timeout, bool runSkipped = false, int? shardIndex, int? totalShards, Device? integrationTestDevice, String? integrationTestUserIdentifier, TestTimeRecorder? testTimeRecorder, TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }); /// Runs tests using the experimental strategy of spawning each test in a /// separate lightweight Engine. Future<int> runTestsBySpawningLightweightEngines( List<Uri> testFiles, { required DebuggingOptions debuggingOptions, List<String> names = const <String>[], List<String> plainNames = const <String>[], String? tags, String? excludeTags, bool machine = false, bool updateGoldens = false, required int? concurrency, String? testAssetDirectory, FlutterProject? flutterProject, String? icudtlPath, String? randomSeed, String? reporter, String? fileReporter, String? timeout, bool runSkipped = false, int? shardIndex, int? totalShards, TestTimeRecorder? testTimeRecorder, TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }); } class _FlutterTestRunnerImpl implements FlutterTestRunner { const _FlutterTestRunnerImpl(); @override Future<int> runTests( TestWrapper testWrapper, List<Uri> testFiles, { required DebuggingOptions debuggingOptions, List<String> names = const <String>[], List<String> plainNames = const <String>[], String? tags, String? excludeTags, bool enableVmService = false, bool ipv6 = false, bool machine = false, String? precompiledDillPath, Map<String, String>? precompiledDillFiles, bool updateGoldens = false, TestWatcher? watcher, required int? concurrency, String? testAssetDirectory, FlutterProject? flutterProject, String? icudtlPath, Directory? coverageDirectory, bool web = false, String? randomSeed, String? reporter, String? fileReporter, String? timeout, bool runSkipped = false, int? shardIndex, int? totalShards, Device? integrationTestDevice, String? integrationTestUserIdentifier, TestTimeRecorder? testTimeRecorder, TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) async { // Configure package:test to use the Flutter engine for child processes. final String shellPath = globals.artifacts!.getArtifactPath(Artifact.flutterTester); // Compute the command-line arguments for package:test. final List<String> testArgs = <String>[ if (!globals.terminal.supportsColor) '--no-color', if (debuggingOptions.startPaused) '--pause-after-load', if (machine) ...<String>['-r', 'json'] else if (reporter != null) ...<String>['-r', reporter], if (fileReporter != null) '--file-reporter=$fileReporter', if (timeout != null) ...<String>['--timeout', timeout], if (concurrency != null) '--concurrency=$concurrency', for (final String name in names) ...<String>['--name', name], for (final String plainName in plainNames) ...<String>['--plain-name', plainName], if (randomSeed != null) '--test-randomize-ordering-seed=$randomSeed', if (tags != null) ...<String>['--tags', tags], if (excludeTags != null) ...<String>['--exclude-tags', excludeTags], if (runSkipped) '--run-skipped', if (totalShards != null) '--total-shards=$totalShards', if (shardIndex != null) '--shard-index=$shardIndex', '--chain-stack-traces', ]; if (web) { final String tempBuildDir = globals.fs.systemTempDirectory .createTempSync('flutter_test.') .absolute .uri .toFilePath(); final WebMemoryFS result = await WebTestCompiler( logger: globals.logger, fileSystem: globals.fs, platform: globals.platform, artifacts: globals.artifacts!, processManager: globals.processManager, config: globals.config, ).initialize( projectDirectory: flutterProject!.directory, testOutputDir: tempBuildDir, testFiles: testFiles.map((Uri uri) => uri.toFilePath()).toList(), buildInfo: debuggingOptions.buildInfo, webRenderer: debuggingOptions.webRenderer, ); testArgs ..add('--platform=chrome') ..add('--') ..addAll(testFiles.map((Uri uri) => uri.toString())); testWrapper.registerPlatformPlugin( <Runtime>[Runtime.chrome], () { return FlutterWebPlatform.start( flutterProject.directory.path, updateGoldens: updateGoldens, shellPath: shellPath, flutterProject: flutterProject, pauseAfterLoad: debuggingOptions.startPaused, nullAssertions: debuggingOptions.nullAssertions, buildInfo: debuggingOptions.buildInfo, webMemoryFS: result, logger: globals.logger, fileSystem: globals.fs, artifacts: globals.artifacts, processManager: globals.processManager, chromiumLauncher: ChromiumLauncher( fileSystem: globals.fs, platform: globals.platform, processManager: globals.processManager, operatingSystemUtils: globals.os, browserFinder: findChromeExecutable, logger: globals.logger, ), testTimeRecorder: testTimeRecorder, webRenderer: debuggingOptions.webRenderer, ); }, ); await testWrapper.main(testArgs); return exitCode; } testArgs ..add('--') ..addAll(testFiles.map((Uri uri) => uri.toString())); final InternetAddressType serverType = ipv6 ? InternetAddressType.IPv6 : InternetAddressType.IPv4; final loader.FlutterPlatform platform = loader.installHook( testWrapper: testWrapper, shellPath: shellPath, debuggingOptions: debuggingOptions, watcher: watcher, enableVmService: enableVmService, machine: machine, serverType: serverType, precompiledDillPath: precompiledDillPath, precompiledDillFiles: precompiledDillFiles, updateGoldens: updateGoldens, testAssetDirectory: testAssetDirectory, projectRootDirectory: globals.fs.currentDirectory.uri, flutterProject: flutterProject, icudtlPath: icudtlPath, integrationTestDevice: integrationTestDevice, integrationTestUserIdentifier: integrationTestUserIdentifier, testTimeRecorder: testTimeRecorder, nativeAssetsBuilder: nativeAssetsBuilder, ); try { globals.printTrace('running test package with arguments: $testArgs'); await testWrapper.main(testArgs); // test.main() sets dart:io's exitCode global. globals.printTrace('test package returned with exit code $exitCode'); return exitCode; } finally { await platform.close(); } } // To compile root_test_isolate_spawner.dart and // child_test_isolate_spawner.dart successfully, we will need to pass a // package_config.json to the frontend server that contains the // union of package:test_core, package:ffi, and all the dependencies of the // project under test. This function generates such a package_config.json. static Future<void> _generateIsolateSpawningTesterPackageConfig({ required FlutterProject flutterProject, required File isolateSpawningTesterPackageConfigFile, }) async { final File projectPackageConfigFile = globals.fs.directory( flutterProject.directory.path, ).childDirectory('.dart_tool').childFile('package_config.json'); final PackageConfig projectPackageConfig = PackageConfig.parseBytes( projectPackageConfigFile.readAsBytesSync(), projectPackageConfigFile.uri, ); // The flutter_tools package_config.json is guaranteed to include // package:ffi and package:test_core. final File flutterToolsPackageConfigFile = globals.fs.directory( globals.fs.path.join( Cache.flutterRoot!, 'packages', 'flutter_tools', ), ).childDirectory('.dart_tool').childFile('package_config.json'); final PackageConfig flutterToolsPackageConfig = PackageConfig.parseBytes( flutterToolsPackageConfigFile.readAsBytesSync(), flutterToolsPackageConfigFile.uri, ); final List<Package> mergedPackages = <Package>[ ...projectPackageConfig.packages, ]; final Set<String> projectPackageNames = Set<String>.from( mergedPackages.map((Package p) => p.name), ); for (final Package p in flutterToolsPackageConfig.packages) { if (!projectPackageNames.contains(p.name)) { mergedPackages.add(p); } } final PackageConfig mergedPackageConfig = PackageConfig(mergedPackages); final StringBuffer buffer = StringBuffer(); PackageConfig.writeString(mergedPackageConfig, buffer); isolateSpawningTesterPackageConfigFile.writeAsStringSync(buffer.toString()); } static void _generateChildTestIsolateSpawnerSourceFile( List<Uri> paths, { required List<String> packageTestArgs, required bool autoUpdateGoldenFiles, required File childTestIsolateSpawnerSourceFile, required File childTestIsolateSpawnerDillFile, }) { final Map<String, String> testConfigPaths = <String, String>{}; final StringBuffer buffer = StringBuffer(); buffer.writeln(''' import 'dart:ffi'; import 'dart:isolate'; import 'dart:ui'; import 'package:ffi/ffi.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stream_channel/isolate_channel.dart'; import 'package:test_api/backend.dart'; // flutter_ignore: test_api_import '''); String pathToImport(String path) { assert(path.endsWith('.dart')); return path .replaceAll('.', '_') .replaceAll(':', '_') .replaceAll('/', '_') .replaceAll(r'\', '_') .replaceRange(path.length - '.dart'.length, null, ''); } final Map<String, String> testImports = <String, String>{}; final Set<String> seenTestConfigPaths = <String>{}; for (final Uri path in paths) { final String sanitizedPath = !path.path.endsWith('?') ? path.path : path.path.substring(0, path.path.length - 1); final String sanitizedImport = pathToImport(sanitizedPath); buffer.writeln("import '$sanitizedPath' as $sanitizedImport;"); testImports[sanitizedPath] = sanitizedImport; final File? testConfigFile = findTestConfigFile( globals.fs.file( globals.platform.isWindows ? sanitizedPath.replaceAll('/', r'\').replaceFirst(r'\', '') : sanitizedPath, ), globals.logger, ); if (testConfigFile != null) { final String sanitizedTestConfigImport = pathToImport(testConfigFile.path); testConfigPaths[sanitizedImport] = sanitizedTestConfigImport; if (seenTestConfigPaths.add(testConfigFile.path)) { buffer.writeln("import '${Uri.file(testConfigFile.path, windows: true)}' as $sanitizedTestConfigImport;"); } } } buffer.writeln(); buffer.writeln('const List<String> packageTestArgs = <String>['); for (final String arg in packageTestArgs) { buffer.writeln(" '$arg',"); } buffer.writeln('];'); buffer.writeln(); buffer.writeln('const List<String> testPaths = <String>['); for (final Uri path in paths) { buffer.writeln(" '$path',"); } buffer.writeln('];'); buffer.writeln(); buffer.writeln(r''' @Native<Void Function(Pointer<Utf8>, Pointer<Utf8>)>(symbol: 'Spawn') external void _spawn(Pointer<Utf8> entrypoint, Pointer<Utf8> route); void spawn({required SendPort port, String entrypoint = 'main', String route = '/'}) { assert( entrypoint != 'main' || route != '/', 'Spawn should not be used to spawn main with the default route name', ); IsolateNameServer.registerPortWithName(port, route); _spawn(entrypoint.toNativeUtf8(), route.toNativeUtf8()); } '''); buffer.write(''' /// Runs on a spawned isolate. void createChannelAndConnect(String path, String name, Function testMain) { goldenFileComparator = LocalFileComparator(Uri.parse(path)); autoUpdateGoldenFiles = $autoUpdateGoldenFiles; final IsolateChannel<dynamic> channel = IsolateChannel<dynamic>.connectSend( IsolateNameServer.lookupPortByName(name)!, ); channel.pipe(RemoteListener.start(() => testMain)); } void testMain() { final String route = PlatformDispatcher.instance.defaultRouteName; switch (route) { '''); for (final MapEntry<String, String> kvp in testImports.entries) { final String importName = kvp.value; final String path = kvp.key; final String? testConfigImport = testConfigPaths[importName]; if (testConfigImport != null) { buffer.writeln(" case '$importName':"); buffer.writeln(" createChannelAndConnect('$path', route, () => $testConfigImport.testExecutable($importName.main));"); } else { buffer.writeln(" case '$importName':"); buffer.writeln(" createChannelAndConnect('$path', route, $importName.main);"); } } buffer.write(r''' } } void main([dynamic sendPort]) { if (sendPort is SendPort) { final ReceivePort receivePort = ReceivePort(); receivePort.listen((dynamic msg) { switch (msg as List<dynamic>) { case ['spawn', final SendPort port, final String entrypoint, final String route]: spawn(port: port, entrypoint: entrypoint, route: route); case ['close']: receivePort.close(); } }); sendPort.send(<Object>[receivePort.sendPort, packageTestArgs, testPaths]); } } '''); childTestIsolateSpawnerSourceFile.writeAsStringSync(buffer.toString()); } static void _generateRootTestIsolateSpawnerSourceFile({ required File childTestIsolateSpawnerSourceFile, required File childTestIsolateSpawnerDillFile, required File rootTestIsolateSpawnerSourceFile, }) { final StringBuffer buffer = StringBuffer(); buffer.writeln(''' import 'dart:async'; import 'dart:ffi'; import 'dart:io' show exit, exitCode; // flutter_ignore: dart_io_import import 'dart:isolate'; import 'dart:ui'; import 'package:ffi/ffi.dart'; import 'package:stream_channel/isolate_channel.dart'; import 'package:stream_channel/stream_channel.dart'; import 'package:test_core/src/executable.dart' as test; // ignore: implementation_imports import 'package:test_core/src/platform.dart'; // ignore: implementation_imports @Native<Handle Function(Pointer<Utf8>)>(symbol: 'LoadLibraryFromKernel') external Object _loadLibraryFromKernel(Pointer<Utf8> path); @Native<Handle Function(Pointer<Utf8>, Pointer<Utf8>)>(symbol: 'LookupEntryPoint') external Object _lookupEntryPoint(Pointer<Utf8> library, Pointer<Utf8> name); late final List<String> packageTestArgs; late final List<String> testPaths; /// Runs on the main isolate. Future<void> registerPluginAndRun() { final SpawnPlugin platform = SpawnPlugin(); registerPlatformPlugin( <Runtime>[Runtime.vm], () { return platform; }, ); return test.main(<String>[...packageTestArgs, '--', ...testPaths]); } late final Isolate rootTestIsolate; late final SendPort commandPort; bool readyToRun = false; final Completer<void> readyToRunSignal = Completer<void>(); Future<void> spawn({ required SendPort port, String entrypoint = 'main', String route = '/', }) async { if (!readyToRun) { await readyToRunSignal.future; } commandPort.send(<Object>['spawn', port, entrypoint, route]); } void main() async { final String route = PlatformDispatcher.instance.defaultRouteName; if (route == '/') { final ReceivePort port = ReceivePort(); port.listen((dynamic message) { final [SendPort sendPort, List<String> args, List<String> paths] = message as List<dynamic>; commandPort = sendPort; packageTestArgs = args; testPaths = paths; readyToRun = true; readyToRunSignal.complete(); }); rootTestIsolate = await Isolate.spawn( _loadLibraryFromKernel( r'${childTestIsolateSpawnerDillFile.absolute.path}' .toNativeUtf8()) as void Function(SendPort), port.sendPort, ); await readyToRunSignal.future; port.close(); // Not expecting anything else. await registerPluginAndRun(); // The [test.main] call in [registerPluginAndRun] sets dart:io's [exitCode] // global. exit(exitCode); } else { (_lookupEntryPoint( r'file://${childTestIsolateSpawnerSourceFile.absolute.uri.toFilePath(windows: false)}' .toNativeUtf8(), 'testMain'.toNativeUtf8()) as void Function())(); } } '''); buffer.write(r''' String pathToImport(String path) { assert(path.endsWith('.dart')); return path .replaceRange(path.length - '.dart'.length, null, '') .replaceAll('.', '_') .replaceAll(':', '_') .replaceAll('/', '_') .replaceAll(r'\', '_'); } class SpawnPlugin extends PlatformPlugin { SpawnPlugin(); final Map<String, IsolateChannel<dynamic>> _channels = <String, IsolateChannel<dynamic>>{}; Future<void> launchIsolate(String path) async { final String name = pathToImport(path); final ReceivePort port = ReceivePort(); _channels[name] = IsolateChannel<dynamic>.connectReceive(port); await spawn(port: port.sendPort, route: name); } @override Future<void> close() async { commandPort.send(<String>['close']); } '''); buffer.write(''' @override Future<RunnerSuite> load( String path, SuitePlatform platform, SuiteConfiguration suiteConfig, Object message, ) async { final String correctedPath = ${globals.platform.isWindows ? r'"/$path"' : 'path'}; await launchIsolate(correctedPath); final StreamChannel<dynamic> channel = _channels[pathToImport(correctedPath)]!; final RunnerSuiteController controller = deserializeSuite(correctedPath, platform, suiteConfig, const PluginEnvironment(), channel, message); return controller.suite; } } '''); rootTestIsolateSpawnerSourceFile.writeAsStringSync(buffer.toString()); } static Future<void> _compileFile({ required DebuggingOptions debuggingOptions, required File packageConfigFile, required PackageConfig packageConfig, required File sourceFile, required File outputDillFile, required TestTimeRecorder? testTimeRecorder, Uri? nativeAssetsYaml, }) async { globals.printTrace('Compiling ${sourceFile.absolute.uri}'); final Stopwatch compilerTime = Stopwatch()..start(); final Stopwatch? testTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.Compile); final ResidentCompiler residentCompiler = ResidentCompiler( globals.artifacts!.getArtifactPath(Artifact.flutterPatchedSdkPath), artifacts: globals.artifacts!, logger: globals.logger, processManager: globals.processManager, buildMode: debuggingOptions.buildInfo.mode, trackWidgetCreation: debuggingOptions. buildInfo.trackWidgetCreation, dartDefines: debuggingOptions.buildInfo.dartDefines, packagesPath: packageConfigFile.path, frontendServerStarterPath: debuggingOptions.buildInfo.frontendServerStarterPath, extraFrontEndOptions: debuggingOptions.buildInfo.extraFrontEndOptions, platform: globals.platform, testCompilation: true, fileSystem: globals.fs, fileSystemRoots: debuggingOptions.buildInfo.fileSystemRoots, fileSystemScheme: debuggingOptions.buildInfo.fileSystemScheme, ); await residentCompiler.recompile( sourceFile.absolute.uri, null, outputPath: outputDillFile.absolute.path, packageConfig: packageConfig, fs: globals.fs, nativeAssetsYaml: nativeAssetsYaml, ); residentCompiler.accept(); globals.printTrace('Compiling ${sourceFile.absolute.uri} took ${compilerTime.elapsedMilliseconds}ms'); testTimeRecorder?.stop(TestTimePhases.Compile, testTimeRecorderStopwatch!); } @override Future<int> runTestsBySpawningLightweightEngines( List<Uri> testFiles, { required DebuggingOptions debuggingOptions, List<String> names = const <String>[], List<String> plainNames = const <String>[], String? tags, String? excludeTags, bool machine = false, bool updateGoldens = false, required int? concurrency, String? testAssetDirectory, FlutterProject? flutterProject, String? icudtlPath, String? randomSeed, String? reporter, String? fileReporter, String? timeout, bool runSkipped = false, int? shardIndex, int? totalShards, TestTimeRecorder? testTimeRecorder, TestCompilerNativeAssetsBuilder? nativeAssetsBuilder, }) async { assert(testFiles.length > 1); final Directory buildDirectory = globals.fs.directory(globals.fs.path.join( flutterProject!.directory.path, getBuildDirectory(), )); final Directory isolateSpawningTesterDirectory = buildDirectory.childDirectory( 'isolate_spawning_tester', ); isolateSpawningTesterDirectory.createSync(); final File isolateSpawningTesterPackageConfigFile = isolateSpawningTesterDirectory .childDirectory('.dart_tool') .childFile( 'package_config.json', ); isolateSpawningTesterPackageConfigFile.createSync(recursive: true); await _generateIsolateSpawningTesterPackageConfig( flutterProject: flutterProject, isolateSpawningTesterPackageConfigFile: isolateSpawningTesterPackageConfigFile, ); final PackageConfig isolateSpawningTesterPackageConfig = PackageConfig.parseBytes( isolateSpawningTesterPackageConfigFile.readAsBytesSync(), isolateSpawningTesterPackageConfigFile.uri, ); final File childTestIsolateSpawnerSourceFile = isolateSpawningTesterDirectory.childFile( 'child_test_isolate_spawner.dart', ); final File rootTestIsolateSpawnerSourceFile = isolateSpawningTesterDirectory.childFile( 'root_test_isolate_spawner.dart', ); final File childTestIsolateSpawnerDillFile = isolateSpawningTesterDirectory.childFile( 'child_test_isolate_spawner.dill', ); final File rootTestIsolateSpawnerDillFile = isolateSpawningTesterDirectory.childFile( 'root_test_isolate_spawner.dill', ); // Compute the command-line arguments for package:test. final List<String> packageTestArgs = <String>[ if (!globals.terminal.supportsColor) '--no-color', if (machine) ...<String>['-r', 'json'] else if (reporter != null) ...<String>['-r', reporter], if (fileReporter != null) '--file-reporter=$fileReporter', if (timeout != null) ...<String>['--timeout', timeout], if (concurrency != null) '--concurrency=$concurrency', for (final String name in names) ...<String>['--name', name], for (final String plainName in plainNames) ...<String>['--plain-name', plainName], if (randomSeed != null) '--test-randomize-ordering-seed=$randomSeed', if (tags != null) ...<String>['--tags', tags], if (excludeTags != null) ...<String>['--exclude-tags', excludeTags], if (runSkipped) '--run-skipped', if (totalShards != null) '--total-shards=$totalShards', if (shardIndex != null) '--shard-index=$shardIndex', '--chain-stack-traces', ]; _generateChildTestIsolateSpawnerSourceFile( testFiles, packageTestArgs: packageTestArgs, autoUpdateGoldenFiles: updateGoldens, childTestIsolateSpawnerSourceFile: childTestIsolateSpawnerSourceFile, childTestIsolateSpawnerDillFile: childTestIsolateSpawnerDillFile, ); _generateRootTestIsolateSpawnerSourceFile( childTestIsolateSpawnerSourceFile: childTestIsolateSpawnerSourceFile, childTestIsolateSpawnerDillFile: childTestIsolateSpawnerDillFile, rootTestIsolateSpawnerSourceFile: rootTestIsolateSpawnerSourceFile, ); final Uri? nativeAssetsYaml = await nativeAssetsBuilder?.build( debuggingOptions.buildInfo, ); await _compileFile( debuggingOptions: debuggingOptions, packageConfigFile: isolateSpawningTesterPackageConfigFile, packageConfig: isolateSpawningTesterPackageConfig, sourceFile: childTestIsolateSpawnerSourceFile, outputDillFile: childTestIsolateSpawnerDillFile, testTimeRecorder: testTimeRecorder, nativeAssetsYaml: nativeAssetsYaml, ); await _compileFile( debuggingOptions: debuggingOptions, packageConfigFile: isolateSpawningTesterPackageConfigFile, packageConfig: isolateSpawningTesterPackageConfig, sourceFile: rootTestIsolateSpawnerSourceFile, outputDillFile: rootTestIsolateSpawnerDillFile, testTimeRecorder: testTimeRecorder, ); final List<String> command = <String>[ globals.artifacts!.getArtifactPath(Artifact.flutterTester), '--disable-vm-service', if (icudtlPath != null) '--icu-data-file-path=$icudtlPath', '--enable-checked-mode', '--verify-entry-points', '--enable-software-rendering', '--skia-deterministic-rendering', if (debuggingOptions.enableDartProfiling) '--enable-dart-profiling', '--non-interactive', '--use-test-fonts', '--disable-asset-fonts', '--packages=${debuggingOptions.buildInfo.packagesPath}', if (testAssetDirectory != null) '--flutter-assets-dir=$testAssetDirectory', if (debuggingOptions.nullAssertions) '--dart-flags=--null_assertions', ...debuggingOptions.dartEntrypointArgs, rootTestIsolateSpawnerDillFile.absolute.path ]; // If the FLUTTER_TEST environment variable has been set, then pass it on // for package:flutter_test to handle the value. // // If FLUTTER_TEST has not been set, assume from this context that this // call was invoked by the command 'flutter test'. final String flutterTest = globals.platform.environment.containsKey('FLUTTER_TEST') ? globals.platform.environment['FLUTTER_TEST']! : 'true'; final Map<String, String> environment = <String, String>{ 'FLUTTER_TEST': flutterTest, 'FONTCONFIG_FILE': FontConfigManager().fontConfigFile.path, 'APP_NAME': flutterProject.manifest.appName, if (testAssetDirectory != null) 'UNIT_TEST_ASSETS': testAssetDirectory, }; globals.logger.printTrace('Starting flutter_tester process with command=$command, environment=$environment'); final Stopwatch? testTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.Run); final Process process = await globals.processManager.start(command, environment: environment); globals.logger.printTrace('Started flutter_tester process at pid ${process.pid}'); for (final Stream<List<int>> stream in <Stream<List<int>>>[ process.stderr, process.stdout, ]) { stream .transform<String>(utf8.decoder) .listen(globals.stdio.stdoutWrite); } return process.exitCode.then((int exitCode) { testTimeRecorder?.stop(TestTimePhases.Run, testTimeRecorderStopwatch!); globals.logger.printTrace('flutter_tester process at pid ${process.pid} exited with code=$exitCode'); return exitCode; }); } }
flutter/packages/flutter_tools/lib/src/test/runner.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/test/runner.dart", "repo_id": "flutter", "token_count": 10830 }
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 'dart:async'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'package:webkit_inspection_protocol/webkit_inspection_protocol.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/os.dart'; import '../base/platform.dart'; import '../convert.dart'; /// An environment variable used to override the location of Google Chrome. const String kChromeEnvironment = 'CHROME_EXECUTABLE'; /// An environment variable used to override the location of Microsoft Edge. const String kEdgeEnvironment = 'EDGE_ENVIRONMENT'; /// The expected executable name on linux. const String kLinuxExecutable = 'google-chrome'; /// The expected executable name on macOS. const String kMacOSExecutable = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; /// The expected Chrome executable name on Windows. const String kWindowsExecutable = r'Google\Chrome\Application\chrome.exe'; /// The expected Edge executable name on Windows. const String kWindowsEdgeExecutable = r'Microsoft\Edge\Application\msedge.exe'; /// Used by [ChromiumLauncher] to detect a glibc bug and retry launching the /// browser. /// /// Once every few thousands of launches we hit this glibc bug: /// /// https://sourceware.org/bugzilla/show_bug.cgi?id=19329. /// /// When this happens Chrome spits out something like the following then exits with code 127: /// /// Inconsistency detected by ld.so: ../elf/dl-tls.c: 493: _dl_allocate_tls_init: Assertion `listp->slotinfo[cnt].gen <= GL(dl_tls_generation)' failed! const String _kGlibcError = 'Inconsistency detected by ld.so'; typedef BrowserFinder = String Function(Platform, FileSystem); /// Find the chrome executable on the current platform. /// /// Does not verify whether the executable exists. String findChromeExecutable(Platform platform, FileSystem fileSystem) { if (platform.environment.containsKey(kChromeEnvironment)) { return platform.environment[kChromeEnvironment]!; } if (platform.isLinux) { return kLinuxExecutable; } if (platform.isMacOS) { return kMacOSExecutable; } if (platform.isWindows) { /// The possible locations where the chrome executable can be located on windows. final List<String> kWindowsPrefixes = <String>[ if (platform.environment.containsKey('LOCALAPPDATA')) platform.environment['LOCALAPPDATA']!, if (platform.environment.containsKey('PROGRAMFILES')) platform.environment['PROGRAMFILES']!, if (platform.environment.containsKey('PROGRAMFILES(X86)')) platform.environment['PROGRAMFILES(X86)']!, ]; final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) { final String path = fileSystem.path.join(prefix, kWindowsExecutable); return fileSystem.file(path).existsSync(); }, orElse: () => '.'); return fileSystem.path.join(windowsPrefix, kWindowsExecutable); } throwToolExit('Platform ${platform.operatingSystem} is not supported.'); } /// Find the Microsoft Edge executable on the current platform. /// /// Does not verify whether the executable exists. String findEdgeExecutable(Platform platform, FileSystem fileSystem) { if (platform.environment.containsKey(kEdgeEnvironment)) { return platform.environment[kEdgeEnvironment]!; } if (platform.isWindows) { /// The possible locations where the Edge executable can be located on windows. final List<String> kWindowsPrefixes = <String>[ if (platform.environment.containsKey('LOCALAPPDATA')) platform.environment['LOCALAPPDATA']!, if (platform.environment.containsKey('PROGRAMFILES')) platform.environment['PROGRAMFILES']!, if (platform.environment.containsKey('PROGRAMFILES(X86)')) platform.environment['PROGRAMFILES(X86)']!, ]; final String windowsPrefix = kWindowsPrefixes.firstWhere((String prefix) { final String path = fileSystem.path.join(prefix, kWindowsEdgeExecutable); return fileSystem.file(path).existsSync(); }, orElse: () => '.'); return fileSystem.path.join(windowsPrefix, kWindowsEdgeExecutable); } // Not yet supported for macOS and Linux. return ''; } /// A launcher for Chromium browsers with devtools configured. class ChromiumLauncher { ChromiumLauncher({ required FileSystem fileSystem, required Platform platform, required ProcessManager processManager, required OperatingSystemUtils operatingSystemUtils, required BrowserFinder browserFinder, required Logger logger, }) : _fileSystem = fileSystem, _platform = platform, _processManager = processManager, _operatingSystemUtils = operatingSystemUtils, _browserFinder = browserFinder, _logger = logger; final FileSystem _fileSystem; final Platform _platform; final ProcessManager _processManager; final OperatingSystemUtils _operatingSystemUtils; final BrowserFinder _browserFinder; final Logger _logger; bool get hasChromeInstance => currentCompleter.isCompleted; @visibleForTesting Completer<Chromium> currentCompleter = Completer<Chromium>(); /// Whether we can locate the chrome executable. bool canFindExecutable() { final String chrome = _browserFinder(_platform, _fileSystem); try { return _processManager.canRun(chrome); } on ArgumentError { return false; } } /// The executable this launcher will use. String findExecutable() => _browserFinder(_platform, _fileSystem); /// Launch a Chromium browser to a particular `host` page. /// /// [headless] defaults to false, and controls whether we open a headless or /// a "headful" browser. /// /// [debugPort] is Chrome's debugging protocol port. If null, a random free /// port is picked automatically. /// /// [skipCheck] does not attempt to make a devtools connection before returning. /// /// [webBrowserFlags] add arbitrary browser flags. Future<Chromium> launch(String url, { bool headless = false, int? debugPort, bool skipCheck = false, Directory? cacheDir, List<String> webBrowserFlags = const <String>[], }) async { if (currentCompleter.isCompleted) { throwToolExit('Only one instance of chrome can be started.'); } if (_logger.isVerbose) { _logger.printTrace('Launching Chromium (url = $url, headless = $headless, skipCheck = $skipCheck, debugPort = $debugPort)'); } final String chromeExecutable = _browserFinder(_platform, _fileSystem); if (_logger.isVerbose) { _logger.printTrace('Will use Chromium executable at $chromeExecutable'); if (!_platform.isWindows) { // The "--version" argument is not supported on Windows. final ProcessResult versionResult = await _processManager.run(<String>[chromeExecutable, '--version']); _logger.printTrace('Using ${versionResult.stdout}'); } } final Directory userDataDir = _fileSystem.systemTempDirectory .createTempSync('flutter_tools_chrome_device.'); if (cacheDir != null) { // Seed data dir with previous state. _restoreUserSessionInformation(cacheDir, userDataDir); } final int port = debugPort ?? await _operatingSystemUtils.findFreePort(); final List<String> args = <String>[ chromeExecutable, // Using a tmp directory ensures that a new instance of chrome launches // allowing for the remote debug port to be enabled. '--user-data-dir=${userDataDir.path}', '--remote-debugging-port=$port', // When the DevTools has focus we don't want to slow down the application. '--disable-background-timer-throttling', // Since we are using a temp profile, disable features that slow the // Chrome launch. '--disable-extensions', '--disable-popup-blocking', '--bwsi', '--no-first-run', '--no-default-browser-check', '--disable-default-apps', '--disable-translate', if (headless) ...<String>[ '--headless', '--disable-gpu', '--no-sandbox', '--window-size=2400,1800', ], ...webBrowserFlags, url, ]; final Process process = await _spawnChromiumProcess(args, chromeExecutable); // When the process exits, copy the user settings back to the provided data-dir. if (cacheDir != null) { unawaited(process.exitCode.whenComplete(() { _cacheUserSessionInformation(userDataDir, cacheDir); // cleanup temp dir try { userDataDir.deleteSync(recursive: true); } on FileSystemException { // ignore } })); } return connect(Chromium( port, ChromeConnection('localhost', port), url: url, process: process, chromiumLauncher: this, logger: _logger, ), skipCheck); } Future<Process> _spawnChromiumProcess(List<String> args, String chromeExecutable) async { if (_operatingSystemUtils.hostPlatform == HostPlatform.darwin_arm64) { final ProcessResult result = _processManager.runSync(<String>['file', chromeExecutable]); // Check if ARM Chrome is installed. // Mach-O 64-bit executable arm64 if ((result.stdout as String).contains('arm64')) { _logger.printTrace('Found ARM Chrome installation at $chromeExecutable, forcing native launch.'); // If so, force Chrome to launch natively. args.insertAll(0, <String>['/usr/bin/arch', '-arm64']); } } // Keep attempting to launch the browser until one of: // - Chrome launched successfully, in which case we just return from the loop. // - The tool reached the maximum retry count, in which case we throw ToolExit. const int kMaxRetries = 3; int retry = 0; while (true) { final Process process = await _processManager.start(args); process.stdout .transform(utf8.decoder) .transform(const LineSplitter()) .listen((String line) { _logger.printTrace('[CHROME]: $line'); }); // Wait until the DevTools are listening before trying to connect. This is // only required for flutter_test --platform=chrome and not flutter run. bool hitGlibcBug = false; bool shouldRetry = false; final List<String> errors = <String>[]; await process.stderr .transform(utf8.decoder) .transform(const LineSplitter()) .map((String line) { _logger.printTrace('[CHROME]: $line'); errors.add('[CHROME]:$line'); if (line.contains(_kGlibcError)) { hitGlibcBug = true; shouldRetry = true; } return line; }) .firstWhere((String line) => line.startsWith('DevTools listening'), orElse: () { if (hitGlibcBug) { _logger.printTrace( 'Encountered glibc bug https://sourceware.org/bugzilla/show_bug.cgi?id=19329. ' 'Will try launching browser again.', ); // Return value unused. return ''; } if (retry >= kMaxRetries) { errors.forEach(_logger.printError); _logger.printError('Failed to launch browser after $kMaxRetries tries. Command used to launch it: ${args.join(' ')}'); throw ToolExit( 'Failed to launch browser. Make sure you are using an up-to-date ' 'Chrome or Edge. Otherwise, consider using -d web-server instead ' 'and filing an issue at https://github.com/flutter/flutter/issues.', ); } shouldRetry = true; return ''; }); if (!hitGlibcBug && !shouldRetry) { return process; } retry += 1; // A precaution that avoids accumulating browser processes, in case the // glibc bug doesn't cause the browser to quit and we keep looping and // launching more processes. unawaited(process.exitCode.timeout(const Duration(seconds: 1), onTimeout: () { process.kill(); // sigterm return 15; })); } } // This is a directory which Chrome uses to store cookies, preferences and // other session data. String get _chromeDefaultPath => _fileSystem.path.join('Default'); // This is a JSON file which contains configuration from the browser session, // such as window position. It is located under the Chrome data-dir folder. String get _preferencesPath => _fileSystem.path.join('Default', 'preferences'); /// Copy Chrome user information from a Chrome session into a per-project /// cache. /// /// More detailed docs of the Chrome user preferences store exists here: /// https://www.chromium.org/developers/design-documents/preferences. /// /// This intentionally skips the Cache, Code Cache, and GPUCache directories. /// While we're not sure exactly what is in them, this constitutes nearly 1 GB /// of data for a fresh flutter run and adds significant overhead to all startups. /// For workflows that may require this data, using the start-paused flag and /// dart debug extension with a user controlled browser profile will lead to a /// better experience. void _cacheUserSessionInformation(Directory userDataDir, Directory cacheDir) { final Directory targetChromeDefault = _fileSystem.directory(_fileSystem.path.join(cacheDir.path, _chromeDefaultPath)); final Directory sourceChromeDefault = _fileSystem.directory(_fileSystem.path.join(userDataDir.path, _chromeDefaultPath)); if (sourceChromeDefault.existsSync()) { targetChromeDefault.createSync(recursive: true); try { copyDirectory( sourceChromeDefault, targetChromeDefault, shouldCopyDirectory: _isNotCacheDirectory ); } on FileSystemException catch (err) { // This is a best-effort update. Display the message in case the failure is relevant. // one possible example is a file lock due to multiple running chrome instances. _logger.printError('Failed to save Chrome preferences: $err'); } } final File targetPreferencesFile = _fileSystem.file(_fileSystem.path.join(cacheDir.path, _preferencesPath)); final File sourcePreferencesFile = _fileSystem.file(_fileSystem.path.join(userDataDir.path, _preferencesPath)); if (sourcePreferencesFile.existsSync()) { targetPreferencesFile.parent.createSync(recursive: true); // If the file contains a crash string, remove it to hide the popup on next run. final String contents = sourcePreferencesFile.readAsStringSync(); targetPreferencesFile.writeAsStringSync(contents .replaceFirst('"exit_type":"Crashed"', '"exit_type":"Normal"')); } } /// Restore Chrome user information from a per-project cache into Chrome's /// user data directory. void _restoreUserSessionInformation(Directory cacheDir, Directory userDataDir) { final Directory sourceChromeDefault = _fileSystem.directory(_fileSystem.path.join(cacheDir.path, _chromeDefaultPath)); final Directory targetChromeDefault = _fileSystem.directory(_fileSystem.path.join(userDataDir.path, _chromeDefaultPath)); try { if (sourceChromeDefault.existsSync()) { targetChromeDefault.createSync(recursive: true); copyDirectory( sourceChromeDefault, targetChromeDefault, shouldCopyDirectory: _isNotCacheDirectory, ); } } on FileSystemException catch (err) { _logger.printError('Failed to restore Chrome preferences: $err'); } } // Cache, Code Cache, and GPUCache are nearly 1GB of data bool _isNotCacheDirectory(Directory directory) { return !directory.path.endsWith('Cache') && !directory.path.endsWith('Code Cache') && !directory.path.endsWith('GPUCache'); } /// Connect to the [chrome] instance, testing the connection if /// [skipCheck] is set to false. @visibleForTesting Future<Chromium> connect(Chromium chrome, bool skipCheck) async { // The connection is lazy. Try a simple call to make sure the provided // connection is valid. if (!skipCheck) { try { await _getFirstTab(chrome); } on Exception catch (error, stackTrace) { _logger.printError('$error', stackTrace: stackTrace); await chrome.close(); throwToolExit( 'Unable to connect to Chrome debug port: ${chrome.debugPort}\n $error'); } } currentCompleter.complete(chrome); return chrome; } /// Gets the first [chrome] tab. /// /// Retries getting tabs from Chrome for a few seconds and retries finding /// the tab a few times. This reduces flakes caused by Chrome not returning /// correct output if the call was too close to the start. // // TODO(ianh): remove the timeouts here, they violate our style guide. // (We should just keep waiting forever, and print a warning when it's // taking too long.) Future<ChromeTab?> _getFirstTab(Chromium chrome) async { const Duration retryFor = Duration(seconds: 2); const int attempts = 5; for (int i = 1; i <= attempts; i++) { try { final List<ChromeTab> tabs = await chrome.chromeConnection.getTabs(retryFor: retryFor); if (tabs.isNotEmpty) { return tabs.first; } if (i == attempts) { return null; } } on ConnectionException catch (_) { if (i == attempts) { rethrow; } } await Future<void>.delayed(const Duration(milliseconds: 25)); } return null; } Future<Chromium> get connectedInstance => currentCompleter.future; } /// A class for managing an instance of a Chromium browser. class Chromium { Chromium( this.debugPort, this.chromeConnection, { this.url, required Process process, required ChromiumLauncher chromiumLauncher, required Logger logger, }) : _process = process, _chromiumLauncher = chromiumLauncher, _logger = logger; final String? url; final int debugPort; final Process _process; final ChromeConnection chromeConnection; final ChromiumLauncher _chromiumLauncher; final Logger _logger; /// Resolves to browser's main process' exit code, when the browser exits. Future<int> get onExit async => _process.exitCode; /// The main Chromium process that represents this instance of Chromium. /// /// Killing this process should result in the browser exiting. @visibleForTesting Process get process => _process; /// Closes all connections to the browser and asks the browser to exit. Future<void> close() async { if (_logger.isVerbose) { _logger.printTrace('Shutting down Chromium.'); } if (_chromiumLauncher.hasChromeInstance) { _chromiumLauncher.currentCompleter = Completer<Chromium>(); } chromeConnection.close(); // Try to exit Chromium nicely using SIGTERM, before exiting it rudely using // SIGKILL. Wait no longer than 5 seconds for Chromium to exit before // falling back to SIGKILL, and then to a warning message. ProcessSignal.sigterm.kill(_process); await _process.exitCode.timeout(const Duration(seconds: 5), onTimeout: () { _logger.printWarning( 'Failed to exit Chromium (pid: ${_process.pid}) using SIGTERM. Will try ' 'sending SIGKILL instead.' ); ProcessSignal.sigkill.kill(_process); return _process.exitCode.timeout(const Duration(seconds: 5), onTimeout: () async { _logger.printWarning( 'Failed to exit Chromium (pid: ${_process.pid}) using SIGKILL. Giving ' 'up. Will continue, assuming Chromium has exited successfully, but ' 'it is possible that this left a dangling Chromium process running ' 'on the system.' ); return 0; }); }); } }
flutter/packages/flutter_tools/lib/src/web/chrome.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/web/chrome.dart", "repo_id": "flutter", "token_count": 6979 }
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/file_system.dart'; import '../../base/project_migrator.dart'; import '../../cmake_project.dart'; import 'utils.dart'; const String _cmakeFileToolBackendBefore = r''' add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" windows-x64 $<CONFIG> VERBATIM ) '''; const String _cmakeFileToolBackendAfter = r''' add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" ${FLUTTER_TARGET_PLATFORM} $<CONFIG> VERBATIM ) '''; const String _cmakeFileTargetPlatformBefore = r''' # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # === Flutter Library === '''; const String _cmakeFileTargetPlatformAfter = r''' # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === '''; /// Migrates Windows build to target specific architecture. /// In more, it deletes old runner folder class BuildArchitectureMigration extends ProjectMigrator { BuildArchitectureMigration( WindowsProject project, Directory buildDirectory, super.logger ) : _cmakeFile = project.managedCmakeFile, _buildDirectory = buildDirectory; final File _cmakeFile; final Directory _buildDirectory; @override void migrate() { final Directory oldRunnerDirectory = _buildDirectory .parent .childDirectory('runner'); if (oldRunnerDirectory.existsSync()) { logger.printTrace(''' Deleting previous build folder ${oldRunnerDirectory.path}. New binaries can be found in ${_buildDirectory.childDirectory('runner').path}. '''); try { oldRunnerDirectory.deleteSync(recursive: true); } on FileSystemException catch (error) { logger.printError( 'Failed to remove ${oldRunnerDirectory.path}: $error. ' 'A program may still be using a file in the directory or the directory itself. ' 'To find and stop such a program, see: ' 'https://superuser.com/questions/1333118/cant-delete-empty-folder-because-it-is-used' ); } } // Skip this migration if the affected file does not exist. This indicates // the app has done non-trivial changes to its runner and this migration // might not work as expected if applied. if (!_cmakeFile.existsSync()) { logger.printTrace(''' windows/flutter/CMakeLists.txt file not found, skipping build architecture migration. This indicates non-trivial changes have been made to the "windows" folder. If needed, you can reset it by deleting the "windows" folder and then using the "flutter create --platforms=windows ." command. '''); return; } // Migrate the windows/flutter/CMakeLists.txt file. final String originalCmakeContents = _cmakeFile.readAsStringSync(); final String cmakeContentsWithTargetPlatform = replaceFirst( originalCmakeContents, _cmakeFileTargetPlatformBefore, _cmakeFileTargetPlatformAfter, ); final String newCmakeContents = replaceFirst( cmakeContentsWithTargetPlatform, _cmakeFileToolBackendBefore, _cmakeFileToolBackendAfter, ); if (originalCmakeContents != newCmakeContents) { logger.printStatus('windows/flutter/CMakeLists.txt does not use FLUTTER_TARGET_PLATFORM, updating.'); _cmakeFile.writeAsStringSync(newCmakeContents); } } }
flutter/packages/flutter_tools/lib/src/windows/migrations/build_architecture_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/windows/migrations/build_architecture_migration.dart", "repo_id": "flutter", "token_count": 1592 }
758
import 'package:flutter/material.dart'; {{#withEmptyMain}} void main() { runApp(const MainApp()); } class MainApp extends StatelessWidget { const MainApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Scaffold( body: Center( child: Text('Hello World!'), ), ), ); } } {{/withEmptyMain}} {{^withEmptyMain}} {{#withPlatformChannelPluginHook}} import 'dart:async'; import 'package:flutter/services.dart'; import 'package:{{pluginProjectName}}/{{pluginProjectName}}.dart'; {{/withPlatformChannelPluginHook}} {{#withFfi}} import 'dart:async'; import 'package:{{pluginProjectName}}/{{pluginProjectName}}.dart' as {{pluginProjectName}}; {{/withFfi}} void main() { runApp(const MyApp()); } {{^withPluginHook}} class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // TRY THIS: Try running your application with "flutter run". You'll see // the application has a purple toolbar. Then, without quitting the app, // try changing the seedColor in the colorScheme below to Colors.green // and then invoke "hot reload" (save your changes or press the "hot // reload" button in a Flutter-supported IDE, or press "r" if you used // the command line to start the app). // // Notice that the counter didn't reset back to zero; the application // state is not lost during the reload. To reset the state, use hot // restart instead. // // This works for code too, not just values: Most code changes can be // tested with just a hot reload. colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // TRY THIS: Try changing the color here to a specific color (to // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar // change color while the other colors stay the same. backgroundColor: Theme.of(context).colorScheme.inversePrimary, // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). // // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint" // action in the IDE, or press "p" in the console), to see the // wireframe for each widget. mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } {{/withPluginHook}} {{#withPlatformChannelPluginHook}} class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String _platformVersion = 'Unknown'; final _{{pluginClassLowerCamelCase}} = {{pluginDartClass}}(); @override void initState() { super.initState(); initPlatformState(); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initPlatformState() async { String platformVersion; // Platform messages may fail, so we use a try/catch PlatformException. // We also handle the message potentially returning null. try { platformVersion = await _{{pluginClassLowerCamelCase}}.getPlatformVersion() ?? 'Unknown platform version'; } on PlatformException { platformVersion = 'Failed to get platform version.'; } // If the widget was removed from the tree while the asynchronous platform // message was in flight, we want to discard the reply rather than calling // setState to update our non-existent appearance. if (!mounted) return; setState(() { _platformVersion = platformVersion; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Plugin example app'), ), body: Center( child: Text('Running on: $_platformVersion\n'), ), ), ); } } {{/withPlatformChannelPluginHook}} {{#withFfi}} class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { late int sumResult; late Future<int> sumAsyncResult; @override void initState() { super.initState(); sumResult = {{pluginProjectName}}.sum(1, 2); sumAsyncResult = {{pluginProjectName}}.sumAsync(3, 4); } @override Widget build(BuildContext context) { const textStyle = TextStyle(fontSize: 25); const spacerSmall = SizedBox(height: 10); return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Native Packages'), ), body: SingleChildScrollView( child: Container( padding: const EdgeInsets.all(10), child: Column( children: [ const Text( 'This calls a native function through FFI that is shipped as source in the package. ' 'The native code is built as part of the Flutter Runner build.', style: textStyle, textAlign: TextAlign.center, ), spacerSmall, Text( 'sum(1, 2) = $sumResult', style: textStyle, textAlign: TextAlign.center, ), spacerSmall, FutureBuilder<int>( future: sumAsyncResult, builder: (BuildContext context, AsyncSnapshot<int> value) { final displayValue = (value.hasData) ? value.data : 'loading'; return Text( 'await sumAsync(3, 4) = $displayValue', style: textStyle, textAlign: TextAlign.center, ); }, ), ], ), ), ), ), ); } } {{/withFfi}} {{/withEmptyMain}}
flutter/packages/flutter_tools/templates/app/lib/main.dart.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/app/lib/main.dart.tmpl", "repo_id": "flutter", "token_count": 3574 }
759
distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-{{gradleVersion}}-all.zip
flutter/packages/flutter_tools/templates/app_shared/android.tmpl/gradle/wrapper/gradle-wrapper.properties.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/app_shared/android.tmpl/gradle/wrapper/gradle-wrapper.properties.tmpl", "repo_id": "flutter", "token_count": 73 }
760
#include "Generated.xcconfig"
flutter/packages/flutter_tools/templates/app_shared/ios.tmpl/Flutter/Release.xcconfig/0
{ "file_path": "flutter/packages/flutter_tools/templates/app_shared/ios.tmpl/Flutter/Release.xcconfig", "repo_id": "flutter", "token_count": 12 }
761
# Project-level configuration. cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "{{projectName}}") # The unique GTK application identifier for this application. See: # https://wiki.gnome.org/HowDoI/ChooseApplicationID set(APPLICATION_ID "{{linuxIdentifier}}") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(SET CMP0063 NEW) # Load bundled libraries from the lib/ directory relative to the binary. set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") # Root filesystem for cross-building. if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() # Define build configuration options. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Define the application target. To change its name, change BINARY_NAME above, # not the value here, or `flutter run` will no longer work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) # Only the install-generated bundle's copy of the executable will launch # correctly, since the resources must in the right relative locations. To avoid # people trying to run the unbundled copy, put it in a subdirectory instead of # the default top-level location. set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) {{#withPlatformChannelPluginHook}} # Enable the test target. set(include_{{pluginProjectName}}_tests TRUE) {{/withPlatformChannelPluginHook}} # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif()
flutter/packages/flutter_tools/templates/app_shared/linux.tmpl/CMakeLists.txt.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/app_shared/linux.tmpl/CMakeLists.txt.tmpl", "repo_id": "flutter", "token_count": 1999 }
762
rootProject.name = '{{projectName}}'
flutter/packages/flutter_tools/templates/module/android/gradle/settings.gradle.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/android/gradle/settings.gradle.tmpl", "repo_id": "flutter", "token_count": 12 }
763
#import "{{pluginClass}}.h" @implementation {{pluginClass}} + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar { FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"{{projectName}}" binaryMessenger:[registrar messenger]]; {{pluginClass}}* instance = [[{{pluginClass}} alloc] init]; [registrar addMethodCallDelegate:instance channel:channel]; } - (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result { if ([@"getPlatformVersion" isEqualToString:call.method]) { result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]); } else { result(FlutterMethodNotImplemented); } } @end
flutter/packages/flutter_tools/templates/plugin/ios-objc.tmpl/Classes/pluginClass.m.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin/ios-objc.tmpl/Classes/pluginClass.m.tmpl", "repo_id": "flutter", "token_count": 237 }
764
import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:{{projectName}}/{{projectName}}_method_channel.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); MethodChannel{{pluginDartClass}} platform = MethodChannel{{pluginDartClass}}(); const MethodChannel channel = MethodChannel('{{projectName}}'); setUp(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( channel, (MethodCall methodCall) async { return '42'; }, ); }); tearDown(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(channel, null); }); test('getPlatformVersion', () async { expect(await platform.getPlatformVersion(), '42'); }); }
flutter/packages/flutter_tools/templates/plugin/test/projectName_method_channel_test.dart.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin/test/projectName_method_channel_test.dart.tmpl", "repo_id": "flutter", "token_count": 269 }
765
# 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) # Invoke the build for native code shared with the other target platforms. # This can be changed to accommodate different builds. add_subdirectory("${CMAKE_CURRENT_SOURCE_DIR}/../src" "${CMAKE_CURRENT_BINARY_DIR}/shared") # 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 # Defined in ../src/CMakeLists.txt. # This can be changed to accommodate different builds. $<TARGET_FILE:{{projectName}}> PARENT_SCOPE )
flutter/packages/flutter_tools/templates/plugin_ffi/linux.tmpl/CMakeLists.txt.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin_ffi/linux.tmpl/CMakeLists.txt.tmpl", "repo_id": "flutter", "token_count": 275 }
766
name: {{projectName}} description: {{description}} version: 0.0.1 homepage: environment: sdk: {{dartSdkVersionBounds}} flutter: '>=3.3.0' dependencies: flutter: sdk: flutter {{#web}} flutter_web_plugins: sdk: flutter {{/web}} plugin_platform_interface: ^2.0.2 dev_dependencies: {{#withFfi}} ffi: ^2.1.0 ffigen: ^11.0.0 {{/withFfi}} flutter_test: sdk: flutter flutter_lints: ^3.0.0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter packages. flutter: # This section identifies this Flutter project as a plugin project. # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.) # which should be registered in the plugin registry. This is required for # using method channels. # The Android 'package' specifies package in which the registered class is. # This is required for using method channels on Android. # The 'ffiPlugin' specifies that native code should be built and bundled. # This is required for using `dart:ffi`. # All these are used by the tooling to maintain consistency when # adding or updating assets for this project. {{#withFfiPluginHook}} # # Please refer to README.md for a detailed explanation. plugin: platforms: {{#no_platforms}} # This FFI plugin project was generated without specifying any # platforms with the `--platform` argument. If you see the `some_platform` map below, remove it and # then add platforms following the instruction here: # https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms # ------------------- some_platform: ffiPlugin: true # ------------------- {{/no_platforms}} {{#android}} android: ffiPlugin: true {{/android}} {{#ios}} ios: ffiPlugin: true {{/ios}} {{#linux}} linux: ffiPlugin: true {{/linux}} {{#macos}} macos: ffiPlugin: true {{/macos}} {{#windows}} windows: ffiPlugin: true {{/windows}} {{/withFfiPluginHook}} {{#withPlatformChannelPluginHook}} plugin: platforms: {{#no_platforms}} # This plugin project was generated without specifying any # platforms with the `--platform` argument. If you see the `some_platform` map below, remove it and # then add platforms following the instruction here: # https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms # ------------------- some_platform: pluginClass: somePluginClass # ------------------- {{/no_platforms}} {{#android}} android: package: {{androidIdentifier}} pluginClass: {{pluginClass}} {{/android}} {{#ios}} ios: pluginClass: {{pluginClass}} {{/ios}} {{#linux}} linux: pluginClass: {{pluginClass}} {{/linux}} {{#macos}} macos: pluginClass: {{pluginClass}} {{/macos}} {{#windows}} windows: pluginClass: {{pluginClass}}CApi {{/windows}} {{#web}} web: pluginClass: {{pluginDartClass}}Web fileName: {{projectName}}_web.dart {{/web}} {{/withPlatformChannelPluginHook}} # To add assets to your plugin package, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # # For details regarding assets in packages, see # https://flutter.dev/assets-and-images/#from-packages # # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware # To add custom fonts to your plugin package, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts in packages, see # https://flutter.dev/custom-fonts/#from-packages
flutter/packages/flutter_tools/templates/plugin_shared/pubspec.yaml.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/plugin_shared/pubspec.yaml.tmpl", "repo_id": "flutter", "token_count": 1564 }
767
name: {{projectName}} description: {{description}} # Prevent accidental publishing to pub.dev. publish_to: 'none' version: 1.0.0+1 environment: sdk: {{dartSdkVersionBounds}} dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.0 flutter: uses-material-design: true # Enable generation of localized Strings from arb files. generate: true assets: # Add assets from the images directory to the application. - assets/images/
flutter/packages/flutter_tools/templates/skeleton/pubspec.yaml.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/skeleton/pubspec.yaml.tmpl", "repo_id": "flutter", "token_count": 196 }
768
// 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/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import '../integration.shard/test_utils.dart'; import '../src/common.dart'; void main() { late Directory tempDir; late String flutterBin; late Directory exampleAppDir; late Directory pluginDir; final RegExp compileSdkVersionMatch = RegExp(r'compileSdk\s*=?\s*[\w.]+'); final String builtApkPath = <String>['build', 'app', 'outputs', 'flutter-apk', 'app-debug.apk'] .join(platform.pathSeparator); setUp(() async { tempDir = createResolvedTempDirectorySync('flutter_plugin_test.'); flutterBin = fileSystem.path.join( getFlutterRoot(), 'bin', 'flutter', ); pluginDir = tempDir.childDirectory('aaa'); exampleAppDir = pluginDir.childDirectory('example'); processManager.runSync(<String>[ flutterBin, ...getLocalEngineArguments(), 'create', '--template=plugin', '--platforms=android', 'aaa', ], workingDirectory: tempDir.path); }); tearDown(() async { tryToDelete(tempDir); }); test( 'build succeeds targeting string compileSdkVersion', () async { final File buildGradleFile = exampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); // write a build.gradle with compileSdkVersion as `android-UpsideDownCake` which is a string preview version buildGradleFile.writeAsStringSync( buildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkVersion = "android-UpsideDownCake"'), flush: true ); expect(buildGradleFile.readAsStringSync(), contains('compileSdkVersion = "android-UpsideDownCake"')); final ProcessResult result = await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', '--debug', ], workingDirectory: exampleAppDir.path); expect(exampleAppDir.childDirectory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('apk') .childDirectory('debug') .childFile('app-debug.apk').existsSync(), true); expect(result.stdout, contains('Built $builtApkPath')); }, ); test( 'build succeeds targeting string compileSdkPreview', () async { final File buildGradleFile = exampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); // write a build.gradle with compileSdkPreview as `UpsideDownCake` which is a string preview version buildGradleFile.writeAsStringSync( buildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkPreview = "UpsideDownCake"'), flush: true ); expect(buildGradleFile.readAsStringSync(), contains('compileSdkPreview = "UpsideDownCake"')); final ProcessResult result = await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', '--debug', ], workingDirectory: exampleAppDir.path); expect(exampleAppDir.childDirectory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('apk') .childDirectory('debug') .childFile('app-debug.apk').existsSync(), true); expect(result.stdout, contains('Built $builtApkPath')); }, ); test( 'build succeeds when both example app and plugin target compileSdkPreview', () async { final File appBuildGradleFile = exampleAppDir.childDirectory('android').childDirectory('app').childFile('build.gradle'); // write a build.gradle with compileSdkPreview as `UpsideDownCake` which is a string preview version appBuildGradleFile.writeAsStringSync( appBuildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkPreview = "UpsideDownCake"'), flush: true ); expect(appBuildGradleFile.readAsStringSync(), contains('compileSdkPreview = "UpsideDownCake"')); final File pluginBuildGradleFile = pluginDir.childDirectory('android').childFile('build.gradle'); // change the plugin build.gradle to use a preview compile sdk version pluginBuildGradleFile.writeAsStringSync( pluginBuildGradleFile.readAsStringSync().replaceFirst(compileSdkVersionMatch, 'compileSdkPreview "UpsideDownCake"'), flush: true ); expect(pluginBuildGradleFile.readAsStringSync(), contains('compileSdkPreview "UpsideDownCake"')); final ProcessResult result = await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', '--debug', ], workingDirectory: exampleAppDir.path); expect(exampleAppDir.childDirectory('build') .childDirectory('app') .childDirectory('outputs') .childDirectory('apk') .childDirectory('debug') .childFile('app-debug.apk').existsSync(), true); expect(result.stdout, contains('Built $builtApkPath')); }, ); }
flutter/packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/android_preview_integration.shard/flutter_build_preview_sdk_test.dart", "repo_id": "flutter", "token_count": 1998 }
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:file/memory.dart'; import 'package:file_testing/file_testing.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/cache.dart'; import 'package:flutter_tools/src/commands/build_windows.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/windows/build_windows.dart'; import 'package:flutter_tools/src/windows/visual_studio.dart'; import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fakes.dart'; import '../../src/test_flutter_command_runner.dart'; const String flutterRoot = r'C:\flutter'; const String buildFilePath = r'windows\CMakeLists.txt'; const String visualStudioPath = r'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community'; const String _cmakePath = visualStudioPath + r'\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'; const String _defaultGenerator = 'Visual Studio 16 2019'; final Platform windowsPlatform = FakePlatform( operatingSystem: 'windows', environment: <String, String>{ 'PROGRAMFILES(X86)': r'C:\Program Files (x86)\', 'FLUTTER_ROOT': flutterRoot, 'USERPROFILE': '/', } ); final Platform notWindowsPlatform = FakePlatform( environment: <String, String>{ 'FLUTTER_ROOT': flutterRoot, } ); void main() { late FileSystem fileSystem; late ProcessManager processManager; late TestUsage usage; late FakeAnalytics fakeAnalytics; setUpAll(() { Cache.disableLocking(); Cache.flutterRoot = ''; }); setUp(() { fileSystem = MemoryFileSystem.test(style: FileSystemStyle.windows); Cache.flutterRoot = flutterRoot; usage = TestUsage(); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); }); // Creates the mock files necessary to look like a Flutter project. void setUpMockCoreProjectFiles() { fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').createSync(); fileSystem.file(fileSystem.path.join('lib', 'main.dart')).createSync(recursive: true); } // Creates the mock files necessary to run a build. void setUpMockProjectFilesForBuild() { fileSystem.file(buildFilePath).createSync(recursive: true); setUpMockCoreProjectFiles(); } // Returns the command matching the build_windows call to generate CMake // files. FakeCommand cmakeGenerationCommand({ void Function(List<String> command)? onRun, String generator = _defaultGenerator, TargetPlatform targetPlatform = TargetPlatform.windows_x64, }) { return FakeCommand( command: <String>[ _cmakePath, '-S', fileSystem.path.absolute(fileSystem.path.dirname(buildFilePath)), '-B', r'C:\build\windows\x64', '-G', generator, '-A', getCmakeWindowsArch(targetPlatform), '-DFLUTTER_TARGET_PLATFORM=windows-x64', ], onRun: onRun, ); } // Returns the command matching the build_windows call to build. FakeCommand buildCommand(String buildMode, { bool verbose = false, void Function(List<String> command)? onRun, String stdout = '', }) { return FakeCommand( command: <String>[ _cmakePath, '--build', r'C:\build\windows\x64', '--config', buildMode, ...<String>['--target', 'INSTALL'], if (verbose) '--verbose', ], environment: <String, String>{ if (verbose) 'VERBOSE_SCRIPT_LOGGING': 'true', }, onRun: onRun, stdout: stdout, ); } testUsingContext('Windows build fails when there is no cmake path', () async { final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = FakeVisualStudio(cmakePath: null); setUpMockProjectFilesForBuild(); expect(createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ), throwsToolExit()); }, overrides: <Type, Generator>{ Platform: () => windowsPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build fails when there is no windows project', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockCoreProjectFiles(); expect(createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ), throwsToolExit(message: 'No Windows desktop project configured. See ' 'https://docs.flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app ' 'to learn about adding Windows support to a project.')); }, overrides: <Type, Generator>{ Platform: () => windowsPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build fails on non windows platform', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); expect(createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ), throwsToolExit(message: '"build windows" only supported on Windows hosts.')); }, overrides: <Type, Generator>{ Platform: () => notWindowsPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build fails when feature is disabled', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); expect(createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ), throwsToolExit(message: '"build windows" is not currently supported. To enable, run "flutter config --enable-windows-desktop".')); }, overrides: <Type, Generator>{ Platform: () => windowsPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('Windows build does not spew stdout to status logger', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release', stdout: 'STDOUT STUFF', ), ]); await createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ); expect(testLogger.statusText, isNot(contains('STDOUT STUFF'))); expect(testLogger.traceText, contains('STDOUT STUFF')); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build sends timing events', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ); expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'windows-cmake-generation', ), true, ); expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'windows-cmake-build', ), true, ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), Analytics: () => fakeAnalytics, }); testUsingContext('Windows build extracts errors from stdout', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); // This contains a mix of routine build output and various types of errors // (compile error, link error, warning treated as an error) from MSBuild, // edited down for compactness. For instance, where similar lines are // repeated in actual output, one or two representative lines are chosen // to be included here. const String stdout = r''' Microsoft (R) Build Engine version 16.6.0+5ff7b0c9e for .NET Framework Copyright (C) Microsoft Corporation. All rights reserved. Checking Build System Generating C:/foo/windows/x64/flutter/ephemeral/flutter_windows.dll, [etc], _phony_ Building Custom Rule C:/foo/windows/x64/flutter/CMakeLists.txt standard_codec.cc Generating Code... flutter_wrapper_plugin.vcxproj -> C:\foo\build\windows\x64\flutter\Debug\flutter_wrapper_plugin.lib C:\foo\windows\x64\runner\main.cpp(18): error C2220: the following warning is treated as an error [C:\foo\build\windows\x64\runner\test.vcxproj] C:\foo\windows\x64\runner\main.cpp(18): warning C4706: assignment within conditional expression [C:\foo\build\windows\x64\runner\test.vcxproj] main.obj : error LNK2019: unresolved external symbol "void __cdecl Bar(void)" (?Bar@@YAXXZ) referenced in function wWinMain [C:\foo\build\windows\x64\runner\test.vcxproj] C:\foo\build\windows\x64\runner\Debug\test.exe : fatal error LNK1120: 1 unresolved externals [C:\foo\build\windows\x64\runner\test.vcxproj] Building Custom Rule C:/foo/windows/x64/runner/CMakeLists.txt flutter_window.cpp main.cpp C:\foo\windows\x64\runner\main.cpp(17,1): error C2065: 'Baz': undeclared identifier [C:\foo\build\windows\x64\runner\test.vcxproj] -- Install configuration: "Debug" -- Installing: C:/foo/build/windows/x64/runner/Debug/data/icudtl.dat '''; processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release', stdout: stdout, ), ]); await createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ); // Just the warnings and errors should be surfaced. expect(testLogger.errorText, r''' C:\foo\windows\x64\runner\main.cpp(18): error C2220: the following warning is treated as an error [C:\foo\build\windows\x64\runner\test.vcxproj] C:\foo\windows\x64\runner\main.cpp(18): warning C4706: assignment within conditional expression [C:\foo\build\windows\x64\runner\test.vcxproj] main.obj : error LNK2019: unresolved external symbol "void __cdecl Bar(void)" (?Bar@@YAXXZ) referenced in function wWinMain [C:\foo\build\windows\x64\runner\test.vcxproj] C:\foo\build\windows\x64\runner\Debug\test.exe : fatal error LNK1120: 1 unresolved externals [C:\foo\build\windows\x64\runner\test.vcxproj] C:\foo\windows\x64\runner\main.cpp(17,1): error C2065: 'Baz': undeclared identifier [C:\foo\build\windows\x64\runner\test.vcxproj] '''); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows verbose build sets VERBOSE_SCRIPT_LOGGING', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release', verbose: true, stdout: 'STDOUT STUFF', ), ]); await createTestCommandRunner(command).run( const <String>['windows', '--no-pub', '-v'] ); expect(testLogger.statusText, contains('STDOUT STUFF')); expect(testLogger.traceText, isNot(contains('STDOUT STUFF'))); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build works around CMake generation bug', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(displayVersion: '17.1.0'); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); fileSystem.file(fileSystem.path.join('lib', 'other.dart')) .createSync(recursive: true); fileSystem.file(fileSystem.path.join('foo', 'bar.sksl.json')) .createSync(recursive: true); // Relevant portions of an incorrectly generated project, with some // irrelevant details removed for length. const String fakeBadProjectContent = r''' <?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="17.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <CustomBuild Include="somepath\build\windows\x64\CMakeFiles\8b570225f626c250e12bc1ede88babae\flutter_windows.dll.rule"> <Message Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Debug endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Profile|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Profile|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Debug endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Debug endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Profile endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Profile|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Profile|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Profile endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Profile endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Release endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Profile|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Profile|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Release endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> <Message Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Generating some files</Message> <Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">setlocal "C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" -E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64 Release endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone :cmErrorLevel exit /b %1 :cmDone if %errorlevel% neq 0 goto :VCEnd</Command> </CustomBuild> </ItemGroup> </Project> '''; final File assembleProject = fileSystem.currentDirectory .childDirectory('build') .childDirectory('windows') .childDirectory('x64') .childDirectory('flutter') .childFile('flutter_assemble.vcxproj'); assembleProject.createSync(recursive: true); assembleProject.writeAsStringSync(fakeBadProjectContent); await createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ); final List<String> projectLines = assembleProject.readAsLinesSync(); const String commandBase = r'"C:\Program Files\Microsoft Visual Studio\2022\Professional\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe" ' r'-E env FOO=bar C:/src/flutter/packages/flutter_tools/bin/tool_backend.bat windows-x64'; // The duplicate commands will still be present, but with the order matching // the condition order (cycling through the configurations), rather than // three copies of Debug, then three copies of Profile, then three copies // of Release. expect(projectLines, containsAllInOrder(<String>[ '$commandBase Debug\r', '$commandBase Profile\r', '$commandBase Release\r', '$commandBase Debug\r', '$commandBase Profile\r', '$commandBase Release\r', '$commandBase Debug\r', '$commandBase Profile\r', '$commandBase Release\r', ])); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build invokes build and writes generated files', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); fileSystem.file(fileSystem.path.join('lib', 'other.dart')) .createSync(recursive: true); fileSystem.file(fileSystem.path.join('foo', 'bar.sksl.json')) .createSync(recursive: true); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', '--track-widget-creation', '--obfuscate', '--tree-shake-icons', '--enable-experiment=non-nullable', r'--split-debug-info=C:\foo\', '--dart-define=foo=a', '--dart-define=bar=b', r'--bundle-sksl-path=foo\bar.sksl.json', r'--target=lib\other.dart', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); // Backslashes are escaped in the file, which is why this uses both raw // strings and double backslashes. expect(configLines, containsAll(<String>[ r'file(TO_CMAKE_PATH "C:\\flutter" FLUTTER_ROOT)', r'file(TO_CMAKE_PATH "C:\\" PROJECT_DIR)', r'set(FLUTTER_VERSION "1.0.0" PARENT_SCOPE)', r'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', r'set(FLUTTER_VERSION_MINOR 0 PARENT_SCOPE)', r'set(FLUTTER_VERSION_PATCH 0 PARENT_SCOPE)', r'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)', r' "DART_DEFINES=Zm9vPWE=,YmFyPWI="', r' "DART_OBFUSCATION=true"', r' "EXTRA_FRONT_END_OPTIONS=--enable-experiment=non-nullable"', r' "EXTRA_GEN_SNAPSHOT_OPTIONS=--enable-experiment=non-nullable"', r' "SPLIT_DEBUG_INFO=C:\\foo\\"', r' "TRACK_WIDGET_CREATION=true"', r' "TREE_SHAKE_ICONS=true"', r' "FLUTTER_ROOT=C:\\flutter"', r' "PROJECT_DIR=C:\\"', r' "FLUTTER_TARGET=lib\\other.dart"', r' "BUNDLE_SKSL_PATH=foo\\bar.sksl.json"', ])); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows profile build passes Profile configuration', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Profile'), ]); await createTestCommandRunner(command).run( const <String>['windows', '--profile', '--no-pub'] ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build passes correct generator', () async { const String generator = 'A different generator'; final FakeVisualStudio fakeVisualStudio = FakeVisualStudio( cmakeGenerator: generator); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(generator: generator), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>['windows', '--release', '--no-pub'] ); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext("Windows build uses pubspec's version", () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); fileSystem.file('pubspec.yaml') ..createSync() ..writeAsStringSync('version: 1.2.3+4'); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); expect(configLines, containsAll(<String>[ 'set(FLUTTER_VERSION "1.2.3+4" PARENT_SCOPE)', 'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', 'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)', 'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)', 'set(FLUTTER_VERSION_BUILD 4 PARENT_SCOPE)', ])); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build uses build-name and build-number', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', '--build-name=1.2.3', '--build-number=4', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); expect(configLines, containsAll(<String>[ 'set(FLUTTER_VERSION "1.2.3+4" PARENT_SCOPE)', 'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', 'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)', 'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)', 'set(FLUTTER_VERSION_BUILD 4 PARENT_SCOPE)', ])); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build build-name overrides pubspec', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); fileSystem.file('pubspec.yaml') ..createSync() ..writeAsStringSync('version: 9.9.9+9'); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', '--build-name=1.2.3', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); expect(configLines, containsAll(<String>[ 'set(FLUTTER_VERSION "1.2.3" PARENT_SCOPE)', 'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', 'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)', 'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)', 'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)', ])); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build build-number overrides pubspec', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); fileSystem.file('pubspec.yaml') ..createSync() ..writeAsStringSync('version: 1.2.3+9'); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', '--build-number=4', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); expect(configLines, containsAll(<String>[ 'set(FLUTTER_VERSION "1.2.3+4" PARENT_SCOPE)', 'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', 'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)', 'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)', 'set(FLUTTER_VERSION_BUILD 4 PARENT_SCOPE)', ])); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build build-name and build-number override pubspec', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); fileSystem.file('pubspec.yaml') ..createSync() ..writeAsStringSync('version: 9.9.9+9'); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', '--build-name=1.2.3', '--build-number=4', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); expect(configLines, containsAll(<String>[ 'set(FLUTTER_VERSION "1.2.3+4" PARENT_SCOPE)', 'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', 'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)', 'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)', 'set(FLUTTER_VERSION_BUILD 4 PARENT_SCOPE)', ])); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build warns on non-numeric build-number', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', '--build-name=1.2.3', '--build-number=hello', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); expect(configLines, containsAll(<String>[ 'set(FLUTTER_VERSION "1.2.3+hello" PARENT_SCOPE)', 'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', 'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)', 'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)', 'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)', ])); expect(testLogger.warningText, contains( 'Warning: build identifier hello in version 1.2.3+hello is not numeric and ' 'cannot be converted into a Windows build version number. Defaulting to 0.\n' 'This may cause issues with Windows installers.' )); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Windows build warns on complex build-number', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release'), ]); await createTestCommandRunner(command).run( const <String>[ 'windows', '--no-pub', '--build-name=1.2.3', '--build-number=4.5', ] ); final File cmakeConfig = fileSystem.currentDirectory .childDirectory('windows') .childDirectory('flutter') .childDirectory('ephemeral') .childFile('generated_config.cmake'); expect(cmakeConfig, exists); final List<String> configLines = cmakeConfig.readAsLinesSync(); expect(configLines, containsAll(<String>[ 'set(FLUTTER_VERSION "1.2.3+4.5" PARENT_SCOPE)', 'set(FLUTTER_VERSION_MAJOR 1 PARENT_SCOPE)', 'set(FLUTTER_VERSION_MINOR 2 PARENT_SCOPE)', 'set(FLUTTER_VERSION_PATCH 3 PARENT_SCOPE)', 'set(FLUTTER_VERSION_BUILD 0 PARENT_SCOPE)', ])); expect(testLogger.warningText, contains( 'Warning: build identifier 4.5 in version 1.2.3+4.5 is not numeric and ' 'cannot be converted into a Windows build version number. Defaulting to 0.\n' 'This may cause issues with Windows installers.' )); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('hidden when not enabled on Windows host', () { expect(BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()).hidden, true); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Platform: () => windowsPlatform, }); testUsingContext('Not hidden when enabled and on Windows host', () { expect(BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()).hidden, false); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), Platform: () => windowsPlatform, }); testUsingContext('Performs code size analysis and sends analytics', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); fileSystem.file(r'build\windows\x64\runner\Release\app.so') ..createSync(recursive: true) ..writeAsBytesSync(List<int>.generate(10000, (int index) => 0)); processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release', onRun: (_) { fileSystem.file(r'build\flutter_size_01\snapshot.windows-x64.json') ..createSync(recursive: true) ..writeAsStringSync(''' [ { "l": "dart:_internal", "c": "SubListIterable", "n": "[Optimized] skip", "s": 2400 } ]'''); fileSystem.file(r'build\flutter_size_01\trace.windows-x64.json') ..createSync(recursive: true) ..writeAsStringSync('{}'); }), ]); await createTestCommandRunner(command).run( const <String>['windows', '--no-pub', '--analyze-size'] ); expect(testLogger.statusText, contains('A summary of your Windows bundle analysis can be found at')); expect(testLogger.statusText, contains('dart devtools --appSizeBase=')); expect(usage.events, contains( const TestUsageEvent('code-size-analysis', 'windows'), )); expect(fakeAnalytics.sentEvents, contains( Event.codeSizeAnalysis(platform: 'windows') )); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FileSystemUtils: () => FileSystemUtils(fileSystem: fileSystem, platform: windowsPlatform), Usage: () => usage, Analytics: () => fakeAnalytics, }); // Confirms that running for Windows in a directory with a // bad character (' in this case) throws the desired error message // If the issue https://github.com/flutter/flutter/issues/104802 ever // is resolved on the VS side, we can allow these paths again testUsingContext('Test bad path characters', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; fileSystem.currentDirectory = fileSystem.directory("test_'path") ..createSync(); final String absPath = fileSystem.currentDirectory.absolute.path; setUpMockCoreProjectFiles(); expect( createTestCommandRunner(command).run(const <String>['windows', '--no-pub']), throwsToolExit( message: 'Path $absPath contains invalid characters in "\'#!\$^&*=|,;<>?". ' 'Please rename your directory so as to not include any of these characters ' 'and retry.', ), ); }, overrides: <Type, Generator>{ Platform: () => windowsPlatform, FileSystem: () => fileSystem, ProcessManager: () => FakeProcessManager.any(), FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); // Tests the case where stdout contains the error about pubspec.yaml // And tests the case where stdout contains the error about missing assets testUsingContext('Windows build extracts errors related to pubspec.yaml from stdout', () async { final FakeVisualStudio fakeVisualStudio = FakeVisualStudio(); final BuildWindowsCommand command = BuildWindowsCommand(logger: BufferLogger.test(), operatingSystemUtils: FakeOperatingSystemUtils()) ..visualStudioOverride = fakeVisualStudio; setUpMockProjectFilesForBuild(); const String stdout = r''' Error detected in pubspec.yaml: No file or variants found for asset: images/a_dot_burr.jpeg. '''; processManager = FakeProcessManager.list(<FakeCommand>[ cmakeGenerationCommand(), buildCommand('Release', stdout: stdout, ), ]); await createTestCommandRunner(command).run( const <String>['windows', '--no-pub'] ); // Just the warnings and errors should be surfaced. expect(testLogger.errorText, r''' Error detected in pubspec.yaml: No file or variants found for asset: images/a_dot_burr.jpeg. '''); }, overrides: <Type, Generator>{ FileSystem: () => fileSystem, ProcessManager: () => processManager, Platform: () => windowsPlatform, FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); } class FakeVisualStudio extends Fake implements VisualStudio { FakeVisualStudio({ this.cmakePath = _cmakePath, this.cmakeGenerator = 'Visual Studio 16 2019', this.displayVersion = '17.0.0' }); @override final String? cmakePath; @override final String cmakeGenerator; @override final String displayVersion; }
flutter/packages/flutter_tools/test/commands.shard/hermetic/build_windows_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/build_windows_test.dart", "repo_id": "flutter", "token_count": 15288 }
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 'dart:async'; import 'package:flutter_tools/src/base/common.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/commands/logs.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:test/fake.dart'; import '../../src/context.dart'; import '../../src/fake_devices.dart'; import '../../src/test_flutter_command_runner.dart'; void main() { group('logs', () { late Platform platform; late FakeDeviceManager deviceManager; const String deviceId = 'abc123'; setUp(() { Cache.disableLocking(); deviceManager = FakeDeviceManager(); platform = FakePlatform(); }); tearDown(() { Cache.enableLocking(); }); testUsingContext('fail with a bad device id', () async { final LogsCommand command = LogsCommand( sigterm: FakeProcessSignal(), sigint: FakeProcessSignal(), ); await expectLater( () => createTestCommandRunner(command).run(<String>['-d', 'abc123', 'logs']), throwsA(isA<ToolExit>().having((ToolExit error) => error.exitCode, 'exitCode', anyOf(isNull, 1))), ); }); testUsingContext('does not try to complete exitCompleter multiple times', () async { final FakeDevice fakeDevice = FakeDevice('phone', deviceId); deviceManager.attachedDevices.add(fakeDevice); final FakeProcessSignal termSignal = FakeProcessSignal(); final FakeProcessSignal intSignal = FakeProcessSignal(); final LogsCommand command = LogsCommand( sigterm: termSignal, sigint: intSignal, ); final Future<void> commandFuture = createTestCommandRunner(command).run(<String>['-d', deviceId, 'logs']); intSignal.send(1); termSignal.send(1); await pumpEventQueue(times: 5); await commandFuture; }, overrides: <Type, Generator>{ Platform: () => platform, DeviceManager: () => deviceManager, }); }); } class FakeProcessSignal extends Fake implements ProcessSignal { late final StreamController<ProcessSignal> _controller = StreamController<ProcessSignal>(); @override Stream<ProcessSignal> watch() => _controller.stream; @override bool send(int pid) { _controller.add(this); return true; } }
flutter/packages/flutter_tools/test/commands.shard/hermetic/logs_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/logs_test.dart", "repo_id": "flutter", "token_count": 908 }
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 'dart:async'; import 'dart:convert'; import 'dart:io' as io; import 'package:args/command_runner.dart'; import 'package:file/memory.dart'; import 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/android/gradle_utils.dart' show templateAndroidGradlePluginVersion, templateAndroidGradlePluginVersionForModule, templateDefaultGradleVersion; import 'package:flutter_tools/src/android/java.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/net.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/version.dart' as software; 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/commands/create_base.dart'; import 'package:flutter_tools/src/dart/pub.dart'; import 'package:flutter_tools/src/features.dart'; import 'package:flutter_tools/src/flutter_project_metadata.dart' show FlutterProjectType; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/version.dart'; import 'package:process/process.dart'; import 'package:pub_semver/pub_semver.dart'; import 'package:pubspec_parse/pubspec_parse.dart'; import 'package:unified_analytics/unified_analytics.dart'; import 'package:uuid/uuid.dart'; import 'package:yaml/yaml.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fake_http_client.dart'; import '../../src/fakes.dart'; import '../../src/pubspec_schema.dart'; import '../../src/test_flutter_command_runner.dart'; const String _kNoPlatformsMessage = "You've created a plugin project that doesn't yet support any platforms.\n"; const String frameworkRevision = '12345678'; const String frameworkChannel = 'omega'; const String _kDisabledPlatformRequestedMessage = 'currently not supported on your local environment.'; const String _kIncompatibleJavaVersionMessage = 'The configured version of Java detected may conflict with the'; final String _kIncompatibleAgpVersionForModule = Version.parse(templateAndroidGradlePluginVersion) < Version.parse(templateAndroidGradlePluginVersionForModule) ? templateAndroidGradlePluginVersionForModule : templateAndroidGradlePluginVersion; // This needs to be created from the local platform due to re-entrant flutter calls made in this test. FakePlatform _kNoColorTerminalPlatform() => FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false; FakePlatform _kNoColorTerminalMacOSPlatform() => FakePlatform.fromPlatform(const LocalPlatform()) ..stdoutSupportsAnsi = false ..operatingSystem = 'macos'; final Map<Type, Generator> noColorTerminalOverride = <Type, Generator>{ Platform: _kNoColorTerminalPlatform, }; const String samplesIndexJson = ''' [ { "id": "sample1" }, { "id": "sample2" } ]'''; void main() { late Directory tempDir; late Directory projectDir; late FakeFlutterVersion fakeFlutterVersion; late LoggingProcessManager loggingProcessManager; late FakeProcessManager fakeProcessManager; late BufferLogger logger; late FakeStdio mockStdio; late FakeAnalytics fakeAnalytics; setUpAll(() async { Cache.disableLocking(); await _ensureFlutterToolsSnapshot(); }); setUp(() { loggingProcessManager = LoggingProcessManager(); logger = BufferLogger.test(); tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_create_test.'); projectDir = tempDir.childDirectory('flutter_project'); fakeFlutterVersion = FakeFlutterVersion( frameworkRevision: frameworkRevision, branch: frameworkChannel, ); fakeProcessManager = FakeProcessManager.empty(); mockStdio = FakeStdio(); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: MemoryFileSystem.test(), fakeFlutterVersion: fakeFlutterVersion, ); }); tearDown(() { tryToDelete(tempDir); }); tearDownAll(() async { await _restoreFlutterToolsSnapshot(); }); test('createAndroidIdentifier emits a valid identifier', () { final String identifier = CreateBase.createAndroidIdentifier('42org', '8project'); expect(identifier.contains('.'), isTrue); final RegExp startsWithLetter = RegExp(r'^[a-zA-Z][\w]*$'); final List<String> segments = identifier.split('.'); for (final String segment in segments) { expect(startsWithLetter.hasMatch(segment), isTrue); } }); test('createUTIIdentifier emits a valid identifier', () { final String identifier = CreateBase.createUTIIdentifier('org@', 'project'); expect(identifier.contains('.'), isTrue); expect(identifier.contains('@'), isFalse); }); test('createWindowsIdentifier emits a GUID', () { final String identifier = CreateBase.createWindowsIdentifier('org', 'project'); expect(Uuid.isValidUUID(fromString: identifier), isTrue); }); testUsingContext('tool exits on Windows if given a drive letter without a path', () async { // Must use LocalFileSystem as it is dependent on dart:io handling of // Windows paths, which the MemoryFileSystem does not implement final Directory workingDir = globals.fs.directory(r'X:\path\to\working\dir'); // Must use [io.IOOverrides] as directory.absolute depends on Directory.current // from dart:io. await io.IOOverrides.runZoned<Future<void>>( () async { // Verify IOOverrides is working expect(io.Directory.current, workingDir); final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); const String driveName = 'X:'; await expectToolExitLater( runner.run(<String>[ 'create', '--project-name', 'test_app', '--offline', driveName, ]), contains('You attempted to create a flutter project at the path "$driveName"'), ); }, getCurrentDirectory: () => workingDir, ); }, overrides: <Type, Generator>{ Logger: () => BufferLogger.test(), }, skip: !io.Platform.isWindows // [intended] relies on Windows file system ); // Verify that we create a default project ('app') that is // well-formed. testUsingContext('can create a default project', () async { await _createAndAnalyzeProject( projectDir, <String>['-i', 'objc', '-a', 'java'], <String>[ 'analysis_options.yaml', 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'flutter_project.iml', 'ios/Flutter/AppFrameworkInfo.plist', 'ios/Runner/AppDelegate.m', 'ios/Runner/GeneratedPluginRegistrant.h', 'ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected]', 'ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png', 'lib/main.dart', ], ); expect(logger.statusText, contains('In order to run your application, type:')); // Check that we're telling them about documentation expect(logger.statusText, contains('https://docs.flutter.dev/')); expect(logger.statusText, contains('https://api.flutter.dev/')); // Check for usage values sent in analytics expect( fakeAnalytics.sentEvents, contains( Event.commandUsageValues( workflow: 'create', commandHasTerminal: false, createAndroidLanguage: 'java', createIosLanguage: 'objc', ), ), ); // Check that the tests run clean return _runFlutterTest(projectDir); }, overrides: <Type, Generator>{ Pub: () => Pub.test( fileSystem: globals.fs, logger: logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), Logger: () => logger, Analytics: () => fakeAnalytics, }); testUsingContext('can create a skeleton (list/detail) app', () async { await _createAndAnalyzeProject( projectDir, <String>['-t', 'skeleton', '-i', 'objc', '-a', 'java', '--implementation-tests'], <String>[ '.dart_tool/flutter_gen/pubspec.yaml', '.dart_tool/flutter_gen/gen_l10n/app_localizations.dart', 'analysis_options.yaml', 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'flutter_project.iml', 'ios/Flutter/AppFrameworkInfo.plist', 'ios/Runner/AppDelegate.m', 'ios/Runner/GeneratedPluginRegistrant.h', 'lib/main.dart', 'l10n.yaml', 'assets/images/2.0x/flutter_logo.png', 'assets/images/flutter_logo.png', 'assets/images/3.0x/flutter_logo.png', 'test/unit_test.dart', 'test/widget_test.dart', 'test/implementation_test.dart', 'lib/src/localization/app_en.arb', 'lib/src/app.dart', 'lib/src/sample_feature/sample_item_details_view.dart', 'lib/src/sample_feature/sample_item_list_view.dart', 'lib/src/sample_feature/sample_item.dart', 'lib/src/settings/settings_controller.dart', 'lib/src/settings/settings_view.dart', 'lib/src/settings/settings_service.dart', 'lib/main.dart', 'pubspec.yaml', 'README.md', ], ); return _runFlutterTest(projectDir); }, 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: mockStdio, ), }); testUsingContext('can create a default project if empty directory exists', () async { await projectDir.create(recursive: true); await _createAndAnalyzeProject( projectDir, <String>['-i', 'objc', '-a', 'java'], <String>[ 'analysis_options.yaml', 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'flutter_project.iml', 'ios/Flutter/AppFrameworkInfo.plist', 'ios/Runner/AppDelegate.m', 'ios/Runner/GeneratedPluginRegistrant.h', ], ); }, 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: mockStdio, ), }); testUsingContext('creates a module project correctly', () async { await _createAndAnalyzeProject(projectDir, <String>[ '--template=module', ], <String>[ '.android/app/', '.gitignore', '.ios/Flutter', '.metadata', 'analysis_options.yaml', 'lib/main.dart', 'pubspec.yaml', 'README.md', 'test/widget_test.dart', ], unexpectedPaths: <String>[ 'android/', 'ios/', ]); return _runFlutterTest(projectDir); }, 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: mockStdio, ), }); testUsingContext('cannot create a project if non-empty non-project directory exists with .metadata', () async { await projectDir.absolute.childDirectory('blag').create(recursive: true); await projectDir.absolute.childFile('.metadata').writeAsString('project_type: blag\n'); expect(() async => _createAndAnalyzeProject( projectDir, <String>[], <String>[], unexpectedPaths: <String>[ 'android/', 'ios/', '.android/', '.ios/', ]), throwsToolExit(message: 'Sorry, unable to detect the type of project to recreate')); }, 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: mockStdio, ), ...noColorTerminalOverride, }); testUsingContext('cannot create a project in flutter root', () async { Cache.flutterRoot = '../..'; final String flutterBin = globals.fs.path.join(getFlutterRoot(), 'bin', globals.platform.isWindows ? 'flutter.bat' : 'flutter'); final ProcessResult exec = await Process.run( flutterBin, <String>[ 'create', 'flutter_project', ], workingDirectory: Cache.flutterRoot, ); expect(exec.exitCode, 2); expect(exec.stderr, contains('Cannot create a project within the Flutter SDK')); }, 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: mockStdio, ), ...noColorTerminalOverride, }); testUsingContext('Will create an app project if non-empty non-project directory exists without .metadata', () async { await projectDir.absolute.childDirectory('blag').create(recursive: true); await projectDir.absolute.childDirectory('.idea').create(recursive: true); await _createAndAnalyzeProject( projectDir, <String>[ '-i', 'objc', '-a', 'java', ], <String>[ 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'flutter_project.iml', 'ios/Flutter/AppFrameworkInfo.plist', 'ios/Runner/AppDelegate.m', 'ios/Runner/GeneratedPluginRegistrant.h', ], unexpectedPaths: <String>[ '.android/', '.ios/', ], ); }, 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: mockStdio, ), }); testUsingContext('detects and recreates an app project correctly', () async { await projectDir.absolute.childDirectory('lib').create(recursive: true); await projectDir.absolute.childDirectory('ios').create(recursive: true); await _createAndAnalyzeProject( projectDir, <String>[ '-i', 'objc', '-a', 'java', ], <String>[ 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'flutter_project.iml', 'ios/Flutter/AppFrameworkInfo.plist', 'ios/Runner/AppDelegate.m', 'ios/Runner/GeneratedPluginRegistrant.h', ], unexpectedPaths: <String>[ '.android/', '.ios/', ], ); }, 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: mockStdio, ), }); testUsingContext('detects and recreates a plugin project correctly', () async { await projectDir.create(recursive: true); await projectDir.absolute.childFile('.metadata').writeAsString('project_type: plugin\n'); await _createAndAnalyzeProject( projectDir, <String>[], <String>[ 'example/lib/main.dart', 'flutter_project.iml', 'lib/flutter_project.dart', ], unexpectedPaths: <String>[ 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java',] ); }, 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: mockStdio, ), }); testUsingContext('detects and recreates a package project correctly', () async { await projectDir.create(recursive: true); await projectDir.absolute.childFile('.metadata').writeAsString('project_type: package\n'); return _createAndAnalyzeProject( projectDir, <String>[], <String>[ 'lib/flutter_project.dart', 'test/flutter_project_test.dart', ], unexpectedPaths: <String>[ 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java', 'example/ios/Runner/AppDelegate.h', 'example/ios/Runner/AppDelegate.m', 'example/ios/Runner/main.m', 'example/lib/main.dart', 'ios/Classes/FlutterProjectPlugin.h', 'ios/Classes/FlutterProjectPlugin.m', 'ios/Runner/AppDelegate.h', 'ios/Runner/AppDelegate.m', 'ios/Runner/main.m', 'lib/main.dart', 'test/widget_test.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: mockStdio, ), }); testUsingContext('kotlin/swift legacy app project', () async { return _createProject( projectDir, <String>['--no-pub', '--template=app', '--android-language=kotlin', '--ios-language=swift'], <String>[ 'android/app/src/main/kotlin/com/example/flutter_project/MainActivity.kt', 'ios/Runner/AppDelegate.swift', 'ios/Runner/Runner-Bridging-Header.h', 'lib/main.dart', '.idea/libraries/KotlinJavaRuntime.xml', ], unexpectedPaths: <String>[ 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'ios/Runner/AppDelegate.h', 'ios/Runner/AppDelegate.m', 'ios/Runner/main.m', ], ); }, 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: mockStdio, ), }); testUsingContext('can create a package project', () async { await _createAndAnalyzeProject( projectDir, <String>['--template=package'], <String>[ 'analysis_options.yaml', 'lib/flutter_project.dart', 'test/flutter_project_test.dart', ], unexpectedPaths: <String>[ 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java', 'example/ios/Runner/AppDelegate.h', 'example/ios/Runner/AppDelegate.m', 'example/ios/Runner/main.m', 'example/lib/main.dart', 'ios/Classes/FlutterProjectPlugin.h', 'ios/Classes/FlutterProjectPlugin.m', 'ios/Runner/AppDelegate.h', 'ios/Runner/AppDelegate.m', 'ios/Runner/GeneratedPluginRegistrant.h', 'ios/Runner/GeneratedPluginRegistrant.m', 'ios/Runner/main.m', 'lib/main.dart', 'test/widget_test.dart', 'windows/flutter/generated_plugin_registrant.cc', 'windows/flutter/generated_plugin_registrant.h', 'windows/flutter/generated_plugins.cmake', 'linux/flutter/generated_plugin_registrant.cc', 'linux/flutter/generated_plugin_registrant.h', 'linux/flutter/generated_plugins.cmake', 'macos/Flutter/GeneratedPluginRegistrant.swift', ], ); return _runFlutterTest(projectDir); }, 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: mockStdio, ), }); testUsingContext('can create a plugin project', () async { await _createAndAnalyzeProject( projectDir, <String>['--template=plugin', '-i', 'objc', '-a', 'java'], <String>[ 'analysis_options.yaml', 'LICENSE', 'README.md', 'example/lib/main.dart', 'flutter_project.iml', 'lib/flutter_project.dart', ], unexpectedPaths: <String>[ 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java', 'lib/flutter_project_web.dart', ], ); return _runFlutterTest(projectDir.childDirectory('example')); }, 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: mockStdio, ), }); testUsingContext('plugin project supports web', () async { await _createAndAnalyzeProject( projectDir, <String>['--template=plugin', '--platform=web'], <String>[ 'lib/flutter_project.dart', 'lib/flutter_project_web.dart', ], ); final String rawPubspec = await projectDir.childFile('pubspec.yaml').readAsString(); final Pubspec pubspec = Pubspec.parse(rawPubspec); // Expect the dependency on flutter_web_plugins exists expect(pubspec.dependencies, contains('flutter_web_plugins')); // The platform is correctly registered final YamlMap web = ((pubspec.flutter!['plugin'] as YamlMap)['platforms'] as YamlMap)['web'] as YamlMap; expect(web['pluginClass'], 'FlutterProjectWeb'); expect(web['fileName'], 'flutter_project_web.dart'); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), Logger: () => logger, }); testUsingContext('plugin example app depends on plugin', () async { await _createProject( projectDir, <String>['--template=plugin', '-i', 'objc', '-a', 'java'], <String>[ 'example/pubspec.yaml', ], ); final String rawPubspec = await projectDir.childDirectory('example').childFile('pubspec.yaml').readAsString(); final Pubspec pubspec = Pubspec.parse(rawPubspec); final String pluginName = projectDir.basename; expect(pubspec.dependencies, contains(pluginName)); expect(pubspec.dependencies[pluginName] is PathDependency, isTrue); final PathDependency pathDependency = pubspec.dependencies[pluginName]! as PathDependency; expect(pathDependency.path, '../'); }, 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: mockStdio, ), }); testUsingContext('plugin example app includes an integration test', () async { await _createAndAnalyzeProject( projectDir, <String>['--template=plugin'], <String>[ 'example/integration_test/plugin_integration_test.dart', ], ); return _runFlutterTest(projectDir.childDirectory('example')); }, 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: mockStdio, ), }); testUsingContext('kotlin/swift plugin project', () async { return _createProject( projectDir, <String>['--no-pub', '--template=plugin', '-a', 'kotlin', '--ios-language', 'swift', '--platforms', 'ios,android'], <String>[ 'analysis_options.yaml', 'android/src/main/kotlin/com/example/flutter_project/FlutterProjectPlugin.kt', 'example/android/app/src/main/kotlin/com/example/flutter_project_example/MainActivity.kt', 'example/ios/Runner/AppDelegate.swift', 'example/ios/Runner/Runner-Bridging-Header.h', 'example/lib/main.dart', 'ios/Classes/FlutterProjectPlugin.swift', 'lib/flutter_project.dart', ], unexpectedPaths: <String>[ 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java', 'example/ios/Runner/AppDelegate.h', 'example/ios/Runner/AppDelegate.m', 'example/ios/Runner/main.m', 'ios/Classes/FlutterProjectPlugin.h', 'ios/Classes/FlutterProjectPlugin.m', ], ); }); testUsingContext('plugin project with custom org', () async { return _createProject( projectDir, <String>[ '--no-pub', '--template=plugin', '--org', 'com.bar.foo', '-i', 'objc', '-a', 'java', '--platform', 'android', ], <String>[ 'android/src/main/java/com/bar/foo/flutter_project/FlutterProjectPlugin.java', 'example/android/app/src/main/java/com/bar/foo/flutter_project_example/MainActivity.java', ], unexpectedPaths: <String>[ 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java', ], ); }); testUsingContext('plugin project with valid custom project name', () async { return _createProject( projectDir, <String>[ '--no-pub', '--template=plugin', '--project-name', 'xyz', '-i', 'objc', '-a', 'java', '--platforms', 'android,ios', ], <String>[ 'android/src/main/java/com/example/xyz/XyzPlugin.java', 'example/android/app/src/main/java/com/example/xyz_example/MainActivity.java', ], unexpectedPaths: <String>[ 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java', ], ); }); testUsingContext('plugin project with invalid custom project name', () async { expect( () => _createProject(projectDir, <String>['--no-pub', '--template=plugin', '--project-name', 'xyz-xyz', '--platforms', 'android,ios',], <String>[], ), allOf( throwsToolExit(message: '"xyz-xyz" is not a valid Dart package name.'), throwsToolExit(message: 'Try "xyz_xyz" instead.'), ), ); }); testUsingContext('module project with pub', () async { return _createProject(projectDir, <String>[ '--template=module', ], <String>[ '.android/build.gradle', '.android/Flutter/build.gradle', '.android/Flutter/flutter.iml', '.android/Flutter/src/main/AndroidManifest.xml', '.android/Flutter/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', '.android/gradle.properties', '.android/gradle/wrapper/gradle-wrapper.jar', '.android/gradle/wrapper/gradle-wrapper.properties', '.android/gradlew', '.android/gradlew.bat', '.android/include_flutter.groovy', '.android/local.properties', '.android/settings.gradle', '.gitignore', '.metadata', '.dart_tool/package_config.json', 'analysis_options.yaml', 'lib/main.dart', 'pubspec.lock', 'pubspec.yaml', 'README.md', 'test/widget_test.dart', ], unexpectedPaths: <String>[ 'android/', 'ios/', '.android/Flutter/src/main/java/io/flutter/facade/FlutterFragment.java', '.android/Flutter/src/main/java/io/flutter/facade/Flutter.java', ]); }, 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: mockStdio, ), }); testUsingContext('androidx is used by default in an app project', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', projectDir.path]); void expectExists(String relPath) { expect(globals.fs.isFileSync('${projectDir.path}/$relPath'), true); } expectExists('android/gradle.properties'); final String actualContents = await globals.fs.file('${projectDir.path}/android/gradle.properties').readAsString(); expect(actualContents.contains('useAndroidX'), true); }); testUsingContext('androidx is used by default in a module project', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=module', '--no-pub', projectDir.path]); final FlutterProject project = FlutterProject.fromDirectory(projectDir); expect( project.usesAndroidX, true, ); }); testUsingContext('creating a new project should create v2 embedding and never show an Android v1 deprecation warning', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--platform', 'android', projectDir.path]); final String androidManifest = await globals.fs.file( '${projectDir.path}/android/app/src/main/AndroidManifest.xml' ).readAsString(); expect(androidManifest.contains('android:name="flutterEmbedding"'), true); expect(androidManifest.contains('android:value="2"'), true); final String mainActivity = await globals.fs.file( '${projectDir.path}/android/app/src/main/kotlin/com/example/flutter_project/MainActivity.kt' ).readAsString(); // Import for the new embedding class. expect(mainActivity.contains('import io.flutter.embedding.android.FlutterActivity'), true); expect(logger.statusText, isNot(contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects'))); }, overrides: <Type, Generator>{ Logger: () => logger, }); testUsingContext('app supports android and ios by default', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('android'), exists); expect(projectDir.childDirectory('ios'), exists); }, overrides: <Type, Generator>{}); testUsingContext('app does not include android if disabled in config', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('android'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isAndroidEnabled: false), }); testUsingContext('app does not include ios if disabled in config', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('ios'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isIOSEnabled: false), }); testUsingContext('app does not include desktop or web by default', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('web'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('plugin does not include desktop or web by default', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run( <String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(projectDir.childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('web'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('web'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('app supports Linux if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--platform=linux', projectDir.path, ]); expect(projectDir.childDirectory('linux').childFile('CMakeLists.txt'), exists); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('web'), isNot(exists)); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), Logger: () => logger, }); testUsingContext('plugin supports Linux if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=linux', projectDir.path]); expect( projectDir.childDirectory('linux').childFile('CMakeLists.txt'), exists); expect( projectDir.childDirectory('example').childDirectory('linux'), exists); expect(projectDir.childDirectory('example').childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('web'), isNot(exists)); validatePubspecForPlugin( projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'linux', ], pluginClass: 'FlutterProjectPlugin', unexpectedPlatforms: <String>['some_platform']); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), Logger: () => logger, }); testUsingContext('app supports macOS if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--platform=macos', projectDir.path, ]); expect( projectDir.childDirectory('macos').childDirectory('Runner.xcworkspace'), exists); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('web'), isNot(exists)); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Logger: () => logger, }); testUsingContext('plugin supports macOS if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=macos', projectDir.path]); expect(projectDir.childDirectory('macos').childFile('flutter_project.podspec'), exists); expect( projectDir.childDirectory('example').childDirectory('macos'), exists); expect(projectDir.childDirectory('example').childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('web'), isNot(exists)); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'macos', ], pluginClass: 'FlutterProjectPlugin', unexpectedPlatforms: <String>['some_platform']); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Logger: () => logger, }); testUsingContext('app supports Windows if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--platform=windows', projectDir.path, ]); expect(projectDir.childDirectory('windows').childFile('CMakeLists.txt'), exists); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('web'), isNot(exists)); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), Logger: () => logger, }); testUsingContext('Windows has correct VERSIONINFO', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--org', 'com.foo.bar', projectDir.path]); final File resourceFile = projectDir.childDirectory('windows').childDirectory('runner').childFile('Runner.rc'); expect(resourceFile, exists); final String contents = resourceFile.readAsStringSync(); expect(contents, contains('"CompanyName", "com.foo.bar"')); expect(contents, contains('"FileDescription", "flutter_project"')); expect(contents, contains('"ProductName", "flutter_project"')); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('plugin supports Windows if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=windows', projectDir.path]); expect(projectDir.childDirectory('windows').childFile('CMakeLists.txt'), exists); expect( projectDir.childDirectory('example').childDirectory('windows'), exists); expect( projectDir .childDirectory('example') .childDirectory('android'), isNot(exists)); expect( projectDir.childDirectory('example').childDirectory('ios'), isNot(exists)); expect( projectDir .childDirectory('example') .childDirectory('linux'), isNot(exists)); expect( projectDir .childDirectory('example') .childDirectory('macos'), isNot(exists)); expect( projectDir.childDirectory('example').childDirectory('web'), isNot(exists)); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'windows', ], pluginClass: 'FlutterProjectPluginCApi', unexpectedPlatforms: <String>['some_platform']); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), Logger: () => logger, }); testUsingContext('app supports web if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--platform=web', projectDir.path, ]); expect( projectDir.childDirectory('web').childFile('index.html'), exists); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('windows'), isNot(exists)); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), Logger: () => logger, }); testUsingContext('app creates maskable icons for web', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--platform=web', projectDir.path, ]); final Directory iconsDir = projectDir.childDirectory('web').childDirectory('icons'); expect(iconsDir.childFile('Icon-maskable-192.png'), exists); expect(iconsDir.childFile('Icon-maskable-512.png'), exists); }); testUsingContext('plugin uses new platform schema', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); final String pubspecContents = await globals.fs.directory(projectDir.path).childFile('pubspec.yaml').readAsString(); expect(pubspecContents.contains('platforms:'), true); }); testUsingContext('has correct content and formatting with module template', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=module', '--no-pub', '--org', 'com.foo.bar', projectDir.path]); void expectExists(String relPath, [bool expectation = true]) { expect(globals.fs.isFileSync('${projectDir.path}/$relPath'), expectation); } expectExists('lib/main.dart'); expectExists('test/widget_test.dart'); final String actualContents = await globals.fs.file('${projectDir.path}/test/widget_test.dart').readAsString(); expect(actualContents.contains('flutter_test.dart'), true); for (final FileSystemEntity file in projectDir.listSync(recursive: true)) { if (file is File && file.path.endsWith('.dart')) { final String original = file.readAsStringSync(); final Process process = await Process.start( globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), <String>['format', '--output=show', file.path], workingDirectory: projectDir.path, ); final String formatted = await process.stdout.transform(utf8.decoder).join(); expect(formatted, contains(original), reason: file.path); } } await _runFlutterTest(projectDir, target: globals.fs.path.join(projectDir.path, 'test', 'widget_test.dart')); // Generated Xcode settings final String xcodeConfigPath = globals.fs.path.join('.ios', 'Flutter', 'Generated.xcconfig'); expectExists(xcodeConfigPath); final File xcodeConfigFile = globals.fs.file(globals.fs.path.join(projectDir.path, xcodeConfigPath)); final String xcodeConfig = xcodeConfigFile.readAsStringSync(); expect(xcodeConfig, contains('FLUTTER_ROOT=')); expect(xcodeConfig, contains('FLUTTER_APPLICATION_PATH=')); expect(xcodeConfig, contains('FLUTTER_TARGET=')); expect(xcodeConfig, contains('COCOAPODS_PARALLEL_CODE_SIGN=true')); expect(xcodeConfig, contains('EXCLUDED_ARCHS[sdk=iphoneos*]=armv7')); // Avoid legacy build locations to support Swift Package Manager. expect(xcodeConfig, isNot(contains('SYMROOT'))); // Generated export environment variables script final String buildPhaseScriptPath = globals.fs.path.join('.ios', 'Flutter', 'flutter_export_environment.sh'); expectExists(buildPhaseScriptPath); final File buildPhaseScriptFile = globals.fs.file(globals.fs.path.join(projectDir.path, buildPhaseScriptPath)); final String buildPhaseScript = buildPhaseScriptFile.readAsStringSync(); expect(buildPhaseScript, contains('FLUTTER_ROOT=')); expect(buildPhaseScript, contains('FLUTTER_APPLICATION_PATH=')); expect(buildPhaseScript, contains('FLUTTER_TARGET=')); expect(buildPhaseScript, contains('COCOAPODS_PARALLEL_CODE_SIGN=true')); // Do not override host app build settings. expect(buildPhaseScript, isNot(contains('SYMROOT'))); // App identification final String xcodeProjectPath = globals.fs.path.join('.ios', 'Runner.xcodeproj', 'project.pbxproj'); expectExists(xcodeProjectPath); final File xcodeProjectFile = globals.fs.file(globals.fs.path.join(projectDir.path, xcodeProjectPath)); final String xcodeProject = xcodeProjectFile.readAsStringSync(); expect(xcodeProject, contains('PRODUCT_BUNDLE_IDENTIFIER = com.foo.bar.flutterProject')); expect(xcodeProject, contains('LastUpgradeCheck = 1510;')); // Xcode workspace shared data final Directory workspaceSharedData = globals.fs.directory(globals.fs.path.join('.ios', 'Runner.xcworkspace', 'xcshareddata')); expectExists(workspaceSharedData.childFile('WorkspaceSettings.xcsettings').path); expectExists(workspaceSharedData.childFile('IDEWorkspaceChecks.plist').path); // Xcode project shared data final Directory projectSharedData = globals.fs.directory(globals.fs.path.join('.ios', 'Runner.xcodeproj', 'project.xcworkspace', 'xcshareddata')); expectExists(projectSharedData.childFile('WorkspaceSettings.xcsettings').path); expectExists(projectSharedData.childFile('IDEWorkspaceChecks.plist').path); final String versionPath = globals.fs.path.join('.metadata'); expectExists(versionPath); final String version = globals.fs.file(globals.fs.path.join(projectDir.path, versionPath)).readAsStringSync(); expect(version, contains('version:')); expect(version, contains('revision: "12345678"')); expect(version, contains('channel: "omega"')); // IntelliJ metadata final String intelliJSdkMetadataPath = globals.fs.path.join('.idea', 'libraries', 'Dart_SDK.xml'); expectExists(intelliJSdkMetadataPath); final String sdkMetaContents = globals.fs .file(globals.fs.path.join( projectDir.path, intelliJSdkMetadataPath, )) .readAsStringSync(); expect(sdkMetaContents, contains('<root url="file:/')); expect(sdkMetaContents, contains('/bin/cache/dart-sdk/lib/core"')); }, overrides: <Type, Generator>{ FlutterVersion: () => fakeFlutterVersion, Platform: _kNoColorTerminalPlatform, }); testUsingContext('has correct default content and formatting with app template', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'com.foo.bar', projectDir.path]); void expectExists(String relPath) { expect(globals.fs.isFileSync('${projectDir.path}/$relPath'), true); } expectExists('lib/main.dart'); expectExists('test/widget_test.dart'); for (final FileSystemEntity file in projectDir.listSync(recursive: true)) { if (file is File && file.path.endsWith('.dart')) { final String original = file.readAsStringSync(); final Process process = await Process.start( globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), <String>['format', '--output=show', file.path], workingDirectory: projectDir.path, ); final String formatted = await process.stdout.transform(utf8.decoder).join(); expect(formatted, contains(original), reason: file.path); } } await _runFlutterTest(projectDir, target: globals.fs.path.join(projectDir.path, 'test', 'widget_test.dart')); // Generated Xcode settings final String xcodeConfigPath = globals.fs.path.join('ios', 'Flutter', 'Generated.xcconfig'); expectExists(xcodeConfigPath); final File xcodeConfigFile = globals.fs.file(globals.fs.path.join(projectDir.path, xcodeConfigPath)); final String xcodeConfig = xcodeConfigFile.readAsStringSync(); expect(xcodeConfig, contains('FLUTTER_ROOT=')); expect(xcodeConfig, contains('FLUTTER_APPLICATION_PATH=')); expect(xcodeConfig, contains('COCOAPODS_PARALLEL_CODE_SIGN=true')); expect(xcodeConfig, contains('EXCLUDED_ARCHS[sdk=iphoneos*]=armv7')); // Xcode project final String xcodeProjectPath = globals.fs.path.join('ios', 'Runner.xcodeproj', 'project.pbxproj'); expectExists(xcodeProjectPath); final File xcodeProjectFile = globals.fs.file(globals.fs.path.join(projectDir.path, xcodeProjectPath)); final String xcodeProject = xcodeProjectFile.readAsStringSync(); expect(xcodeProject, contains('PRODUCT_BUNDLE_IDENTIFIER = com.foo.bar.flutterProject')); expect(xcodeProject, contains('LastUpgradeCheck = 1510;')); // Xcode workspace shared data final Directory workspaceSharedData = globals.fs.directory(globals.fs.path.join('ios', 'Runner.xcworkspace', 'xcshareddata')); expectExists(workspaceSharedData.childFile('WorkspaceSettings.xcsettings').path); expectExists(workspaceSharedData.childFile('IDEWorkspaceChecks.plist').path); // Xcode project shared data final Directory projectSharedData = globals.fs.directory(globals.fs.path.join('ios', 'Runner.xcodeproj', 'project.xcworkspace', 'xcshareddata')); expectExists(projectSharedData.childFile('WorkspaceSettings.xcsettings').path); expectExists(projectSharedData.childFile('IDEWorkspaceChecks.plist').path); final String versionPath = globals.fs.path.join('.metadata'); expectExists(versionPath); final String version = globals.fs.file(globals.fs.path.join(projectDir.path, versionPath)).readAsStringSync(); expect(version, contains('version:')); expect(version, contains('revision: "12345678"')); expect(version, contains('channel: "omega"')); // IntelliJ metadata final String intelliJSdkMetadataPath = globals.fs.path.join('.idea', 'libraries', 'Dart_SDK.xml'); expectExists(intelliJSdkMetadataPath); final String sdkMetaContents = globals.fs .file(globals.fs.path.join( projectDir.path, intelliJSdkMetadataPath, )) .readAsStringSync(); expect(sdkMetaContents, contains('<root url="file:/')); expect(sdkMetaContents, contains('/bin/cache/dart-sdk/lib/core"')); }, overrides: <Type, Generator>{ FlutterVersion: () => fakeFlutterVersion, Platform: _kNoColorTerminalPlatform, }); testUsingContext('has iOS development team with app template', () async { Cache.flutterRoot = '../..'; final Completer<void> completer = Completer<void>(); final StreamController<List<int>> controller = StreamController<List<int>>(); const String certificates = ''' 1) 86f7e437faa5a7fce15d1ddcb9eaeaea377667b8 "iPhone Developer: Profile 1 (1111AAAA11)" 1 valid identities found'''; fakeProcessManager.addCommands(<FakeCommand>[ const FakeCommand( command: <String>['which', 'security'], ), const FakeCommand( command: <String>['which', 'openssl'], ), const FakeCommand( command: <String>['security', 'find-identity', '-p', 'codesigning', '-v'], stdout: certificates, ), const FakeCommand( command: <String>['security', 'find-certificate', '-c', '1111AAAA11', '-p'], stdout: 'This is a fake certificate', ), FakeCommand( command: const <String>['openssl', 'x509', '-subject'], stdin: IOSink(controller.sink), stdout: 'subject= /CN=iPhone Developer: Profile 1 (1111AAAA11)/OU=3333CCCC33/O=My Team/C=US', ), ]); controller.stream.listen((List<int> chunk) { completer.complete(); }); final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'com.foo.bar', projectDir.path]); final String xcodeProjectPath = globals.fs.path.join('ios', 'Runner.xcodeproj', 'project.pbxproj'); final File xcodeProjectFile = globals.fs.file(globals.fs.path.join(projectDir.path, xcodeProjectPath)); expect(xcodeProjectFile, exists); final String xcodeProject = xcodeProjectFile.readAsStringSync(); expect(xcodeProject, contains('DEVELOPMENT_TEAM = 3333CCCC33;')); }, overrides: <Type, Generator>{ FlutterVersion: () => fakeFlutterVersion, Java: () => null, Platform: _kNoColorTerminalMacOSPlatform, ProcessManager: () => fakeProcessManager, }); testUsingContext('Correct info.plist key-value pairs for objc iOS project.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'com.foo.bar','--ios-language=objc', '--project-name=my_project', projectDir.path]); final String plistPath = globals.fs.path.join('ios', 'Runner', 'Info.plist'); final File plistFile = globals.fs.file(globals.fs.path.join(projectDir.path, plistPath)); expect(plistFile, exists); final bool disabled = _getBooleanValueFromPlist(plistFile: plistFile, key: 'CADisableMinimumFrameDurationOnPhone'); expect(disabled, isTrue); final bool indirectInput = _getBooleanValueFromPlist(plistFile: plistFile, key: 'UIApplicationSupportsIndirectInputEvents'); expect(indirectInput, isTrue); final String displayName = _getStringValueFromPlist(plistFile: plistFile, key: 'CFBundleDisplayName'); expect(displayName, 'My Project'); }); testUsingContext('Correct info.plist key-value pairs for objc swift project.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'com.foo.bar','--ios-language=swift', '--project-name=my_project', projectDir.path]); final String plistPath = globals.fs.path.join('ios', 'Runner', 'Info.plist'); final File plistFile = globals.fs.file(globals.fs.path.join(projectDir.path, plistPath)); expect(plistFile, exists); final bool disabled = _getBooleanValueFromPlist(plistFile: plistFile, key: 'CADisableMinimumFrameDurationOnPhone'); expect(disabled, isTrue); final bool indirectInput = _getBooleanValueFromPlist(plistFile: plistFile, key: 'UIApplicationSupportsIndirectInputEvents'); expect(indirectInput, isTrue); final String displayName = _getStringValueFromPlist(plistFile: plistFile, key: 'CFBundleDisplayName'); expect(displayName, 'My Project'); }); testUsingContext('Correct info.plist key-value pairs for objc iOS module.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=module', '--org', 'com.foo.bar','--ios-language=objc', '--project-name=my_project', projectDir.path]); final String plistPath = globals.fs.path.join('.ios', 'Runner', 'Info.plist'); final File plistFile = globals.fs.file(globals.fs.path.join(projectDir.path, plistPath)); expect(plistFile, exists); final bool disabled = _getBooleanValueFromPlist(plistFile: plistFile, key: 'CADisableMinimumFrameDurationOnPhone'); expect(disabled, isTrue); final bool indirectInput = _getBooleanValueFromPlist(plistFile: plistFile, key: 'UIApplicationSupportsIndirectInputEvents'); expect(indirectInput, isTrue); final String displayName = _getStringValueFromPlist(plistFile: plistFile, key: 'CFBundleDisplayName'); expect(displayName, 'My Project'); }, 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: mockStdio, ), }); testUsingContext('Correct info.plist key-value pairs for swift iOS module.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=module', '--org', 'com.foo.bar','--ios-language=swift', '--project-name=my_project', projectDir.path]); final String plistPath = globals.fs.path.join('.ios', 'Runner', 'Info.plist'); final File plistFile = globals.fs.file(globals.fs.path.join(projectDir.path, plistPath)); expect(plistFile, exists); final bool disabled = _getBooleanValueFromPlist(plistFile: plistFile, key: 'CADisableMinimumFrameDurationOnPhone'); expect(disabled, isTrue); final bool indirectInput = _getBooleanValueFromPlist(plistFile: plistFile, key: 'UIApplicationSupportsIndirectInputEvents'); expect(indirectInput, isTrue); final String displayName = _getStringValueFromPlist(plistFile: plistFile, key: 'CFBundleDisplayName'); expect(displayName, 'My Project'); }, 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: mockStdio, ), }); testUsingContext('Correct info.plist key-value pairs for swift iOS plugin.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=plugin', '--no-pub', '--org', 'com.foo.bar', '--platforms=ios', '--ios-language=swift', '--project-name=my_project', projectDir.path]); final String plistPath = globals.fs.path.join('example', 'ios', 'Runner', 'Info.plist'); final File plistFile = globals.fs.file(globals.fs.path.join(projectDir.path, plistPath)); expect(plistFile, exists); final bool disabled = _getBooleanValueFromPlist(plistFile: plistFile, key: 'CADisableMinimumFrameDurationOnPhone'); expect(disabled, isTrue); final bool indirectInput = _getBooleanValueFromPlist(plistFile: plistFile, key: 'UIApplicationSupportsIndirectInputEvents'); expect(indirectInput, isTrue); final String displayName = _getStringValueFromPlist(plistFile: plistFile, key: 'CFBundleDisplayName'); expect(displayName, 'My Project'); }); testUsingContext('Correct info.plist key-value pairs for objc iOS plugin.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=plugin', '--no-pub', '--org', 'com.foo.bar', '--platforms=ios', '--ios-language=objc', '--project-name=my_project', projectDir.path]); final String plistPath = globals.fs.path.join('example', 'ios', 'Runner', 'Info.plist'); final File plistFile = globals.fs.file(globals.fs.path.join(projectDir.path, plistPath)); expect(plistFile, exists); final bool disabled = _getBooleanValueFromPlist(plistFile: plistFile, key: 'CADisableMinimumFrameDurationOnPhone'); expect(disabled, isTrue); final bool indirectInput = _getBooleanValueFromPlist(plistFile: plistFile, key: 'UIApplicationSupportsIndirectInputEvents'); expect(indirectInput, isTrue); final String displayName = _getStringValueFromPlist(plistFile: plistFile, key: 'CFBundleDisplayName'); expect(displayName, 'My Project'); }); testUsingContext('has correct content and formatting with macOS app template', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--template=app', '--platforms=macos', '--no-pub', '--org', 'com.foo.bar', projectDir.path]); void expectExists(String relPath) { expect(globals.fs.isFileSync('${projectDir.path}/$relPath'), true); } // Generated Xcode settings final String macosXcodeConfigPath = globals.fs.path.join('macos', 'Runner', 'Configs', 'AppInfo.xcconfig'); expectExists(macosXcodeConfigPath); final File macosXcodeConfigFile = globals.fs.file(globals.fs.path.join(projectDir.path, macosXcodeConfigPath)); final String macosXcodeConfig = macosXcodeConfigFile.readAsStringSync(); expect(macosXcodeConfig, contains('PRODUCT_NAME = flutter_project')); expect(macosXcodeConfig, contains('PRODUCT_BUNDLE_IDENTIFIER = com.foo.bar.flutterProject')); expect(macosXcodeConfig, contains('PRODUCT_COPYRIGHT =')); // Xcode project final String xcodeProjectPath = globals.fs.path.join('macos', 'Runner.xcodeproj', 'project.pbxproj'); expectExists(xcodeProjectPath); final File xcodeProjectFile = globals.fs.file(globals.fs.path.join(projectDir.path, xcodeProjectPath)); final String xcodeProject = xcodeProjectFile.readAsStringSync(); expect(xcodeProject, contains('path = "flutter_project.app";')); expect(xcodeProject, contains('LastUpgradeCheck = 1510;')); // Xcode workspace shared data final Directory workspaceSharedData = globals.fs.directory(globals.fs.path.join('macos', 'Runner.xcworkspace', 'xcshareddata')); expectExists(workspaceSharedData.childFile('IDEWorkspaceChecks.plist').path); // Xcode project shared data final Directory projectSharedData = globals.fs.directory(globals.fs.path.join('macos', 'Runner.xcodeproj', 'project.xcworkspace', 'xcshareddata')); expectExists(projectSharedData.childFile('IDEWorkspaceChecks.plist').path); }, overrides: <Type, Generator>{ Platform: _kNoColorTerminalPlatform, FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('has correct application id for android, bundle id for ios and application id for Linux', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); String tmpProjectDir = globals.fs.path.join(tempDir.path, 'hello_flutter'); await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'com.example', tmpProjectDir]); FlutterProject project = FlutterProject.fromDirectory(globals.fs.directory(tmpProjectDir)); expect( await project.ios.productBundleIdentifier(BuildInfo.debug), 'com.example.helloFlutter', ); expect( await project.ios.productBundleIdentifier(BuildInfo.profile), 'com.example.helloFlutter', ); expect( await project.ios.productBundleIdentifier(BuildInfo.release), 'com.example.helloFlutter', ); expect( await project.ios.productBundleIdentifier(null), 'com.example.helloFlutter', ); expect( project.android.applicationId, 'com.example.hello_flutter', ); expect( project.linux.applicationId, 'com.example.hello_flutter', ); tmpProjectDir = globals.fs.path.join(tempDir.path, 'test_abc'); await runner.run(<String>['create', '--template=app', '--no-pub', '--org', 'abc^*.1#@', tmpProjectDir]); project = FlutterProject.fromDirectory(globals.fs.directory(tmpProjectDir)); expect( await project.ios.productBundleIdentifier(BuildInfo.debug), 'abc.1.testAbc', ); expect( project.android.applicationId, 'abc.u1.test_abc', ); tmpProjectDir = globals.fs.path.join(tempDir.path, 'flutter_project'); await runner.run(<String>['create', '--template=app', '--no-pub', '--org', '#+^%', tmpProjectDir]); project = FlutterProject.fromDirectory(globals.fs.directory(tmpProjectDir)); expect( await project.ios.productBundleIdentifier(BuildInfo.debug), 'flutterProject.untitled', ); expect( project.android.applicationId, 'flutter_project.untitled', ); expect( project.linux.applicationId, 'flutter_project.untitled', ); }, overrides: <Type, Generator>{ FlutterVersion: () => fakeFlutterVersion, Platform: _kNoColorTerminalPlatform, FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), }); testUsingContext('can re-gen default template over existing project', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); final String metadata = globals.fs.file(globals.fs.path.join(projectDir.path, '.metadata')).readAsStringSync(); expect(LineSplitter.split(metadata), contains('project_type: app')); }); testUsingContext('can re-gen default template over existing app project with no metadata and detect the type', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=app', projectDir.path]); // Remove the .metadata to simulate an older instantiation that didn't generate those. globals.fs.file(globals.fs.path.join(projectDir.path, '.metadata')).deleteSync(); await runner.run(<String>['create', '--no-pub', projectDir.path]); final String metadata = globals.fs.file(globals.fs.path.join(projectDir.path, '.metadata')).readAsStringSync(); expect(LineSplitter.split(metadata), contains('project_type: app')); }); testUsingContext('can re-gen app template over existing app project and detect the type', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=app', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); final String metadata = globals.fs.file(globals.fs.path.join(projectDir.path, '.metadata')).readAsStringSync(); expect(LineSplitter.split(metadata), contains('project_type: app')); }); testUsingContext('can re-gen template over existing module project and detect the type', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=module', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); final String metadata = globals.fs.file(globals.fs.path.join(projectDir.path, '.metadata')).readAsStringSync(); expect(LineSplitter.split(metadata), contains('project_type: module')); }); testUsingContext('can re-gen default template over existing plugin project and detect the type', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); final String metadata = globals.fs.file(globals.fs.path.join(projectDir.path, '.metadata')).readAsStringSync(); expect(LineSplitter.split(metadata), contains('project_type: plugin')); }); testUsingContext('can re-gen default template over existing package project and detect the type', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=package', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); final String metadata = globals.fs.file(globals.fs.path.join(projectDir.path, '.metadata')).readAsStringSync(); expect(LineSplitter.split(metadata), contains('project_type: package')); }); testUsingContext('can re-gen module .android/ folder, reusing custom org', () async { await _createProject( projectDir, <String>['--template=module', '--org', 'com.bar.foo'], <String>[], ); projectDir.childDirectory('.android').deleteSync(recursive: true); return _createProject( projectDir, <String>[], <String>[ '.android/app/src/main/java/com/bar/foo/flutter_project/host/MainActivity.java', ], ); }, 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: mockStdio, ), }); testUsingContext('can re-gen module .ios/ folder, reusing custom org', () async { await _createProject( projectDir, <String>['--template=module', '--org', 'com.bar.foo'], <String>[], ); projectDir.childDirectory('.ios').deleteSync(recursive: true); await _createProject(projectDir, <String>[], <String>[]); final FlutterProject project = FlutterProject.fromDirectory(projectDir); expect( await project.ios.productBundleIdentifier(BuildInfo.debug), 'com.bar.foo.flutterProject', ); }, 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: mockStdio, ), }); testUsingContext('can re-gen app android/ folder, reusing custom org', () async { await _createProject( projectDir, <String>[ '--no-pub', '--template=app', '--org', 'com.bar.foo', '-i', 'objc', '-a', 'java', ], <String>[], ); projectDir.childDirectory('android').deleteSync(recursive: true); return _createProject( projectDir, <String>['--no-pub', '-i', 'objc', '-a', 'java'], <String>[ 'android/app/src/main/java/com/bar/foo/flutter_project/MainActivity.java', ], unexpectedPaths: <String>[ 'android/app/src/main/java/com/example/flutter_project/MainActivity.java', ], ); }); testUsingContext('can re-gen app ios/ folder, reusing custom org', () async { await _createProject( projectDir, <String>['--no-pub', '--template=app', '--org', 'com.bar.foo'], <String>[], ); projectDir.childDirectory('ios').deleteSync(recursive: true); await _createProject(projectDir, <String>['--no-pub'], <String>[]); final FlutterProject project = FlutterProject.fromDirectory(projectDir); expect( await project.ios.productBundleIdentifier(BuildInfo.debug), 'com.bar.foo.flutterProject', ); }); testUsingContext('can re-gen plugin ios/ and example/ folders, reusing custom org', () async { await _createProject( projectDir, <String>[ '--no-pub', '--template=plugin', '--org', 'com.bar.foo', '-i', 'objc', '-a', 'java', '--platforms', 'ios,android', ], <String>[], ); projectDir.childDirectory('example').deleteSync(recursive: true); projectDir.childDirectory('ios').deleteSync(recursive: true); await _createProject( projectDir, <String>['--no-pub', '--template=plugin', '-i', 'objc', '-a', 'java', '--platforms', 'ios,android'], <String>[ 'example/android/app/src/main/java/com/bar/foo/flutter_project_example/MainActivity.java', 'ios/Classes/FlutterProjectPlugin.h', ], unexpectedPaths: <String>[ 'example/android/app/src/main/java/com/example/flutter_project_example/MainActivity.java', 'android/src/main/java/com/example/flutter_project/FlutterProjectPlugin.java', ], ); final FlutterProject project = FlutterProject.fromDirectory(projectDir); expect( await project.example.ios.productBundleIdentifier(BuildInfo.debug), 'com.bar.foo.flutterProjectExample', ); }); testUsingContext('fails to re-gen without specified org when org is ambiguous', () async { await _createProject( projectDir, <String>['--no-pub', '--template=app', '--org', 'com.bar.foo'], <String>[], ); globals.fs.directory(globals.fs.path.join(projectDir.path, 'ios')).deleteSync(recursive: true); await _createProject( projectDir, <String>['--no-pub', '--template=app', '--org', 'com.bar.baz'], <String>[], ); expect( () => _createProject(projectDir, <String>[], <String>[]), throwsToolExit(message: 'Ambiguous organization'), ); }); testUsingContext('fails when file exists where output directory should be', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final File existingFile = globals.fs.file(globals.fs.path.join(projectDir.path, 'bad')); if (!existingFile.existsSync()) { existingFile.createSync(recursive: true); } expect( runner.run(<String>['create', existingFile.path]), throwsToolExit(message: 'existing file'), ); }); testUsingContext('fails overwrite when file exists where output directory should be', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final File existingFile = globals.fs.file(globals.fs.path.join(projectDir.path, 'bad')); if (!existingFile.existsSync()) { existingFile.createSync(recursive: true); } expect( runner.run(<String>['create', '--overwrite', existingFile.path]), throwsToolExit(message: 'existing file'), ); }); testUsingContext('overwrites existing directory when requested', () async { Cache.flutterRoot = '../..'; final Directory existingDirectory = globals.fs.directory(globals.fs.path.join(projectDir.path, 'bad')); if (!existingDirectory.existsSync()) { existingDirectory.createSync(recursive: true); } final File existingFile = globals.fs.file(globals.fs.path.join(existingDirectory.path, 'lib', 'main.dart')); existingFile.createSync(recursive: true); await _createProject( globals.fs.directory(existingDirectory.path), <String>['--overwrite', '-i', 'objc', '-a', 'java'], <String>[ 'android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java', 'lib/main.dart', 'ios/Flutter/AppFrameworkInfo.plist', 'ios/Runner/AppDelegate.m', 'ios/Runner/GeneratedPluginRegistrant.h', ], ); }, 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: mockStdio, ), }); testUsingContext( 'invokes pub in online and offline modes', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); // Run pub online first in order to populate the pub cache. await runner.run(<String>['create', '--pub', projectDir.path]); final RegExp dartCommand = RegExp(r'dart-sdk[\\/]bin[\\/]dart'); expect(loggingProcessManager.commands, contains(predicate( (List<String> c) => dartCommand.hasMatch(c[0]) && c[1].contains('pub') && !c.contains('--offline') ))); // Run pub offline. loggingProcessManager.clear(); await runner.run(<String>['create', '--pub', '--offline', projectDir.path]); expect(loggingProcessManager.commands, contains(predicate( (List<String> c) => dartCommand.hasMatch(c[0]) && c[1].contains('pub') && c.contains('--offline'), ))); }, overrides: <Type, Generator>{ ProcessManager: () => loggingProcessManager, Pub: () => Pub.test( fileSystem: globals.fs, logger: globals.logger, processManager: globals.processManager, usage: globals.flutterUsage, botDetector: globals.botDetector, platform: globals.platform, stdio: mockStdio, ), }, ); testUsingContext('can create an empty application project', () async { await _createAndAnalyzeProject( projectDir, <String>['--no-pub', '--empty'], <String>[ 'lib/main.dart', 'flutter_project.iml', 'android/app/src/main/AndroidManifest.xml', 'ios/Flutter/AppFrameworkInfo.plist', ], unexpectedPaths: <String>['test'], ); expect(projectDir.childDirectory('lib').childFile('main.dart').readAsStringSync(), contains("Text('Hello World!')")); expect(projectDir.childDirectory('lib').childFile('main.dart').readAsStringSync(), isNot(contains('int _counter'))); expect(projectDir.childFile('analysis_options.yaml').readAsStringSync(), isNot(contains('#'))); expect(projectDir.childFile('README.md').readAsStringSync(), isNot(contains('Getting Started'))); }); testUsingContext("can't create an empty non-application project", () async { final String outputDir = globals.fs.path.join(tempDir.path, 'test_project'); final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<String> args = <String>[ 'create', '--no-pub', '--empty', '--template=plugin', outputDir, ]; await expectLater( runner.run(args), throwsToolExit( message: 'The --empty flag is only supported for the app template.', )); }); testUsingContext('can create a sample-based project', () async { await _createAndAnalyzeProject( projectDir, <String>['--no-pub', '--sample=foo.bar.Baz'], <String>[ 'lib/main.dart', 'flutter_project.iml', 'android/app/src/main/AndroidManifest.xml', 'ios/Flutter/AppFrameworkInfo.plist', ], unexpectedPaths: <String>['test'], ); expect(projectDir.childDirectory('lib').childFile('main.dart').readAsStringSync(), contains('void main() {}')); }, overrides: <Type, Generator>{ HttpClientFactory: () { return () { return FakeHttpClient.list(<FakeRequest>[ FakeRequest( Uri.parse('https://main-api.flutter.dev/snippets/foo.bar.Baz.dart'), response: FakeResponse(body: utf8.encode('void main() {}')), ), ]); }; }, }); testUsingContext('null-safe sample-based project have no analyzer errors', () async { await _createAndAnalyzeProject( projectDir, <String>['--no-pub', '--sample=foo.bar.Baz'], <String>['lib/main.dart'], ); expect( projectDir.childDirectory('lib').childFile('main.dart').readAsStringSync(), contains('String?'), // uses null-safe syntax ); }, overrides: <Type, Generator>{ HttpClientFactory: () { return () { return FakeHttpClient.list(<FakeRequest>[ FakeRequest( Uri.parse('https://main-api.flutter.dev/snippets/foo.bar.Baz.dart'), response: FakeResponse(body: utf8.encode('void main() { String? foo; print(foo); } // ignore: avoid_print')), ), ]); }; }, }); testUsingContext('can write samples index to disk', () async { final String outputFile = globals.fs.path.join(tempDir.path, 'flutter_samples.json'); final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<String> args = <String>[ 'create', '--list-samples', outputFile, ]; await runner.run(args); final File expectedFile = globals.fs.file(outputFile); expect(expectedFile, exists); expect(expectedFile.readAsStringSync(), equals(samplesIndexJson)); }, overrides: <Type, Generator>{ HttpClientFactory: () { return () { return FakeHttpClient.list(<FakeRequest>[ FakeRequest( Uri.parse('https://main-api.flutter.dev/snippets/index.json'), response: FakeResponse(body: utf8.encode(samplesIndexJson)), ), ]); }; }, }); testUsingContext('Throws tool exit on empty samples index', () async { final String outputFile = globals.fs.path.join(tempDir.path, 'flutter_samples.json'); final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<String> args = <String>[ 'create', '--list-samples', outputFile, ]; await expectLater( runner.run(args), throwsToolExit( exitCode: 2, message: 'Unable to download samples', )); }, overrides: <Type, Generator>{ HttpClientFactory: () { return () { return FakeHttpClient.list(<FakeRequest>[ FakeRequest( Uri.parse('https://main-api.flutter.dev/snippets/index.json'), ), ]); }; }, }); testUsingContext('provides an error to the user if samples json download fails', () async { final String outputFile = globals.fs.path.join(tempDir.path, 'flutter_samples.json'); final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<String> args = <String>[ 'create', '--list-samples', outputFile, ]; await expectLater(runner.run(args), throwsToolExit(exitCode: 2, message: 'Failed to write samples')); expect(globals.fs.file(outputFile), isNot(exists)); }, overrides: <Type, Generator>{ HttpClientFactory: () { return () { return FakeHttpClient.list(<FakeRequest>[ FakeRequest( Uri.parse('https://main-api.flutter.dev/snippets/index.json'), response: const FakeResponse(statusCode: HttpStatus.notFound), ), ]); }; }, }); testUsingContext('plugin does not support any platform by default', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(projectDir.childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('web'), isNot(exists)); expect(projectDir.childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('ios'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('web'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('macos'), isNot(exists)); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: <String>[ 'some_platform', ], pluginClass: 'somePluginClass', unexpectedPlatforms: <String>[ 'ios', 'android', 'web', 'linux', 'windows', 'macos']); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('plugin creates platform interface by default', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(projectDir.childDirectory('lib').childFile('flutter_project_method_channel.dart'), exists); expect(projectDir.childDirectory('lib').childFile('flutter_project_platform_interface.dart'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('plugin passes analysis and unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await _getPackages(projectDir); await _analyzeProject(projectDir.path); await _runFlutterTest(projectDir); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('plugin example passes analysis and unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); final Directory exampleDir = projectDir.childDirectory('example'); await _getPackages(exampleDir); await _analyzeProject(exampleDir.path); await _runFlutterTest(exampleDir); }); testUsingContext('plugin supports ios if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=ios', projectDir.path]); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: <String>[ 'ios', ], pluginClass: 'FlutterProjectPlugin', unexpectedPlatforms: <String>['some_platform']); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('plugin supports android if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); expect(projectDir.childDirectory('android'), exists); expect( projectDir.childDirectory('example').childDirectory('android'), exists); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'android', ], pluginClass: 'FlutterProjectPlugin', unexpectedPlatforms: <String>['some_platform'], androidIdentifier: 'com.example.flutter_project'); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('plugin supports web if requested', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=web', projectDir.path]); expect( projectDir.childDirectory('lib').childFile('flutter_project_web.dart'), exists); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'web', ], pluginClass: 'FlutterProjectWeb', unexpectedPlatforms: <String>['some_platform'], androidIdentifier: 'com.example.flutter_project', webFileName: 'flutter_project_web.dart'); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); await _getPackages(projectDir); await _analyzeProject(projectDir.path); await _runFlutterTest(projectDir); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), Logger: () => logger, }); testUsingContext('plugin does not support web if feature is not enabled', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=web', projectDir.path]); expect( projectDir.childDirectory('lib').childFile('flutter_project_web.dart'), isNot(exists)); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'some_platform', ], pluginClass: 'somePluginClass', unexpectedPlatforms: <String>['web']); expect(logger.errorText, contains(_kNoPlatformsMessage)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('create an empty plugin, then add ios', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=ios', projectDir.path]); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('create an empty plugin, then add android', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); expect(projectDir.childDirectory('android'), exists); expect( projectDir.childDirectory('example').childDirectory('android'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), }); testUsingContext('create an empty plugin, then add linux', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=linux', projectDir.path]); expect(projectDir.childDirectory('linux'), exists); expect( projectDir.childDirectory('example').childDirectory('linux'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), }); testUsingContext('create an empty plugin, then add macos', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=macos', projectDir.path]); expect(projectDir.childDirectory('macos'), exists); expect( projectDir.childDirectory('example').childDirectory('macos'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('create an empty plugin, then add windows', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=windows', projectDir.path]); expect(projectDir.childDirectory('windows'), exists); expect( projectDir.childDirectory('example').childDirectory('windows'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('create an empty plugin, then add web', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=web', projectDir.path]); expect( projectDir.childDirectory('lib').childFile('flutter_project_web.dart'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), }); testUsingContext('create a plugin with ios, then add macos', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=ios', projectDir.path]); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'ios', ], pluginClass: 'FlutterProjectPlugin', unexpectedPlatforms: <String>['some_platform']); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=macos', projectDir.path]); expect(projectDir.childDirectory('macos'), exists); expect( projectDir.childDirectory('example').childDirectory('macos'), exists); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('create a plugin with ios and android', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platforms=ios,android', projectDir.path]); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); expect(projectDir.childDirectory('android'), exists); expect( projectDir.childDirectory('example').childDirectory('android'), exists); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); validatePubspecForPlugin(projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'ios', 'android', ], pluginClass: 'FlutterProjectPlugin', unexpectedPlatforms: <String>['some_platform'], androidIdentifier: 'com.example.flutter_project'); }); testUsingContext('plugin includes native Swift unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platforms=ios,macos', projectDir.path]); expect(projectDir .childDirectory('example') .childDirectory('ios') .childDirectory('RunnerTests') .childFile('RunnerTests.swift'), exists); expect(projectDir .childDirectory('example') .childDirectory('macos') .childDirectory('RunnerTests') .childFile('RunnerTests.swift'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), Logger: () => logger, }); testUsingContext('plugin includes native Kotlin unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--template=plugin', '--org=com.example', '--platforms=android', projectDir.path]); expect(projectDir .childDirectory('android') .childDirectory('src') .childDirectory('test') .childDirectory('kotlin') .childDirectory('com') .childDirectory('example') .childDirectory('flutter_project') .childFile('FlutterProjectPluginTest.kt'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('plugin includes native Java unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--template=plugin', '--org=com.example', '--platforms=android', '-a', 'java', projectDir.path]); expect(projectDir .childDirectory('android') .childDirectory('src') .childDirectory('test') .childDirectory('java') .childDirectory('com') .childDirectory('example') .childDirectory('flutter_project') .childFile('FlutterProjectPluginTest.java'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('plugin includes native Objective-C unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--template=plugin', '--platforms=ios', '-i', 'objc', projectDir.path]); expect(projectDir .childDirectory('example') .childDirectory('ios') .childDirectory('RunnerTests') .childFile('RunnerTests.m'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('plugin includes native Windows unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--template=plugin', '--platforms=windows', projectDir.path]); expect(projectDir .childDirectory('windows') .childDirectory('test') .childFile('flutter_project_plugin_test.cpp'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), Logger: () => logger, }); testUsingContext('plugin includes native Linux unit tests', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', '--no-pub', '--template=plugin', '--platforms=linux', projectDir.path]); expect(projectDir .childDirectory('linux') .childDirectory('test') .childFile('flutter_project_plugin_test.cc'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), Logger: () => logger, }); testUsingContext('create a module with --platforms throws error.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await expectLater( runner.run(<String>['create', '--no-pub', '--template=module', '--platform=ios', projectDir.path]) , throwsToolExit(message: 'The "--platforms" argument is not supported', exitCode:2)); }); testUsingContext('create a package with --platforms throws error.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await expectLater( runner.run(<String>['create', '--no-pub', '--template=package', '--platform=ios', projectDir.path]) , throwsToolExit(message: 'The "--platforms" argument is not supported', exitCode: 2)); }); testUsingContext('create an ffi package with --platforms throws error.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await expectLater( runner.run(<String>['create', '--no-pub', '--template=package_ffi', '--platform=ios', projectDir.path]) , throwsToolExit(message: 'The "--platforms" argument is not supported', exitCode: 2)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), }); testUsingContext('create a plugin with android, delete then re-create folders', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); expect(projectDir.childDirectory('android'), exists); expect( projectDir.childDirectory('example').childDirectory('android'), exists); globals.fs.file(globals.fs.path.join(projectDir.path, 'android')).deleteSync(recursive: true); globals.fs.file(globals.fs.path.join(projectDir.path, 'example/android')).deleteSync(recursive: true); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('android'), isNot(exists)); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('android'), exists); expect( projectDir.childDirectory('example').childDirectory('android'), exists); }); testUsingContext('create a plugin with android, delete then re-create folders while also adding windows', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); expect(projectDir.childDirectory('android'), exists); expect( projectDir.childDirectory('example').childDirectory('android'), exists); globals.fs.file(globals.fs.path.join(projectDir.path, 'android')).deleteSync(recursive: true); globals.fs.file(globals.fs.path.join(projectDir.path, 'example/android')).deleteSync(recursive: true); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('android'), isNot(exists)); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=windows', projectDir.path]); expect(projectDir.childDirectory('android'), exists); expect( projectDir.childDirectory('example').childDirectory('android'), exists); expect(projectDir.childDirectory('windows'), exists); expect( projectDir.childDirectory('example').childDirectory('windows'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('flutter create . on and existing plugin does not add android folders if android is not supported in pubspec', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=ios', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('android'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('android'), isNot(exists)); }); testUsingContext('flutter create . on and existing plugin does not add windows folder even feature is enabled', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('windows'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('windows'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('flutter create . on and existing plugin does not add linux folder even feature is enabled', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('linux'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('linux'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), }); testUsingContext('flutter create . on and existing plugin does not add web files even feature is enabled', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('lib').childFile('flutter_project_web.dart'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWebEnabled: true), }); testUsingContext('flutter create . on and existing plugin does not add macos folder even feature is enabled', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(projectDir.childDirectory('macos'), isNot(exists)); expect(projectDir.childDirectory('example').childDirectory('macos'), isNot(exists)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); testUsingContext('flutter create . on and existing plugin should show "Your example app code in"', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final String projectDirPath = globals.fs.path.normalize(projectDir.absolute.path); final String relativePluginPath = globals.fs.path.normalize(globals.fs.path.relative(projectDirPath)); final String relativeExamplePath = globals.fs.path.normalize(globals.fs.path.join(relativePluginPath, 'example/lib/main.dart')); await runner.run(<String>['create', '--no-pub', '--org=com.example', '--template=plugin', '--platform=android', projectDir.path]); expect(logger.statusText, contains('Your example app code is in $relativeExamplePath.\n')); await runner.run(<String>['create', '--no-pub', '--org=com.example', '--template=plugin', '--platform=ios', projectDir.path]); expect(logger.statusText, contains('Your example app code is in $relativeExamplePath.\n')); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(logger.statusText, contains('Your example app code is in $relativeExamplePath.\n')); }, overrides: <Type, Generator> { Logger: () => logger, }); testUsingContext('flutter create -t plugin in an empty folder should not show pubspec.yaml updating suggestion', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); final String projectDirPath = globals.fs.path.normalize(projectDir.absolute.path); final String relativePluginPath = globals.fs.path.normalize(globals.fs.path.relative(projectDirPath)); expect(logger.statusText, isNot(contains('You need to update $relativePluginPath/pubspec.yaml to support android.\n'))); }, overrides: <Type, Generator> { Logger: () => logger, }); testUsingContext('flutter create -t plugin in an existing plugin should show pubspec.yaml updating suggestion', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final String projectDirPath = globals.fs.path.normalize(projectDir.absolute.path); final String relativePluginPath = globals.fs.path.normalize(globals.fs.path.relative(projectDirPath)); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=ios', projectDir.path]); expect(logger.statusText, isNot(contains('You need to update $relativePluginPath/pubspec.yaml to support ios.\n'))); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=android', projectDir.path]); expect(logger.statusText, contains('You need to update $relativePluginPath/pubspec.yaml to support android.\n')); }, overrides: <Type, Generator> { Logger: () => logger, }); testUsingContext('newly created plugin has min flutter sdk version as 3.3.0', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); final String rawPubspec = await projectDir.childFile('pubspec.yaml').readAsString(); final Pubspec pubspec = Pubspec.parse(rawPubspec); final Map<String, VersionConstraint?> env = pubspec.environment!; expect(env['flutter']!.allows(Version(3, 3, 0)), true); expect(env['flutter']!.allows(Version(3, 2, 9)), false); }); testUsingContext('newly created iOS plugins has correct min iOS version', () async { Cache.flutterRoot = '../..'; final String flutterToolsAbsolutePath = globals.fs.path.join( Cache.flutterRoot!, 'packages', 'flutter_tools', ); final List<String> iosPluginTemplates = <String>[ globals.fs.path.join( flutterToolsAbsolutePath, 'templates', 'plugin', 'ios-objc.tmpl', 'projectName.podspec.tmpl', ), globals.fs.path.join( flutterToolsAbsolutePath, 'templates', 'plugin', 'ios-swift.tmpl', 'projectName.podspec.tmpl', ), globals.fs.path.join( flutterToolsAbsolutePath, 'templates', 'plugin_ffi', 'ios.tmpl', 'projectName.podspec.tmpl', ), ]; for (final String templatePath in iosPluginTemplates) { final String rawTemplate = globals.fs.file(templatePath).readAsStringSync(); expect(rawTemplate, contains("s.platform = :ios, '12.0'")); } final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=ios', projectDir.path]); expect(projectDir.childDirectory('ios').childFile('flutter_project.podspec'), exists); final String rawPodSpec = await projectDir.childDirectory('ios').childFile('flutter_project.podspec').readAsString(); expect(rawPodSpec, contains("s.platform = :ios, '12.0'")); }); testUsingContext('default app uses flutter default versions', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(globals.fs.isFileSync('${projectDir.path}/android/app/build.gradle'), true); final String buildContent = await globals.fs.file('${projectDir.path}/android/app/build.gradle').readAsString(); expect(buildContent.contains('compileSdk = flutter.compileSdkVersion'), true); expect(buildContent.contains('ndkVersion = flutter.ndkVersion'), true); expect(buildContent.contains('minSdk = flutter.minSdkVersion'), true); expect(buildContent.contains('targetSdk = flutter.targetSdkVersion'), true); }); testUsingContext('Android Java plugin contains namespace', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '-t', 'plugin', '--org', 'com.bar.foo', '-a', 'java', '--platforms=android', projectDir.path]); final File buildGradleFile = globals.fs.file('${projectDir.path}/android/build.gradle'); expect(buildGradleFile.existsSync(), true); final String buildGradleContent = await buildGradleFile.readAsString(); expect(buildGradleContent.contains('namespace = "com.bar.foo.flutter_project"'), true); // The namespace should be conditionalized for AGP <4.2. expect(buildGradleContent.contains('if (project.android.hasProperty("namespace")) {'), true); }); testUsingContext('Android FFI plugin contains namespace', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '-t', 'plugin_ffi', '--org', 'com.bar.foo', '--platforms=android', projectDir.path]); final File buildGradleFile = globals.fs.file('${projectDir.path}/android/build.gradle'); expect(buildGradleFile.existsSync(), true); final String buildGradleContent = await buildGradleFile.readAsString(); expect(buildGradleContent.contains('namespace = "com.bar.foo.flutter_project"'), true); // The namespace should be conditionalized for AGP <4.2. expect(buildGradleContent.contains('if (project.android.hasProperty("namespace")) {'), true); }); testUsingContext('Android Kotlin plugin contains namespace', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '-t', 'plugin', '--org', 'com.bar.foo', '-a', 'kotlin', '--platforms=android', projectDir.path]); final File buildGradleFile = globals.fs.file('${projectDir.path}/android/build.gradle'); expect(buildGradleFile.existsSync(), true); final String buildGradleContent = await buildGradleFile.readAsString(); expect(buildGradleContent.contains('namespace = "com.bar.foo.flutter_project"'), true); // The namespace should be conditionalized for AGP <4.2. expect(buildGradleContent.contains('if (project.android.hasProperty("namespace")) {'), true); }); testUsingContext('Flutter module Android project contains namespace', () async { const String moduleBuildGradleFilePath = '.android/build.gradle'; const String moduleAppBuildGradleFlePath = '.android/app/build.gradle'; const String moduleFlutterBuildGradleFilePath = '.android/Flutter/build.gradle'; await _createProject( projectDir, <String>['--template=module', '--org', 'com.bar.foo'], <String>[moduleBuildGradleFilePath, moduleAppBuildGradleFlePath, moduleFlutterBuildGradleFilePath, ], ); final String moduleBuildGradleFileContent = await globals.fs.file(globals.fs.path.join(projectDir.path, moduleBuildGradleFilePath)).readAsString(); final String moduleAppBuildGradleFileContent = await globals.fs.file(globals.fs.path.join(projectDir.path, moduleAppBuildGradleFlePath)).readAsString(); final String moduleFlutterBuildGradleFileContent = await globals.fs.file(globals.fs.path.join(projectDir.path, moduleFlutterBuildGradleFilePath)).readAsString(); // Each build file should contain the expected namespace. const String expectedNameSpace = 'namespace = "com.bar.foo.flutter_project"'; expect(moduleBuildGradleFileContent.contains(expectedNameSpace), true); expect(moduleFlutterBuildGradleFileContent.contains(expectedNameSpace), true); const String expectedHostNameSpace = 'namespace = "com.bar.foo.flutter_project.host"'; expect(moduleAppBuildGradleFileContent.contains(expectedHostNameSpace), true); // The namespaces should be conditionalized for AGP <4.2. const String expectedConditional = 'if (project.android.hasProperty("namespace")) {'; expect(moduleBuildGradleFileContent.contains(expectedConditional), true); expect(moduleAppBuildGradleFileContent.contains(expectedConditional), true); expect(moduleFlutterBuildGradleFileContent.contains(expectedConditional), true); }, 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: mockStdio, ), }); testUsingContext('Linux plugins handle partially camel-case project names correctly', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); const String projectName = 'foo_BarBaz'; final Directory projectDir = tempDir.childDirectory(projectName); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=linux', '--skip-name-checks', projectDir.path]); final Directory platformDir = projectDir.childDirectory('linux'); const String classFilenameBase = 'foo_bar_baz_plugin'; const String headerName = '$classFilenameBase.h'; final File headerFile = platformDir .childDirectory('include') .childDirectory(projectName) .childFile(headerName); final File implFile = platformDir.childFile('$classFilenameBase.cc'); // Ensure that the files have the right names. expect(headerFile, exists); expect(implFile, exists); // Ensure that the include is correct. expect(implFile.readAsStringSync(), contains(headerName)); // Ensure that the CMake file has the right target and source values. final String cmakeContents = platformDir.childFile('CMakeLists.txt').readAsStringSync(); expect(cmakeContents, contains('"$classFilenameBase.cc"')); expect(cmakeContents, contains('set(PLUGIN_NAME "foo_BarBaz_plugin")')); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), }); testUsingContext('Windows plugins handle partially camel-case project names correctly', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); const String projectName = 'foo_BarBaz'; final Directory projectDir = tempDir.childDirectory(projectName); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=windows', '--skip-name-checks', projectDir.path]); final Directory platformDir = projectDir.childDirectory('windows'); const String classFilenameBase = 'foo_bar_baz_plugin'; const String cApiHeaderName = '${classFilenameBase}_c_api.h'; const String pluginClassHeaderName = '$classFilenameBase.h'; final File cApiHeaderFile = platformDir .childDirectory('include') .childDirectory(projectName) .childFile(cApiHeaderName); final File cApiImplFile = platformDir.childFile('${classFilenameBase}_c_api.cpp'); final File pluginClassHeaderFile = platformDir.childFile(pluginClassHeaderName); final File pluginClassImplFile = platformDir.childFile('$classFilenameBase.cpp'); // Ensure that the files have the right names. expect(cApiHeaderFile, exists); expect(cApiImplFile, exists); expect(pluginClassHeaderFile, exists); expect(pluginClassImplFile, exists); // Ensure that the includes are correct. expect(cApiImplFile.readAsLinesSync(), containsAllInOrder(<Matcher>[ contains('#include "include/$projectName/$cApiHeaderName"'), contains('#include "$pluginClassHeaderName"'), ])); expect(pluginClassImplFile.readAsLinesSync(), contains('#include "$pluginClassHeaderName"')); // Ensure that the plugin target name matches the post-processed version. // Ensure that the CMake file has the right target and source values. final String cmakeContents = platformDir.childFile('CMakeLists.txt').readAsStringSync(); expect(cmakeContents, contains('"$classFilenameBase.cpp"')); expect(cmakeContents, contains('"$classFilenameBase.h"')); expect(cmakeContents, contains('"${classFilenameBase}_c_api.cpp"')); expect(cmakeContents, contains('"include/$projectName/${classFilenameBase}_c_api.h"')); expect(cmakeContents, contains('set(PLUGIN_NAME "foo_BarBaz_plugin")')); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('Linux plugins handle project names ending in _plugin correctly', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); const String projectName = 'foo_bar_plugin'; final Directory projectDir = tempDir.childDirectory(projectName); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=linux', projectDir.path]); final Directory platformDir = projectDir.childDirectory('linux'); // If the project already ends in _plugin, it shouldn't be added again. const String classFilenameBase = projectName; const String headerName = '$classFilenameBase.h'; final File headerFile = platformDir .childDirectory('include') .childDirectory(projectName) .childFile(headerName); final File implFile = platformDir.childFile('$classFilenameBase.cc'); // Ensure that the files have the right names. expect(headerFile, exists); expect(implFile, exists); // Ensure that the include is correct. expect(implFile.readAsStringSync(), contains(headerName)); // Ensure that the CMake file has the right target and source values. final String cmakeContents = platformDir.childFile('CMakeLists.txt').readAsStringSync(); expect(cmakeContents, contains('"$classFilenameBase.cc"')); // The "_plugin_plugin" suffix is intentional; because the target names must // be unique across the ecosystem, no canonicalization can be done, // otherwise plugins called "foo_bar" and "foo_bar_plugin" would collide in // builds. expect(cmakeContents, contains('set(PLUGIN_NAME "foo_bar_plugin_plugin")')); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isLinuxEnabled: true), }); testUsingContext('Windows plugins handle project names ending in _plugin correctly', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); const String projectName = 'foo_bar_plugin'; final Directory projectDir = tempDir.childDirectory(projectName); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=windows', projectDir.path]); final Directory platformDir = projectDir.childDirectory('windows'); // If the project already ends in _plugin, it shouldn't be added again. const String classFilenameBase = projectName; const String cApiHeaderName = '${classFilenameBase}_c_api.h'; const String pluginClassHeaderName = '$classFilenameBase.h'; final File cApiHeaderFile = platformDir .childDirectory('include') .childDirectory(projectName) .childFile(cApiHeaderName); final File cApiImplFile = platformDir.childFile('${classFilenameBase}_c_api.cpp'); final File pluginClassHeaderFile = platformDir.childFile(pluginClassHeaderName); final File pluginClassImplFile = platformDir.childFile('$classFilenameBase.cpp'); // Ensure that the files have the right names. expect(cApiHeaderFile, exists); expect(cApiImplFile, exists); expect(pluginClassHeaderFile, exists); expect(pluginClassImplFile, exists); // Ensure that the includes are correct. expect(cApiImplFile.readAsLinesSync(), containsAllInOrder(<Matcher>[ contains('#include "include/$projectName/$cApiHeaderName"'), contains('#include "$pluginClassHeaderName"'), ])); expect(pluginClassImplFile.readAsLinesSync(), contains('#include "$pluginClassHeaderName"')); // Ensure that the CMake file has the right target and source values. final String cmakeContents = platformDir.childFile('CMakeLists.txt').readAsStringSync(); expect(cmakeContents, contains('"$classFilenameBase.cpp"')); // The "_plugin_plugin" suffix is intentional; because the target names must // be unique across the ecosystem, no canonicalization can be done, // otherwise plugins called "foo_bar" and "foo_bar_plugin" would collide in // builds. expect(cmakeContents, contains('set(PLUGIN_NAME "foo_bar_plugin_plugin")')); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), }); testUsingContext('created plugin supports no platforms should print `no platforms` message', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(logger.errorText, contains(_kNoPlatformsMessage)); expect(logger.statusText, contains('To add platforms, run `flutter create -t plugin --platforms <platforms> .` under ${globals.fs.path.normalize(globals.fs.path.relative(projectDir.path))}.')); expect(logger.statusText, contains('For more information, see https://flutter.dev/go/plugin-platforms.')); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: ()=> logger, }); testUsingContext('created FFI plugin supports no platforms should print `no platforms` message', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', projectDir.path]); expect(logger.errorText, contains(_kNoPlatformsMessage)); expect(logger.statusText, contains('To add platforms, run `flutter create -t plugin_ffi --platforms <platforms> .` under ${globals.fs.path.normalize(globals.fs.path.relative(projectDir.path))}.')); expect(logger.statusText, contains('For more information, see https://flutter.dev/go/plugin-platforms.')); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: ()=> logger, }); testUsingContext('created plugin with no --platforms flag should not print `no platforms` message if the existing plugin supports a platform.', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=ios', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(logger.errorText, isNot(contains(_kNoPlatformsMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('should show warning when disabled platforms are selected while creating a plugin', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platforms=android,ios,web,windows,macos,linux', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(logger.statusText, contains(_kDisabledPlatformRequestedMessage)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext("shouldn't show warning when only enabled platforms are selected while creating a plugin", () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platforms=android,ios,windows', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(logger.statusText, isNot(contains(_kDisabledPlatformRequestedMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true), Logger: () => logger, }); testUsingContext('should show warning when disabled platforms are selected while creating a app', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--platforms=android,ios,web,windows,macos,linux', projectDir.path]); await runner.run(<String>['create', '--no-pub', projectDir.path]); expect(logger.statusText, contains(_kDisabledPlatformRequestedMessage)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext("shouldn't show warning when only enabled platforms are selected while creating a app", () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin', '--platform=windows', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); expect(logger.statusText, isNot(contains(_kDisabledPlatformRequestedMessage))); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isWindowsEnabled: true, isAndroidEnabled: false, isIOSEnabled: false), Logger: () => logger, }); testUsingContext('default project has analysis_options.yaml set up correctly', () async { await _createProject( projectDir, <String>[], <String>[ 'analysis_options.yaml', ], ); final String dataPath = globals.fs.path.join( getFlutterRoot(), 'packages', 'flutter_tools', 'test', 'commands.shard', 'permeable', 'data', ); final File toAnalyze = await globals.fs.file(globals.fs.path.join(dataPath, 'to_analyze.dart.test')) .copy(globals.fs.path.join(projectDir.path, 'lib', 'to_analyze.dart')); final String relativePath = globals.fs.path.join('lib', 'to_analyze.dart'); final List<String> expectedFailures = <String>[ '$relativePath:11:7: use_key_in_widget_constructors', '$relativePath:20:3: prefer_const_constructors_in_immutables', '$relativePath:31:26: use_full_hex_values_for_flutter_colors', ]; expect(expectedFailures.length, '// LINT:'.allMatches(toAnalyze.readAsStringSync()).length); await _analyzeProject( projectDir.path, expectedFailures: expectedFailures, ); }, 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: mockStdio, ), }); testUsingContext('should escape ":" in project description', () async { await _createProject( projectDir, <String>[ '--no-pub', '--description', 'a: b', ], <String>[ 'pubspec.yaml', ], ); final String rawPubspec = await projectDir.childFile('pubspec.yaml').readAsString(); final Pubspec pubspec = Pubspec.parse(rawPubspec); expect(pubspec.description, 'a: b'); }); testUsingContext('create an FFI plugin with ios, then add macos', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', '--platform=ios', projectDir.path]); expect(projectDir.childDirectory('src'), exists); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); validatePubspecForPlugin( projectDir: projectDir.absolute.path, expectedPlatforms: const <String>[ 'ios', ], ffiPlugin: true, unexpectedPlatforms: <String>['some_platform'], ); await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', '--platform=macos', projectDir.path]); expect(projectDir.childDirectory('macos'), exists); expect( projectDir.childDirectory('example').childDirectory('macos'), exists); expect(projectDir.childDirectory('ios'), exists); expect(projectDir.childDirectory('example').childDirectory('ios'), exists); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isMacOSEnabled: true), }); for (final String template in <String>['package_ffi', 'plugin_ffi']) { testUsingContext('$template error android language', () async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<String> args = <String>[ 'create', '--no-pub', '--template=$template', '-a', 'kotlin', if (template == 'plugin_ffi') '--platforms=android', projectDir.path, ]; await expectLater( runner.run(args), throwsToolExit(message: 'The "android-language" option is not supported with the $template template: the language will always be C or C++.'), ); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), }); testUsingContext('$template error ios language', () async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<String> args = <String>[ 'create', '--no-pub', '--template=$template', '--ios-language', 'swift', if (template == 'plugin_ffi') '--platforms=ios', projectDir.path, ]; await expectLater( runner.run(args), throwsToolExit(message: 'The "ios-language" option is not supported with the $template template: the language will always be C or C++.'), ); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(isNativeAssetsEnabled: true), }); } testUsingContext('FFI plugins error web platform', () async { final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<String> args = <String>[ 'create', '--no-pub', '--template=plugin_ffi', '--platforms=web', projectDir.path, ]; await expectLater( runner.run(args), throwsToolExit(message: 'The web platform is not supported in plugin_ffi template.'), ); }); testUsingContext('should show warning when disabled platforms are selected while creating an FFI plugin', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', '--platforms=android,ios,windows,macos,linux', projectDir.path]); await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', projectDir.path]); expect(logger.statusText, contains(_kDisabledPlatformRequestedMessage)); }, overrides: <Type, Generator>{ FeatureFlags: () => TestFeatureFlags(), Logger: () => logger, }); testUsingContext('should not show warning for incompatible Java/template Gradle versions when Java version not found', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>['create', '--no-pub', '--platforms=android', projectDir.path]); expect(logger.warningText, isNot(contains(_kIncompatibleJavaVersionMessage))); }, overrides: <Type, Generator>{ Java: () => null, Logger: () => logger, }); testUsingContext('should not show warning for incompatible Java/template Gradle versions when created project type is irrelevant', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); // Test not creating a project for Android. await runner.run(<String>['create', '--no-pub', '--platforms=ios,windows,macos,linux', projectDir.path]); tryToDelete(projectDir); // Test creating a package (Dart-only code). await runner.run(<String>['create', '--no-pub', '--template=package', projectDir.path]); tryToDelete(projectDir); // Test creating project types without configured Gradle versions. await runner.run(<String>['create', '--no-pub', '--template=plugin', projectDir.path]); tryToDelete(projectDir); await runner.run(<String>['create', '--no-pub', '--template=plugin_ffi', projectDir.path]); expect(logger.warningText, isNot(contains(getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, templateAndroidGradlePluginVersion, 'app')))); expect(logger.warningText, isNot(contains(getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, templateAndroidGradlePluginVersion, 'package')))); expect(logger.warningText, isNot(contains(getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, templateAndroidGradlePluginVersion, 'plugin')))); expect(logger.warningText, isNot(contains(getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, templateAndroidGradlePluginVersion, 'pluginFfi')))); }, overrides: <Type, Generator>{ Java: () => FakeJava(version: const software.Version.withText(1000, 0, 0, '1000.0.0')), // Too high a version for template Gradle versions. Logger: () => logger, }); testUsingContext('should not show warning for incompatible Java/template AGP versions when project type unrelated', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); // Test not creating a project for Android. await runner.run(<String>['create', '--no-pub', '--platforms=ios,windows,macos,linux', projectDir.path]); tryToDelete(projectDir); // Test creating a package (Dart-only code). await runner.run(<String>['create', '--no-pub', '--template=package', projectDir.path]); expect(logger.warningText, isNot(contains(getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, templateAndroidGradlePluginVersion, 'app')))); expect(logger.warningText, isNot(contains(getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, templateAndroidGradlePluginVersion, 'package')))); }, overrides: <Type, Generator>{ Java: () => FakeJava(version: const software.Version.withText(0, 0, 0, '0.0.0')), // Too low a version for template AGP versions. Logger: () => logger, }); testUsingContext('should show warning for incompatible Java/template Gradle versions when detected', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<FlutterProjectType> relevantProjectTypes = <FlutterProjectType>[FlutterProjectType.app, FlutterProjectType.skeleton, FlutterProjectType.module]; for (final FlutterProjectType projectType in relevantProjectTypes) { final String relevantAgpVersion = projectType == FlutterProjectType.module ? _kIncompatibleAgpVersionForModule : templateAndroidGradlePluginVersion; final String expectedMessage = getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); final String unexpectedMessage = getIncompatibleJavaGradleAgpMessageHeader(true, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); await runner.run(<String>['create', '--no-pub', '--template=${projectType.cliName}', if (projectType != FlutterProjectType.module) '--platforms=android', projectDir.path]); // Check components of expected header warning message are printed. expect(logger.warningText, contains(expectedMessage)); expect(logger.warningText, isNot(contains(unexpectedMessage))); expect(logger.warningText, contains('./gradlew wrapper --gradle-version=<COMPATIBLE_GRADLE_VERSION>')); expect(logger.warningText, contains('https://docs.gradle.org/current/userguide/compatibility.html#java')); // Check expected file for updating Gradle version is present. if (projectType == FlutterProjectType.app || projectType == FlutterProjectType.skeleton) { expect(logger.warningText, contains(globals.fs.path.join(projectDir.path, 'android/gradle/wrapper/gradle-wrapper.properties'))); } else { // Project type is module. expect(logger.warningText, contains(globals.fs.path.join(projectDir.path, '.android/gradle/wrapper/gradle-wrapper.properties'))); } // Cleanup to reuse projectDir and logger checks. tryToDelete(projectDir); logger.clear(); } }, overrides: <Type, Generator>{ Java: () => FakeJava(version: const software.Version.withText(500, 0, 0, '500.0.0')), // Too high a version for template Gradle versions. Logger: () => logger, }); testUsingContext('should show warning for incompatible Java/template AGP versions when detected', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<FlutterProjectType> relevantProjectTypes = <FlutterProjectType>[FlutterProjectType.app, FlutterProjectType.skeleton, FlutterProjectType.pluginFfi, FlutterProjectType.module, FlutterProjectType.plugin]; for (final FlutterProjectType projectType in relevantProjectTypes) { final String relevantAgpVersion = projectType == FlutterProjectType.module ? _kIncompatibleAgpVersionForModule : templateAndroidGradlePluginVersion; final String expectedMessage = getIncompatibleJavaGradleAgpMessageHeader(true, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); final String unexpectedMessage = getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); await runner.run(<String>['create', '--no-pub', '--template=${projectType.cliName}', if (projectType != FlutterProjectType.module) '--platforms=android', projectDir.path]); // Check components of expected header warning message are printed. expect(logger.warningText, contains(expectedMessage)); expect(logger.warningText, isNot(contains(unexpectedMessage))); expect(logger.warningText, contains('https://developer.android.com/build/releases/gradle-plugin')); // Check expected file(s) for updating AGP version is/are present. if (projectType == FlutterProjectType.app || projectType == FlutterProjectType.skeleton || projectType == FlutterProjectType.pluginFfi) { expect(logger.warningText, contains(globals.fs.path.join(projectDir.path, 'android/build.gradle'))); } else if (projectType == FlutterProjectType.plugin) { expect(logger.warningText, contains(globals.fs.path.join(projectDir.path, 'android/app/build.gradle'))); } else { // Project type is module. expect(logger.warningText, contains(globals.fs.path.join(projectDir.path, '.android/build.gradle'))); expect(logger.warningText, contains(globals.fs.path.join(projectDir.path, '.android/app/build.gradle'))); expect(logger.warningText, contains(globals.fs.path.join(projectDir.path, '.android/Flutter/build.gradle'))); } // Cleanup to reuse projectDir and logger checks. tryToDelete(projectDir); logger.clear(); } }, overrides: <Type, Generator>{ Java: () => FakeJava(version: const software.Version.withText(1, 8, 0, '1.8.0')), // Too low a version for template AGP versions. Logger: () => logger, }); // The Java versions configured in the following tests will need updates as more Java versions are supported by AGP/Gradle: testUsingContext('should not show warning for incompatible Java/template AGP/Gradle versions when not detected', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<FlutterProjectType> relevantProjectTypes = <FlutterProjectType>[FlutterProjectType.app, FlutterProjectType.skeleton, FlutterProjectType.pluginFfi, FlutterProjectType.module, FlutterProjectType.plugin]; for (final FlutterProjectType projectType in relevantProjectTypes) { final String relevantAgpVersion = projectType == FlutterProjectType.module ? _kIncompatibleAgpVersionForModule : templateAndroidGradlePluginVersion; final String unexpectedIncompatibleAgpMessage = getIncompatibleJavaGradleAgpMessageHeader(true, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); final String unexpectedIncompatibleGradleMessage = getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); await runner.run(<String>['create', '--no-pub', '--template=${projectType.cliName}', if (projectType != FlutterProjectType.module) '--platforms=android', projectDir.path]); // We do not expect warnings for incompatible Java/template AGP versions if they are in fact, compatible. expect(logger.warningText, isNot(contains(unexpectedIncompatibleAgpMessage))); expect(logger.warningText, isNot(contains(unexpectedIncompatibleGradleMessage))); // Cleanup to reuse projectDir and logger checks. tryToDelete(projectDir); logger.clear(); } }, overrides: <Type, Generator>{ Java: () => FakeJava(version: const software.Version.withText(14, 0, 0, '14.0.0')), // Middle compatible Java version with current template AGP/Gradle versions. Logger: () => logger, }); testUsingContext('should not show warning for incompatible Java/template AGP/Gradle versions when not detected -- maximum compatible Java version', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<FlutterProjectType> relevantProjectTypes = <FlutterProjectType>[FlutterProjectType.app, FlutterProjectType.skeleton, FlutterProjectType.pluginFfi, FlutterProjectType.module, FlutterProjectType.plugin]; for (final FlutterProjectType projectType in relevantProjectTypes) { final String relevantAgpVersion = projectType == FlutterProjectType.module ? _kIncompatibleAgpVersionForModule : templateAndroidGradlePluginVersion; final String unexpectedIncompatibleAgpMessage = getIncompatibleJavaGradleAgpMessageHeader(true, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); final String unexpectedIncompatibleGradleMessage = getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); await runner.run(<String>['create', '--no-pub', '--template=${projectType.cliName}', if (projectType != FlutterProjectType.module) '--platforms=android', projectDir.path]); // We do not expect warnings for incompatible Java/template AGP versions if they are in fact, compatible. expect(logger.warningText, isNot(contains(unexpectedIncompatibleAgpMessage))); expect(logger.warningText, isNot(contains(unexpectedIncompatibleGradleMessage))); // Cleanup to reuse projectDir and logger checks. tryToDelete(projectDir); logger.clear(); } }, overrides: <Type, Generator>{ Java: () => FakeJava(version: const software.Version.withText(17, 0, 0, '18.0.0')), // Maximum compatible Java version with current template AGP/Gradle versions. Logger: () => logger, }); testUsingContext('should not show warning for incompatible Java/template AGP/Gradle versions when not detected -- minimum compatible Java version', () async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); final List<FlutterProjectType> relevantProjectTypes = <FlutterProjectType>[FlutterProjectType.app, FlutterProjectType.skeleton, FlutterProjectType.pluginFfi, FlutterProjectType.module, FlutterProjectType.plugin]; for (final FlutterProjectType projectType in relevantProjectTypes) { final String relevantAgpVersion = projectType == FlutterProjectType.module ? _kIncompatibleAgpVersionForModule : templateAndroidGradlePluginVersion; final String unexpectedIncompatibleAgpMessage = getIncompatibleJavaGradleAgpMessageHeader(true, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); final String unexpectedIncompatibleGradleMessage = getIncompatibleJavaGradleAgpMessageHeader(false, templateDefaultGradleVersion, relevantAgpVersion, projectType.cliName); await runner.run(<String>['create', '--no-pub', '--template=${projectType.cliName}', if (projectType != FlutterProjectType.module) '--platforms=android', projectDir.path]); // We do not expect warnings for incompatible Java/template AGP versions if they are in fact, compatible. expect(logger.warningText, isNot(contains(unexpectedIncompatibleAgpMessage))); expect(logger.warningText, isNot(contains(unexpectedIncompatibleGradleMessage))); // Cleanup to reuse projectDir and logger checks. tryToDelete(projectDir); logger.clear(); } }, overrides: <Type, Generator>{ Java: () => FakeJava(version: const software.Version.withText(11, 0, 0, '11.0.0')), // Minimum compatible Java version with current template AGP/Gradle versions. Logger: () => logger, }); testUsingContext('Does not double quote description in index.html on web', () async { await _createProject( projectDir, <String>['--no-pub', '--platforms=web'], <String>['pubspec.yaml', 'web/index.html'], ); final String rawIndexHtml = await projectDir.childDirectory('web').childFile('index.html').readAsString(); const String expectedDescription = '<meta name="description" content="A new Flutter project.">'; expect(rawIndexHtml.contains(expectedDescription), isTrue); }); testUsingContext('Does not double quote description in manifest.json on web', () async { await _createProject( projectDir, <String>['--no-pub', '--platforms=web'], <String>['pubspec.yaml', 'web/manifest.json'], ); final String rawManifestJson = await projectDir.childDirectory('web').childFile('manifest.json').readAsString(); const String expectedDescription = '"description": "A new Flutter project."'; expect(rawManifestJson.contains(expectedDescription), isTrue); }); } Future<void> _createProject( Directory dir, List<String> createArgs, List<String> expectedPaths, { List<String> unexpectedPaths = const <String>[], }) async { Cache.flutterRoot = '../..'; final CreateCommand command = CreateCommand(); final CommandRunner<void> runner = createTestCommandRunner(command); await runner.run(<String>[ 'create', ...createArgs, dir.path, ]); bool pathExists(String path) { final String fullPath = globals.fs.path.join(dir.path, path); return globals.fs.typeSync(fullPath) != FileSystemEntityType.notFound; } final List<String> failures = <String>[ for (final String path in expectedPaths) if (!pathExists(path)) 'Path "$path" does not exist.', for (final String path in unexpectedPaths) if (pathExists(path)) 'Path "$path" exists when it shouldn\'t.', ]; expect(failures, isEmpty, reason: failures.join('\n')); } Future<void> _createAndAnalyzeProject( Directory dir, List<String> createArgs, List<String> expectedPaths, { List<String> unexpectedPaths = const <String>[], }) async { await _createProject(dir, createArgs, expectedPaths, unexpectedPaths: unexpectedPaths); await _analyzeProject(dir.path); } 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 packageConfig = 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=$packageConfig', flutterToolsPath, ]; final ProcessResult snapshotResult = await Process.run( '../../bin/cache/dart-sdk/bin/dart', snapshotArgs, ); printOnFailure('Results of generating snapshot:'); printOnFailure(snapshotResult.stdout.toString()); printOnFailure(snapshotResult.stderr.toString()); expect(snapshotResult.exitCode, 0); } 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> _analyzeProject(String workingDir, { List<String> expectedFailures = const <String>[] }) async { final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( '..', '..', 'bin', 'cache', 'flutter_tools.snapshot', )); final List<String> args = <String>[ flutterToolsSnapshotPath, 'analyze', ]; final ProcessResult exec = await Process.run( globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), args, workingDirectory: workingDir, ); if (expectedFailures.isEmpty) { printOnFailure('Results of running analyzer:'); printOnFailure(exec.stdout.toString()); printOnFailure(exec.stderr.toString()); expect(exec.exitCode, 0); return; } expect(exec.exitCode, isNot(0)); String lineParser(String line) { try { final String analyzerSeparator = globals.platform.isWindows ? ' - ' : ' • '; final List<String> lineComponents = line.trim().split(analyzerSeparator); final String lintName = lineComponents.removeLast(); final String location = lineComponents.removeLast(); return '$location: $lintName'; } on RangeError catch (err) { throw RangeError('Received "$err" while trying to parse: "$line".'); } } final String stdout = exec.stdout.toString(); final List<String> errors = <String>[]; try { bool analyzeLineFound = false; const LineSplitter().convert(stdout).forEach((String line) { // Conditional to filter out any stdout from `pub get` if (!analyzeLineFound && line.startsWith('Analyzing')) { analyzeLineFound = true; return; } if (analyzeLineFound && line.trim().isNotEmpty) { errors.add(lineParser(line.trim())); } }); } on Exception catch (err) { fail('$err\n\nComplete STDOUT was:\n\n$stdout'); } expect(errors, unorderedEquals(expectedFailures), reason: 'Failed with stdout:\n\n$stdout'); } Future<void> _getPackages(Directory workingDir) async { final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( '..', '..', 'bin', 'cache', 'flutter_tools.snapshot', )); // While flutter test does get packages, it doesn't write version // files anymore. await Process.run( globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), <String>[ flutterToolsSnapshotPath, 'packages', 'get', ], workingDirectory: workingDir.path, ); } Future<void> _runFlutterTest(Directory workingDir, { String? target }) async { final String flutterToolsSnapshotPath = globals.fs.path.absolute(globals.fs.path.join( '..', '..', 'bin', 'cache', 'flutter_tools.snapshot', )); await _getPackages(workingDir); final List<String> args = <String>[ flutterToolsSnapshotPath, 'test', '--no-color', if (target != null) target, ]; final ProcessResult exec = await Process.run( globals.artifacts!.getArtifactPath(Artifact.engineDartBinary), args, workingDirectory: workingDir.path, ); printOnFailure('Output of running flutter test:'); printOnFailure(exec.stdout.toString()); printOnFailure(exec.stderr.toString()); expect(exec.exitCode, 0); } /// A ProcessManager that invokes a real process manager, but keeps /// track of all commands sent to it. class LoggingProcessManager extends LocalProcessManager { List<List<String>> commands = <List<String>>[]; @override Future<Process> start( List<Object> command, { String? workingDirectory, Map<String, String>? environment, bool includeParentEnvironment = true, bool runInShell = false, ProcessStartMode mode = ProcessStartMode.normal, }) { commands.add(command.map((Object arg) => arg.toString()).toList()); return super.start( command, workingDirectory: workingDirectory, environment: environment, includeParentEnvironment: includeParentEnvironment, runInShell: runInShell, mode: mode, ); } void clear() { commands.clear(); } } String _getStringValueFromPlist({required File plistFile, String? key}) { final List<String> plist = plistFile.readAsLinesSync().map((String line) => line.trim()).toList(); final int keyIndex = plist.indexOf('<key>$key</key>'); assert(keyIndex > 0); return plist[keyIndex+1].replaceAll('<string>', '').replaceAll('</string>', ''); } bool _getBooleanValueFromPlist({required File plistFile, String? key}) { final List<String> plist = plistFile.readAsLinesSync().map((String line) => line.trim()).toList(); final int keyIndex = plist.indexOf('<key>$key</key>'); assert(keyIndex > 0); return plist[keyIndex+1].replaceAll('<', '').replaceAll('/>', '') == 'true'; }
flutter/packages/flutter_tools/test/commands.shard/permeable/create_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/commands.shard/permeable/create_test.dart", "repo_id": "flutter", "token_count": 58141 }
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 'dart:async'; import 'package:flutter_tools/src/android/android_emulator.dart'; import 'package:flutter_tools/src/android/android_sdk.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; const String emulatorID = 'i1234'; const String errorText = '[Android emulator test error]'; const List<String> kEmulatorLaunchCommand = <String>[ 'emulator', '-avd', emulatorID, ]; void main() { group('android_emulator', () { testWithoutContext('flags emulators without config', () { const String emulatorID = '1234'; final AndroidEmulator emulator = AndroidEmulator( emulatorID, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), ); expect(emulator.id, emulatorID); expect(emulator.hasConfig, false); }); testWithoutContext('flags emulators with config', () { const String emulatorID = '1234'; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: const <String, String>{'name': 'test'}, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), ); expect(emulator.id, emulatorID); expect(emulator.hasConfig, true); }); testWithoutContext('reads expected metadata', () { const String emulatorID = '1234'; const String manufacturer = 'Me'; const String displayName = 'The best one'; final Map<String, String> properties = <String, String>{ 'hw.device.manufacturer': manufacturer, 'avd.ini.displayname': displayName, }; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: properties, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), ); expect(emulator.id, emulatorID); expect(emulator.name, displayName); expect(emulator.manufacturer, manufacturer); expect(emulator.category, Category.mobile); expect(emulator.platformType, PlatformType.android); }); testWithoutContext('prefers displayname for name', () { const String emulatorID = '1234'; const String displayName = 'The best one'; final Map<String, String> properties = <String, String>{ 'avd.ini.displayname': displayName, }; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: properties, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), ); expect(emulator.name, displayName); }); testWithoutContext('uses cleaned up ID if no displayname is set', () { // Android Studio uses the ID with underscores replaced with spaces // for the name if displayname is not set so we do the same. const String emulatorID = 'This_is_my_ID'; final Map<String, String> properties = <String, String>{ 'avd.ini.notadisplayname': 'this is not a display name', }; final AndroidEmulator emulator = AndroidEmulator( emulatorID, properties: properties, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), androidSdk: FakeAndroidSdk(), ); expect(emulator.name, 'This is my ID'); }); testWithoutContext('parses ini files', () { const String iniFile = ''' hw.device.name=My Test Name #hw.device.name=Bad Name hw.device.manufacturer=Me avd.ini.displayname = dispName '''; final Map<String, String> results = parseIniLines(iniFile.split('\n')); expect(results['hw.device.name'], 'My Test Name'); expect(results['hw.device.manufacturer'], 'Me'); expect(results['avd.ini.displayname'], 'dispName'); }); }); group('Android emulator launch ', () { late FakeAndroidSdk mockSdk; setUp(() { mockSdk = FakeAndroidSdk(); mockSdk.emulatorPath = 'emulator'; }); testWithoutContext('succeeds', () async { final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand(command: kEmulatorLaunchCommand), ]), androidSdk: mockSdk, logger: BufferLogger.test(), ); await emulator.launch(startupDuration: Duration.zero); }); testWithoutContext('succeeds with coldboot launch', () async { final List<String> kEmulatorLaunchColdBootCommand = <String>[ ...kEmulatorLaunchCommand, '-no-snapshot-load', ]; final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand(command: kEmulatorLaunchColdBootCommand), ]), androidSdk: mockSdk, logger: BufferLogger.test(), ); await emulator.launch(startupDuration: Duration.zero, coldBoot: true); }); testWithoutContext('prints error on failure', () async { final BufferLogger logger = BufferLogger.test(); final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: kEmulatorLaunchCommand, exitCode: 1, stderr: errorText, stdout: 'dummy text', ), ]), androidSdk: mockSdk, logger: logger, ); await emulator.launch(startupDuration: Duration.zero); expect(logger.errorText, contains(errorText)); }); testWithoutContext('prints nothing on late failure with empty stderr', () async { final BufferLogger logger = BufferLogger.test(); final AndroidEmulator emulator = AndroidEmulator(emulatorID, processManager: FakeProcessManager.list(<FakeCommand>[ FakeCommand( command: kEmulatorLaunchCommand, exitCode: 1, stdout: 'dummy text', completer: Completer<void>(), ), ]), androidSdk: mockSdk, logger: logger, ); await emulator.launch(startupDuration: Duration.zero); expect(logger.errorText, isEmpty); }); testWithoutContext('throws if emulator not found', () async { mockSdk.emulatorPath = null; final AndroidEmulator emulator = AndroidEmulator( emulatorID, processManager: FakeProcessManager.empty(), androidSdk: mockSdk, logger: BufferLogger.test(), ); await expectLater( () => emulator.launch(startupDuration: Duration.zero), throwsA(isException.having( (Exception exception) => exception.toString(), 'description', contains('Emulator is missing from the Android SDK'), )), ); }); }); } class FakeAndroidSdk extends Fake implements AndroidSdk { @override String? emulatorPath; }
flutter/packages/flutter_tools/test/general.shard/android/android_emulator_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/android/android_emulator_test.dart", "repo_id": "flutter", "token_count": 2823 }
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/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/isolated/mustache_template.dart'; import 'package:flutter_tools/src/template.dart'; import '../../src/common.dart'; void main() { testWithoutContext('kotlin reserved keywords', () { final FileSystem fileSystem = MemoryFileSystem.test(); final BufferLogger logger = BufferLogger.test(); final Directory rootDir = fileSystem.currentDirectory; final Directory templateSource = rootDir.childDirectory('src'); final Directory imageSourceDir = templateSource; final Directory destination = rootDir.childDirectory('dest'); const String outputClass = 'SomeClass.kt'; final File sourceFile = templateSource.childFile('$outputClass.tmpl'); templateSource.createSync(); sourceFile.writeAsStringSync('package {{androidIdentifier}};'); final Template template = Template( templateSource, imageSourceDir, fileSystem: fileSystem, logger: logger, templateRenderer: const MustacheTemplateRenderer(), ); final Map<String, Object> context = <String, Object>{ 'androidIdentifier': 'is.in.when.there', }; template.render(destination, context); final File destinationFile = destination.childFile(outputClass); expect(destinationFile.readAsStringSync(), equals('package `is`.`in`.`when`.there;')); }); }
flutter/packages/flutter_tools/test/general.shard/android/template_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/android/template_test.dart", "repo_id": "flutter", "token_count": 515 }
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 'package:flutter_tools/src/base/command_help.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/base/terminal.dart' show AnsiTerminal, OutputPreferences; import '../../src/common.dart'; import '../../src/fakes.dart'; CommandHelp _createCommandHelp({ required bool ansi, required int wrapColumn, }) { final Platform platform = FakePlatform( stdoutSupportsAnsi: ansi, ); return CommandHelp( logger: BufferLogger.test(), terminal: AnsiTerminal( stdio: FakeStdio(), platform: platform, ), platform: platform, outputPreferences: OutputPreferences.test( showColor: ansi, wrapColumn: wrapColumn, ), ); } // Used to use the message length in different scenarios in a DRY way void _testMessageLength({ required bool stdoutSupportsAnsi, required int maxTestLineLength, required int wrapColumn, }) { final CommandHelp commandHelp = _createCommandHelp( ansi: stdoutSupportsAnsi, wrapColumn: wrapColumn, ); int expectedWidth = maxTestLineLength; if (stdoutSupportsAnsi) { const int ansiMetaCharactersLength = 33; expectedWidth += ansiMetaCharactersLength; } expect(commandHelp.I.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.L.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.M.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.P.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.R.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.S.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.U.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.a.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.b.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.c.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.d.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.f.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.g.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.hWithDetails.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.hWithoutDetails.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.i.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.k.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.o.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.p.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.q.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.r.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.s.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.t.toString().length, lessThanOrEqualTo(expectedWidth)); expect(commandHelp.w.toString().length, lessThanOrEqualTo(expectedWidth)); } void main() { group('CommandHelp', () { group('toString', () { testWithoutContext('ends with a resetBold when it has parenthetical text', () { // This is apparently required to work around bugs in some terminal clients. final Platform platform = FakePlatform(stdoutSupportsAnsi: true); final AnsiTerminal terminal = AnsiTerminal(stdio: FakeStdio(), platform: platform); final CommandHelpOption commandHelpOption = CommandHelpOption( 'tester', 'for testing', platform: platform, outputPreferences: OutputPreferences.test(showColor: true), terminal: terminal, logger: BufferLogger.test(), inParenthesis: 'Parenthetical', ); expect(commandHelpOption.toString(), endsWith(AnsiTerminal.resetBold)); }); testWithoutContext('should have a bold command key', () { final CommandHelp commandHelp = _createCommandHelp( ansi: true, wrapColumn: maxLineWidth, ); expect(commandHelp.I.toString(), startsWith('\x1B[1mI\x1B[22m')); expect(commandHelp.L.toString(), startsWith('\x1B[1mL\x1B[22m')); expect(commandHelp.M.toString(), startsWith('\x1B[1mM\x1B[22m')); expect(commandHelp.P.toString(), startsWith('\x1B[1mP\x1B[22m')); expect(commandHelp.R.toString(), startsWith('\x1B[1mR\x1B[22m')); expect(commandHelp.S.toString(), startsWith('\x1B[1mS\x1B[22m')); expect(commandHelp.U.toString(), startsWith('\x1B[1mU\x1B[22m')); expect(commandHelp.a.toString(), startsWith('\x1B[1ma\x1B[22m')); expect(commandHelp.b.toString(), startsWith('\x1B[1mb\x1B[22m')); expect(commandHelp.c.toString(), startsWith('\x1B[1mc\x1B[22m')); expect(commandHelp.d.toString(), startsWith('\x1B[1md\x1B[22m')); expect(commandHelp.g.toString(), startsWith('\x1B[1mg\x1B[22m')); expect(commandHelp.hWithDetails.toString(), startsWith('\x1B[1mh\x1B[22m')); expect(commandHelp.hWithoutDetails.toString(), startsWith('\x1B[1mh\x1B[22m')); expect(commandHelp.i.toString(), startsWith('\x1B[1mi\x1B[22m')); expect(commandHelp.k.toString(), startsWith('\x1B[1mk\x1B[22m')); expect(commandHelp.o.toString(), startsWith('\x1B[1mo\x1B[22m')); expect(commandHelp.p.toString(), startsWith('\x1B[1mp\x1B[22m')); expect(commandHelp.q.toString(), startsWith('\x1B[1mq\x1B[22m')); expect(commandHelp.r.toString(), startsWith('\x1B[1mr\x1B[22m')); expect(commandHelp.s.toString(), startsWith('\x1B[1ms\x1B[22m')); expect(commandHelp.t.toString(), startsWith('\x1B[1mt\x1B[22m')); expect(commandHelp.w.toString(), startsWith('\x1B[1mw\x1B[22m')); }); testWithoutContext('commands that should have a grey bolden parenthetical text', () { final CommandHelp commandHelp = _createCommandHelp( ansi: true, wrapColumn: maxLineWidth, ); expect(commandHelp.I.toString(), contains('\x1B[90m(debugInvertOversizedImages)\x1B[39m')); expect(commandHelp.L.toString(), contains('\x1B[90m(debugDumpLayerTree)\x1B[39m')); expect(commandHelp.P.toString(), contains('\x1B[90m(WidgetsApp.showPerformanceOverlay)\x1B[39m')); expect(commandHelp.S.toString(), contains('\x1B[90m(debugDumpSemantics)\x1B[39m')); expect(commandHelp.U.toString(), contains('\x1B[90m(debugDumpSemantics)\x1B[39m')); expect(commandHelp.a.toString(), contains('\x1B[90m(debugProfileWidgetBuilds)\x1B[39m')); expect(commandHelp.b.toString(), contains('\x1B[90m(debugBrightnessOverride)\x1B[39m')); expect(commandHelp.f.toString(), contains('\x1B[90m(debugDumpFocusTree)\x1B[39m')); expect(commandHelp.i.toString(), contains('\x1B[90m(WidgetsApp.showWidgetInspectorOverride)\x1B[39m')); expect(commandHelp.o.toString(), contains('\x1B[90m(defaultTargetPlatform)\x1B[39m')); expect(commandHelp.p.toString(), contains('\x1B[90m(debugPaintSizeEnabled)\x1B[39m')); expect(commandHelp.t.toString(), contains('\x1B[90m(debugDumpRenderTree)\x1B[39m')); expect(commandHelp.w.toString(), contains('\x1B[90m(debugDumpApp)\x1B[39m')); }); testWithoutContext('should not create a help text longer than maxLineWidth without ansi support', () { _testMessageLength( stdoutSupportsAnsi: false, wrapColumn: 0, maxTestLineLength: maxLineWidth, ); }); testWithoutContext('should not create a help text longer than maxLineWidth with ansi support', () { _testMessageLength( stdoutSupportsAnsi: true, wrapColumn: 0, maxTestLineLength: maxLineWidth, ); }); testWithoutContext('should not create a help text longer than outputPreferences.wrapColumn without ansi support', () { _testMessageLength( stdoutSupportsAnsi: false, wrapColumn: OutputPreferences.kDefaultTerminalColumns, maxTestLineLength: OutputPreferences.kDefaultTerminalColumns, ); }); testWithoutContext('should not create a help text longer than outputPreferences.wrapColumn with ansi support', () { _testMessageLength( stdoutSupportsAnsi: true, wrapColumn: OutputPreferences.kDefaultTerminalColumns, maxTestLineLength: OutputPreferences.kDefaultTerminalColumns, ); }); testWithoutContext('should create the correct help text with ansi support', () { final CommandHelp commandHelp = _createCommandHelp( ansi: true, wrapColumn: maxLineWidth, ); // The trailing \x1B[22m is to work around reported bugs in some terminal clients. expect(commandHelp.I.toString(), equals('\x1B[1mI\x1B[22m Toggle oversized image inversion. \x1B[90m(debugInvertOversizedImages)\x1B[39m\x1B[22m')); expect(commandHelp.L.toString(), equals('\x1B[1mL\x1B[22m Dump layer tree to the console. \x1B[90m(debugDumpLayerTree)\x1B[39m\x1B[22m')); expect(commandHelp.M.toString(), equals('\x1B[1mM\x1B[22m Write SkSL shaders to a unique file in the project directory.')); expect(commandHelp.P.toString(), equals('\x1B[1mP\x1B[22m Toggle performance overlay. \x1B[90m(WidgetsApp.showPerformanceOverlay)\x1B[39m\x1B[22m')); expect(commandHelp.R.toString(), equals('\x1B[1mR\x1B[22m Hot restart.')); expect(commandHelp.S.toString(), equals('\x1B[1mS\x1B[22m Dump accessibility tree in traversal order. \x1B[90m(debugDumpSemantics)\x1B[39m\x1B[22m')); expect(commandHelp.U.toString(), equals('\x1B[1mU\x1B[22m Dump accessibility tree in inverse hit test order. \x1B[90m(debugDumpSemantics)\x1B[39m\x1B[22m')); expect(commandHelp.a.toString(), equals('\x1B[1ma\x1B[22m Toggle timeline events for all widget build methods. \x1B[90m(debugProfileWidgetBuilds)\x1B[39m\x1B[22m')); expect(commandHelp.b.toString(), equals('\x1B[1mb\x1B[22m Toggle platform brightness (dark and light mode). \x1B[90m(debugBrightnessOverride)\x1B[39m\x1B[22m')); expect(commandHelp.c.toString(), equals('\x1B[1mc\x1B[22m Clear the screen')); expect(commandHelp.d.toString(), equals('\x1B[1md\x1B[22m Detach (terminate "flutter run" but leave application running).')); expect(commandHelp.f.toString(), equals('\x1B[1mf\x1B[22m Dump focus tree to the console. \x1B[90m(debugDumpFocusTree)\x1B[39m\x1B[22m')); expect(commandHelp.g.toString(), equals('\x1B[1mg\x1B[22m Run source code generators.')); expect(commandHelp.hWithDetails.toString(), equals('\x1B[1mh\x1B[22m Repeat this help message.')); expect(commandHelp.hWithoutDetails.toString(), equals('\x1B[1mh\x1B[22m List all available interactive commands.')); expect(commandHelp.i.toString(), equals('\x1B[1mi\x1B[22m Toggle widget inspector. \x1B[90m(WidgetsApp.showWidgetInspectorOverride)\x1B[39m\x1B[22m')); expect(commandHelp.o.toString(), equals('\x1B[1mo\x1B[22m Simulate different operating systems. \x1B[90m(defaultTargetPlatform)\x1B[39m\x1B[22m')); expect(commandHelp.p.toString(), equals('\x1B[1mp\x1B[22m Toggle the display of construction lines. \x1B[90m(debugPaintSizeEnabled)\x1B[39m\x1B[22m')); expect(commandHelp.q.toString(), equals('\x1B[1mq\x1B[22m Quit (terminate the application on the device).')); expect(commandHelp.r.toString(), equals('\x1B[1mr\x1B[22m Hot reload. $fire$fire$fire')); expect(commandHelp.s.toString(), equals('\x1B[1ms\x1B[22m Save a screenshot to flutter.png.')); expect(commandHelp.t.toString(), equals('\x1B[1mt\x1B[22m Dump rendering tree to the console. \x1B[90m(debugDumpRenderTree)\x1B[39m\x1B[22m')); expect(commandHelp.v.toString(), equals('\x1B[1mv\x1B[22m Open Flutter DevTools.')); expect(commandHelp.w.toString(), equals('\x1B[1mw\x1B[22m Dump widget hierarchy to the console. \x1B[90m(debugDumpApp)\x1B[39m\x1B[22m')); }); testWithoutContext('should create the correct help text without ansi support', () { final CommandHelp commandHelp = _createCommandHelp( ansi: false, wrapColumn: maxLineWidth, ); expect(commandHelp.I.toString(), equals('I Toggle oversized image inversion. (debugInvertOversizedImages)')); expect(commandHelp.M.toString(), equals('M Write SkSL shaders to a unique file in the project directory.')); expect(commandHelp.L.toString(), equals('L Dump layer tree to the console. (debugDumpLayerTree)')); expect(commandHelp.P.toString(), equals('P Toggle performance overlay. (WidgetsApp.showPerformanceOverlay)')); expect(commandHelp.R.toString(), equals('R Hot restart.')); expect(commandHelp.S.toString(), equals('S Dump accessibility tree in traversal order. (debugDumpSemantics)')); expect(commandHelp.U.toString(), equals('U Dump accessibility tree in inverse hit test order. (debugDumpSemantics)')); expect(commandHelp.a.toString(), equals('a Toggle timeline events for all widget build methods. (debugProfileWidgetBuilds)')); expect(commandHelp.b.toString(), equals('b Toggle platform brightness (dark and light mode). (debugBrightnessOverride)')); expect(commandHelp.c.toString(), equals('c Clear the screen')); expect(commandHelp.d.toString(), equals('d Detach (terminate "flutter run" but leave application running).')); expect(commandHelp.g.toString(), equals('g Run source code generators.')); expect(commandHelp.hWithDetails.toString(), equals('h Repeat this help message.')); expect(commandHelp.hWithoutDetails.toString(), equals('h List all available interactive commands.')); expect(commandHelp.i.toString(), equals('i Toggle widget inspector. (WidgetsApp.showWidgetInspectorOverride)')); expect(commandHelp.o.toString(), equals('o Simulate different operating systems. (defaultTargetPlatform)')); expect(commandHelp.p.toString(), equals('p Toggle the display of construction lines. (debugPaintSizeEnabled)')); expect(commandHelp.q.toString(), equals('q Quit (terminate the application on the device).')); expect(commandHelp.r.toString(), equals('r Hot reload. $fire$fire$fire')); expect(commandHelp.s.toString(), equals('s Save a screenshot to flutter.png.')); expect(commandHelp.t.toString(), equals('t Dump rendering tree to the console. (debugDumpRenderTree)')); expect(commandHelp.v.toString(), equals('v Open Flutter DevTools.')); expect(commandHelp.w.toString(), equals('w Dump widget hierarchy to the console. (debugDumpApp)')); }); }); }); }
flutter/packages/flutter_tools/test/general.shard/base/command_help_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/base/command_help_test.dart", "repo_id": "flutter", "token_count": 6353 }
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:async'; import 'package:flutter_tools/src/base/task_queue.dart'; import '../../src/common.dart'; void main() { group('TaskQueue', () { /// A special test designed to check shared [TaskQueue] /// behavior when exceptions occur after a delay in the passed closures to /// [TaskQueue.add]. test('no deadlock when delayed exceptions fire in closures', () async { final TaskQueue<void> sharedTracker = TaskQueue<void>(maxJobs: 2); expect(() async { final Future<void> t = Future<void>.delayed(const Duration(milliseconds: 10), () => throw TestException()); await sharedTracker.add(() => t); return t; }, throwsA(const TypeMatcher<TestException>())); expect(() async { final Future<void> t = Future<void>.delayed(const Duration(milliseconds: 10), () => throw TestException()); await sharedTracker.add(() => t); return t; }, throwsA(const TypeMatcher<TestException>())); expect(() async { final Future<void> t = Future<void>.delayed(const Duration(milliseconds: 10), () => throw TestException()); await sharedTracker.add(() => t); return t; }, throwsA(const TypeMatcher<TestException>())); expect(() async { final Future<void> t = Future<void>.delayed(const Duration(milliseconds: 10), () => throw TestException()); await sharedTracker.add(() => t); return t; }, throwsA(const TypeMatcher<TestException>())); /// We deadlock here if the exception is not handled properly. await sharedTracker.tasksComplete; }); test('basic sequential processing works with no deadlock', () async { final Set<int> completed = <int>{}; final TaskQueue<void> tracker = TaskQueue<void>(maxJobs: 1); await tracker.add(() async => completed.add(1)); await tracker.add(() async => completed.add(2)); await tracker.add(() async => completed.add(3)); await tracker.tasksComplete; expect(completed.length, equals(3)); }); test('basic sequential processing works on exceptions', () async { final Set<int> completed = <int>{}; final TaskQueue<void> tracker = TaskQueue<void>(maxJobs: 1); await tracker.add(() async => completed.add(0)); await tracker.add(() async => throw TestException()).then((_) {}, onError: (Object _) {}); await tracker.add(() async => throw TestException()).then((_) {}, onError: (Object _) {}); await tracker.add(() async => completed.add(3)); await tracker.tasksComplete; expect(completed.length, equals(2)); }); /// Verify that if there are more exceptions than the maximum number /// of in-flight [Future]s that there is no deadlock. test('basic parallel processing works with no deadlock', () async { final Set<int> completed = <int>{}; final TaskQueue<void> tracker = TaskQueue<void>(maxJobs: 10); for (int i = 0; i < 100; i++) { await tracker.add(() async => completed.add(i)); } await tracker.tasksComplete; expect(completed.length, equals(100)); }); test('basic parallel processing works on exceptions', () async { final Set<int> completed = <int>{}; final TaskQueue<void> tracker = TaskQueue<void>(maxJobs: 10); for (int i = 0; i < 50; i++) { await tracker.add(() async => completed.add(i)); } for (int i = 50; i < 65; i++) { try { await tracker.add(() async => throw TestException()); } on TestException { // Ignore } } for (int i = 65; i < 100; i++) { await tracker.add(() async => completed.add(i)); } await tracker.tasksComplete; expect(completed.length, equals(85)); }); }); } class TestException implements Exception {}
flutter/packages/flutter_tools/test/general.shard/base/task_queue_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/base/task_queue_test.dart", "repo_id": "flutter", "token_count": 1453 }
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: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/build_info.dart'; import 'package:flutter_tools/src/build_system/build_system.dart'; import 'package:flutter_tools/src/build_system/targets/dart_plugin_registrant.dart'; import 'package:flutter_tools/src/project.dart'; import '../../../src/common.dart'; import '../../../src/context.dart'; const String _kEmptyPubspecFile = ''' name: path_provider_example dependencies: flutter: sdk: flutter '''; const String _kEmptyPackageJson = ''' { "configVersion": 2, "packages": [ { "name": "path_provider_example", "rootUri": "../", "packageUri": "lib/", "languageVersion": "2.12" } ] } '''; const String _kSamplePackageJson = ''' { "configVersion": 2, "packages": [ { "name": "path_provider_linux", "rootUri": "/path_provider_linux", "packageUri": "lib/", "languageVersion": "2.12" }, { "name": "path_provider_example", "rootUri": "../", "packageUri": "lib/", "languageVersion": "2.12" } ] } '''; const String _kSamplePackagesFile = ''' path_provider_linux:/path_provider_linux/lib/ path_provider_example:lib/ '''; const String _kSamplePubspecFile = ''' name: path_provider_example description: Demonstrates how to use the path_provider plugin. dependencies: flutter: sdk: flutter path_provider_linux: 1.0.0 '''; const String _kSamplePluginPubspec = ''' name: path_provider_linux description: linux implementation of the path_provider plugin // version: 2.0.1 // homepage: https://github.com/flutter/plugins/tree/master/packages/path_provider/path_provider_linux flutter: plugin: implements: path_provider platforms: linux: dartPluginClass: PathProviderLinux pluginClass: none environment: sdk: '>=3.2.0-0 <4.0.0' flutter: ">=1.20.0" '''; void main() { group('Dart plugin registrant' , () { late FileSystem fileSystem; setUp(() { fileSystem = MemoryFileSystem.test(); }); testWithoutContext('skipped based on environment.generateDartPluginRegistry', () async { final Environment environment = Environment.test( fileSystem.currentDirectory, artifacts: Artifacts.test(), fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), ); expect(const DartPluginRegistrantTarget().canSkip(environment), isTrue); final Environment environment2 = Environment.test( fileSystem.currentDirectory, artifacts: Artifacts.test(), fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), generateDartPluginRegistry: true); expect(const DartPluginRegistrantTarget().canSkip(environment2), isFalse); }); testWithoutContext('skipped based on platform', () async { const Map<String, bool> canSkip = <String, bool>{ 'darwin-x64': false, 'linux-x64': false, 'linux-arm64': false, 'windows-x64': false, 'web-javascript': true, 'ios': false, 'android': false, 'fuchsia-arm64': true, 'fuchsia-x64': true, }; for (final String targetPlatform in canSkip.keys) { expect( const DartPluginRegistrantTarget().canSkip( Environment.test( fileSystem.currentDirectory, artifacts: Artifacts.test(), fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), generateDartPluginRegistry: true, defines: <String, String>{ kTargetPlatform: targetPlatform, }, ), ), canSkip[targetPlatform], ); } }); testUsingContext("doesn't generate dart_plugin_registrant.dart if there aren't Dart plugins", () async { final Directory projectDir = fileSystem.directory('project')..createSync(); final Environment environment = Environment.test( fileSystem.currentDirectory, projectDir: projectDir, artifacts: Artifacts.test(), fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), defines: <String, String>{ kTargetFile: projectDir.childDirectory('lib').childFile('main.dart').absolute.path, }, generateDartPluginRegistry: true); projectDir .childDirectory('.dart_tool') .childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync(_kSamplePackageJson); projectDir.childFile('pubspec.yaml').createSync(); projectDir.childFile('.packages').createSync(); final FlutterProject testProject = FlutterProject.fromDirectoryTest(projectDir); await DartPluginRegistrantTarget.test(testProject).build(environment); final File generatedMain = projectDir .childDirectory('.dart_tool') .childDirectory('flutter_build') .childFile('dart_plugin_registrant.dart'); expect(generatedMain.existsSync(), isFalse); }); testUsingContext('regenerates dart_plugin_registrant.dart', () async { final Directory projectDir = fileSystem.directory('project')..createSync(); final Environment environment = Environment.test( fileSystem.currentDirectory, projectDir: projectDir, artifacts: Artifacts.test(), fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), defines: <String, String>{ kTargetFile: projectDir.childDirectory('lib').childFile('main.dart').absolute.path, }, generateDartPluginRegistry: true); projectDir .childDirectory('.dart_tool') .childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync(_kSamplePackageJson); projectDir.childFile('pubspec.yaml').writeAsStringSync(_kSamplePubspecFile); projectDir.childFile('.packages').writeAsStringSync(_kSamplePackagesFile); projectDir.childDirectory('lib').childFile('main.dart').createSync(recursive: true); environment.fileSystem.currentDirectory .childDirectory('path_provider_linux') .childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(_kSamplePluginPubspec); final FlutterProject testProject = FlutterProject.fromDirectoryTest(projectDir); await DartPluginRegistrantTarget.test(testProject).build(environment); final File generatedMain = projectDir .childDirectory('.dart_tool') .childDirectory('flutter_build') .childFile('dart_plugin_registrant.dart'); final String mainContent = generatedMain.readAsStringSync(); expect( mainContent, equals( '//\n' '// Generated file. Do not edit.\n' '// This file is generated from template in file `flutter_tools/lib/src/flutter_plugins.dart`.\n' '//\n' '\n' '// @dart = 2.12\n' '\n' "import 'dart:io'; // flutter_ignore: dart_io_import.\n" "import 'package:path_provider_linux/path_provider_linux.dart';\n" '\n' "@pragma('vm:entry-point')\n" 'class _PluginRegistrant {\n' '\n' " @pragma('vm:entry-point')\n" ' static void register() {\n' ' if (Platform.isAndroid) {\n' ' } else if (Platform.isIOS) {\n' ' } else if (Platform.isLinux) {\n' ' try {\n' ' PathProviderLinux.registerWith();\n' ' } catch (err) {\n' ' print(\n' " '`path_provider_linux` threw an error: \$err. '\n" " 'The app may not function as expected until you remove this plugin from pubspec.yaml'\n" ' );\n' ' }\n' '\n' ' } else if (Platform.isMacOS) {\n' ' } else if (Platform.isWindows) {\n' ' }\n' ' }\n' '}\n' ), ); }); testUsingContext('removes dart_plugin_registrant.dart if plugins are removed from pubspec.yaml', () async { final Directory projectDir = fileSystem.directory('project')..createSync(); final Environment environment = Environment.test( fileSystem.currentDirectory, projectDir: projectDir, artifacts: Artifacts.test(), fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), defines: <String, String>{ kTargetFile: projectDir.childDirectory('lib').childFile('main.dart').absolute.path, }, generateDartPluginRegistry: true); final File config = projectDir .childDirectory('.dart_tool') .childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync(_kSamplePackageJson); final File pubspec = projectDir.childFile('pubspec.yaml')..writeAsStringSync(_kSamplePubspecFile); final File packages = projectDir.childFile('.packages')..writeAsStringSync(_kSamplePackagesFile); environment.fileSystem.currentDirectory .childDirectory('path_provider_linux') .childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(_kSamplePluginPubspec); final File generatedMain = projectDir .childDirectory('.dart_tool') .childDirectory('flutter_build') .childFile('dart_plugin_registrant.dart'); final FlutterProject testProject = FlutterProject.fromDirectoryTest(projectDir); await DartPluginRegistrantTarget.test(testProject).build(environment); expect(generatedMain.existsSync(), isTrue); // Simulate a user removing everything from pubspec.yaml. pubspec.writeAsStringSync(_kEmptyPubspecFile); packages.writeAsStringSync(_kEmptyPackageJson); config.writeAsStringSync(_kEmptyPackageJson); await DartPluginRegistrantTarget.test(testProject).build(environment); expect(generatedMain.existsSync(), isFalse); }); testUsingContext('target file is outside the current project package', () async { final Directory projectDir = fileSystem.directory('project')..createSync(); final Environment environment = Environment.test( fileSystem.currentDirectory, projectDir: projectDir, artifacts: Artifacts.test(), fileSystem: fileSystem, logger: BufferLogger.test(), processManager: FakeProcessManager.any(), defines: <String, String>{ kTargetFile: fileSystem.directory('root').childFile('external.dart').absolute.path, }, generateDartPluginRegistry: true); projectDir .childDirectory('.dart_tool') .childFile('package_config.json') ..createSync(recursive: true) ..writeAsStringSync(_kSamplePackageJson); projectDir.childFile('pubspec.yaml').writeAsStringSync(_kSamplePubspecFile); projectDir.childFile('.packages').writeAsStringSync(_kSamplePackagesFile); projectDir.childDirectory('lib').childFile('main.dart').createSync(recursive: true); environment.fileSystem.currentDirectory .childDirectory('path_provider_linux') .childFile('pubspec.yaml') ..createSync(recursive: true) ..writeAsStringSync(_kSamplePluginPubspec); final FlutterProject testProject = FlutterProject.fromDirectoryTest(projectDir); await DartPluginRegistrantTarget.test(testProject).build(environment); final File generatedMain = projectDir .childDirectory('.dart_tool') .childDirectory('flutter_build') .childFile('dart_plugin_registrant.dart'); final String mainContent = generatedMain.readAsStringSync(); expect( mainContent, equals( '//\n' '// Generated file. Do not edit.\n' '// This file is generated from template in file `flutter_tools/lib/src/flutter_plugins.dart`.\n' '//\n' '\n' '// @dart = 2.12\n' '\n' "import 'dart:io'; // flutter_ignore: dart_io_import.\n" "import 'package:path_provider_linux/path_provider_linux.dart';\n" '\n' "@pragma('vm:entry-point')\n" 'class _PluginRegistrant {\n' '\n' " @pragma('vm:entry-point')\n" ' static void register() {\n' ' if (Platform.isAndroid) {\n' ' } else if (Platform.isIOS) {\n' ' } else if (Platform.isLinux) {\n' ' try {\n' ' PathProviderLinux.registerWith();\n' ' } catch (err) {\n' ' print(\n' " '`path_provider_linux` threw an error: \$err. '\n" " 'The app may not function as expected until you remove this plugin from pubspec.yaml'\n" ' );\n' ' }\n' '\n' ' } else if (Platform.isMacOS) {\n' ' } else if (Platform.isWindows) {\n' ' }\n' ' }\n' '}\n' ), ); }); }); }
flutter/packages/flutter_tools/test/general.shard/build_system/targets/dart_plugin_registrant_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/build_system/targets/dart_plugin_registrant_test.dart", "repo_id": "flutter", "token_count": 5935 }
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/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/tools/shader_compiler.dart'; import 'package:flutter_tools/src/compile.dart'; import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/resident_runner.dart'; import 'package:flutter_tools/src/run_cold.dart'; import 'package:flutter_tools/src/tracing.dart'; import 'package:flutter_tools/src/vmservice.dart'; import 'package:test/fake.dart'; import 'package:vm_service/vm_service.dart'; import '../src/common.dart'; import '../src/context.dart'; void main() { testUsingContext('Exits with code 2 when HttpException is thrown ' 'during VM service connection', () async { final FakeResidentCompiler residentCompiler = FakeResidentCompiler(); final FakeDevice device = FakeDevice() ..supportsHotReload = true ..supportsHotRestart = false; final List<FlutterDevice> devices = <FlutterDevice>[ TestFlutterDevice( device: device, generator: residentCompiler, exception: const HttpException('Connection closed before full header was received, ' 'uri = http://127.0.0.1:63394/5ZmLv8A59xY=/ws'), ), ]; final int exitCode = await ColdRunner(devices, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', ).attach(); expect(exitCode, 2); }); group('cleanupAtFinish()', () { testUsingContext('disposes each device', () async { final FakeDevice device1 = FakeDevice(); final FakeDevice device2 = FakeDevice(); final FakeFlutterDevice flutterDevice1 = FakeFlutterDevice(device1); final FakeFlutterDevice flutterDevice2 = FakeFlutterDevice(device2); final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice1, flutterDevice2]; await ColdRunner(devices, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', ).cleanupAtFinish(); expect(flutterDevice1.stopEchoingDeviceLogCount, 1); expect(flutterDevice2.stopEchoingDeviceLogCount, 1); expect(device2.wasDisposed, true); expect(device1.wasDisposed, true); }); }); group('cold run', () { late MemoryFileSystem memoryFileSystem; late FakePlatform fakePlatform; setUp(() { memoryFileSystem = MemoryFileSystem(); fakePlatform = FakePlatform(environment: <String, String>{}); }); testUsingContext('calls runCold on attached device', () async { final FakeDevice device = FakeDevice(); final FakeFlutterDevice flutterDevice = FakeFlutterDevice(device) ..runColdCode = 1; final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice]; final File applicationBinary = MemoryFileSystem.test().file('binary'); final int result = await ColdRunner( devices, applicationBinary: applicationBinary, debuggingOptions: DebuggingOptions.enabled(BuildInfo.debug), target: 'main.dart', ).run(); expect(result, 1); }); testUsingContext('with traceStartup, no env variable', () async { final FakeDevice device = FakeDevice(); final FakeFlutterDevice flutterDevice = FakeFlutterDevice(device); final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice]; final File applicationBinary = MemoryFileSystem.test().file('binary'); final int result = await ColdRunner( devices, applicationBinary: applicationBinary, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', traceStartup: true, ).run(); expect(result, 0); expect(memoryFileSystem.directory(getBuildDirectory()).childFile('start_up_info.json').existsSync(), true); }, overrides: <Type, Generator>{ FileSystem: () => memoryFileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => fakePlatform, }); testUsingContext('with traceStartup, env variable', () async { fakePlatform.environment[kFlutterTestOutputsDirEnvName] = 'test_output_dir'; final FakeDevice device = FakeDevice(); final FakeFlutterDevice flutterDevice = FakeFlutterDevice(device); final List<FlutterDevice> devices = <FlutterDevice>[flutterDevice]; final File applicationBinary = MemoryFileSystem.test().file('binary'); final int result = await ColdRunner( devices, applicationBinary: applicationBinary, debuggingOptions: DebuggingOptions.disabled(BuildInfo.debug), target: 'main.dart', traceStartup: true, ).run(); expect(result, 0); expect(memoryFileSystem.directory('test_output_dir').childFile('start_up_info.json').existsSync(), true); }, overrides: <Type, Generator>{ FileSystem: () => memoryFileSystem, ProcessManager: () => FakeProcessManager.any(), Platform: () => fakePlatform, }); }); } class FakeFlutterDevice extends Fake implements FlutterDevice { FakeFlutterDevice(this.device); @override Stream<Uri> get vmServiceUris => const Stream<Uri>.empty(); @override final Device device; int stopEchoingDeviceLogCount = 0; @override Future<void> stopEchoingDeviceLog() async { stopEchoingDeviceLogCount += 1; } @override FlutterVmService get vmService => FakeFlutterVmService(); int runColdCode = 0; @override Future<int> runCold({ColdRunner? coldRunner, String? route}) async { return runColdCode; } @override Future<void> initLogReader() async { } } class FakeDevice extends Fake implements Device { @override bool isSupported() => true; @override bool supportsHotReload = false; @override bool supportsHotRestart = false; @override Future<String> get sdkNameAndVersion async => 'Android 10'; @override String get name => 'test'; @override Future<TargetPlatform> get targetPlatform async => TargetPlatform.tester; bool wasDisposed = false; @override Future<void> dispose() async { wasDisposed = true; } } class TestFlutterDevice extends FlutterDevice { TestFlutterDevice({ required Device device, required this.exception, required ResidentCompiler generator, }) : super(device, buildInfo: BuildInfo.debug, generator: generator, developmentShaderCompiler: const FakeShaderCompiler()); /// The exception to throw when the connect method is called. final Exception exception; @override Future<void> connect({ ReloadSources? reloadSources, Restart? restart, CompileExpression? compileExpression, GetSkSLMethod? getSkSLMethod, FlutterProject? flutterProject, PrintStructuredErrorLogMethod? printStructuredErrorLogMethod, bool enableDds = true, bool cacheStartupProfile = false, bool disableServiceAuthCodes = false, int? hostVmServicePort, int? ddsPort, bool? ipv6 = false, bool allowExistingDdsInstance = false, }) async { throw exception; } } class FakeResidentCompiler extends Fake implements ResidentCompiler { } class FakeFlutterVmService extends Fake implements FlutterVmService { @override VmService get service => FakeVmService(); @override Future<List<FlutterView>> getFlutterViews({bool returnEarly = false, Duration delay = const Duration(milliseconds: 50)}) async { return <FlutterView>[]; } @override Future<bool> flutterAlreadyPaintedFirstUsefulFrame({String? isolateId}) async => true; @override Future<Response?> getTimeline() async { return Response.parse(<String, dynamic>{ 'traceEvents': <dynamic>[ <String, dynamic>{ 'name': kFlutterEngineMainEnterEventName, 'ts': 123, }, <String, dynamic>{ 'name': kFirstFrameBuiltEventName, 'ts': 124, }, <String, dynamic>{ 'name': kFirstFrameRasterizedEventName, 'ts': 124, }, ], }); } @override Future<void> setTimelineFlags(List<String> recordedStreams) async {} } class FakeVmService extends Fake implements VmService { @override Future<Success> streamListen(String streamId) async => Success(); @override Stream<Event> get onExtensionEvent { return Stream<Event>.fromIterable(<Event>[ Event(kind: 'Extension', extensionKind: 'Flutter.FirstFrame', timestamp: 1), ]); } } class FakeShaderCompiler implements DevelopmentShaderCompiler { const FakeShaderCompiler(); @override void configureCompiler(TargetPlatform? platform) { } @override Future<DevFSContent> recompileShader(DevFSContent inputShader) { throw UnimplementedError(); } }
flutter/packages/flutter_tools/test/general.shard/cold_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/cold_test.dart", "repo_id": "flutter", "token_count": 3152 }
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:flutter_tools/src/custom_devices/custom_device_workflow.dart'; import '../../src/common.dart'; import '../../src/fakes.dart'; void main() { testWithoutContext('CustomDeviceWorkflow reports false when custom devices feature is disabled', () { final CustomDeviceWorkflow workflow = CustomDeviceWorkflow(featureFlags: TestFeatureFlags()); expect(workflow.appliesToHostPlatform, false); expect(workflow.canLaunchDevices, false); expect(workflow.canListDevices, false); expect(workflow.canListEmulators, false); }); testWithoutContext('CustomDeviceWorkflow reports true for everything except canListEmulators when custom devices feature is enabled', () { final CustomDeviceWorkflow workflow = CustomDeviceWorkflow(featureFlags: TestFeatureFlags(areCustomDevicesEnabled: true)); expect(workflow.appliesToHostPlatform, true); expect(workflow.canLaunchDevices, true); expect(workflow.canListDevices, true); expect(workflow.canListEmulators, false); }); }
flutter/packages/flutter_tools/test/general.shard/custom_devices/custom_device_workflow_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/custom_devices/custom_device_workflow_test.dart", "repo_id": "flutter", "token_count": 341 }
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/file.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/net.dart'; import 'package:flutter_tools/src/base/process.dart'; import 'package:flutter_tools/src/base/time.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/drive/web_driver_service.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/resident_runner.dart'; import 'package:flutter_tools/src/web/web_runner.dart'; import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart'; import 'package:webdriver/sync_io.dart' as sync_io; import '../../src/common.dart'; import '../../src/context.dart'; const List<String> kChromeArgs = <String>[ '--bwsi', '--disable-background-timer-throttling', '--disable-default-apps', '--disable-extensions', '--disable-popup-blocking', '--disable-translate', '--no-default-browser-check', '--no-sandbox', '--no-first-run', ]; void main() { testWithoutContext('getDesiredCapabilities Chrome with headless on', () { final Map<String, dynamic> expected = <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'chrome', 'goog:loggingPrefs': <String, String>{ sync_io.LogType.browser: 'INFO', sync_io.LogType.performance: 'ALL', }, 'goog:chromeOptions': <String, dynamic>{ 'w3c': true, 'args': <String>[ ...kChromeArgs, '--headless', ], 'perfLoggingPrefs': <String, String>{ 'traceCategories': 'devtools.timeline,' 'v8,blink.console,benchmark,blink,' 'blink.user_timing', }, }, }; expect(getDesiredCapabilities(Browser.chrome, true), expected); }); testWithoutContext('getDesiredCapabilities Chrome with headless off', () { const String chromeBinary = 'random-binary'; final Map<String, dynamic> expected = <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'chrome', 'goog:loggingPrefs': <String, String>{ sync_io.LogType.browser: 'INFO', sync_io.LogType.performance: 'ALL', }, 'goog:chromeOptions': <String, dynamic>{ 'binary': chromeBinary, 'w3c': true, 'args': kChromeArgs, 'perfLoggingPrefs': <String, String>{ 'traceCategories': 'devtools.timeline,' 'v8,blink.console,benchmark,blink,' 'blink.user_timing', }, }, }; expect(getDesiredCapabilities(Browser.chrome, false, chromeBinary: chromeBinary), expected); }); testWithoutContext('getDesiredCapabilities Chrome with browser flags', () { const List<String> webBrowserFlags = <String>[ '--autoplay-policy=no-user-gesture-required', '--incognito', '--auto-select-desktop-capture-source="Entire screen"', ]; final Map<String, dynamic> expected = <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'chrome', 'goog:loggingPrefs': <String, String>{ sync_io.LogType.browser: 'INFO', sync_io.LogType.performance: 'ALL', }, 'goog:chromeOptions': <String, dynamic>{ 'w3c': true, 'args': <String>[ ...kChromeArgs, '--autoplay-policy=no-user-gesture-required', '--incognito', '--auto-select-desktop-capture-source="Entire screen"', ], 'perfLoggingPrefs': <String, String>{ 'traceCategories': 'devtools.timeline,' 'v8,blink.console,benchmark,blink,' 'blink.user_timing', }, }, }; expect(getDesiredCapabilities(Browser.chrome, false, webBrowserFlags: webBrowserFlags), expected); }); testWithoutContext('getDesiredCapabilities Firefox with headless on', () { final Map<String, dynamic> expected = <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'firefox', 'moz:firefoxOptions' : <String, dynamic>{ 'args': <String>['-headless'], 'prefs': <String, dynamic>{ 'dom.file.createInChild': true, 'dom.timeout.background_throttling_max_budget': -1, 'media.autoplay.default': 0, 'media.gmp-manager.url': '', 'media.gmp-provider.enabled': false, 'network.captive-portal-service.enabled': false, 'security.insecure_field_warning.contextual.enabled': false, 'test.currentTimeOffsetSeconds': 11491200, }, 'log': <String, String>{'level': 'trace'}, }, }; expect(getDesiredCapabilities(Browser.firefox, true), expected); }); testWithoutContext('getDesiredCapabilities Firefox with headless off', () { final Map<String, dynamic> expected = <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'firefox', 'moz:firefoxOptions' : <String, dynamic>{ 'args': <String>[], 'prefs': <String, dynamic>{ 'dom.file.createInChild': true, 'dom.timeout.background_throttling_max_budget': -1, 'media.autoplay.default': 0, 'media.gmp-manager.url': '', 'media.gmp-provider.enabled': false, 'network.captive-portal-service.enabled': false, 'security.insecure_field_warning.contextual.enabled': false, 'test.currentTimeOffsetSeconds': 11491200, }, 'log': <String, String>{'level': 'trace'}, }, }; expect(getDesiredCapabilities(Browser.firefox, false), expected); }); testWithoutContext('getDesiredCapabilities Firefox with browser flags', () { const List<String> webBrowserFlags = <String>[ '-url=https://example.com', '-private', ]; final Map<String, dynamic> expected = <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'firefox', 'moz:firefoxOptions' : <String, dynamic>{ 'args': <String>[ '-url=https://example.com', '-private', ], 'prefs': <String, dynamic>{ 'dom.file.createInChild': true, 'dom.timeout.background_throttling_max_budget': -1, 'media.autoplay.default': 0, 'media.gmp-manager.url': '', 'media.gmp-provider.enabled': false, 'network.captive-portal-service.enabled': false, 'security.insecure_field_warning.contextual.enabled': false, 'test.currentTimeOffsetSeconds': 11491200, }, 'log': <String, String>{'level': 'trace'}, }, }; expect(getDesiredCapabilities(Browser.firefox, false, webBrowserFlags: webBrowserFlags), expected); }); testWithoutContext('getDesiredCapabilities Edge', () { final Map<String, dynamic> expected = <String, dynamic>{ 'acceptInsecureCerts': true, 'browserName': 'edge', }; expect(getDesiredCapabilities(Browser.edge, false), expected); }); testWithoutContext('getDesiredCapabilities macOS Safari', () { final Map<String, dynamic> expected = <String, dynamic>{ 'browserName': 'safari', }; expect(getDesiredCapabilities(Browser.safari, false), expected); }); testWithoutContext('getDesiredCapabilities iOS Safari', () { final Map<String, dynamic> expected = <String, dynamic>{ 'platformName': 'ios', 'browserName': 'safari', 'safari:useSimulator': true, }; expect(getDesiredCapabilities(Browser.iosSafari, false), expected); }); testWithoutContext('getDesiredCapabilities android chrome', () { const List<String> webBrowserFlags = <String>[ '--autoplay-policy=no-user-gesture-required', '--incognito', ]; final Map<String, dynamic> expected = <String, dynamic>{ 'browserName': 'chrome', 'platformName': 'android', 'goog:chromeOptions': <String, dynamic>{ 'androidPackage': 'com.android.chrome', 'args': <String>[ '--disable-fullscreen', '--autoplay-policy=no-user-gesture-required', '--incognito', ], }, }; expect(getDesiredCapabilities(Browser.androidChrome, false, webBrowserFlags: webBrowserFlags), expected); }); testUsingContext('WebDriverService starts and stops an app', () async { final WebDriverService service = setUpDriverService(); final FakeDevice device = FakeDevice(); await service.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true); await service.stop(); expect(FakeResidentRunner.instance.callLog, <String>[ 'run', 'exitApp', 'cleanupAtFinish', ]); }, overrides: <Type, Generator>{ WebRunnerFactory: () => FakeWebRunnerFactory(), }); testUsingContext('WebDriverService can start an app with a launch url provided', () async { final WebDriverService service = setUpDriverService(); final FakeDevice device = FakeDevice(); const String testUrl = 'http://localhost:1234/test'; await service.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile, webLaunchUrl: testUrl), true); await service.stop(); expect(service.webUri, Uri.parse(testUrl)); }, overrides: <Type, Generator>{ WebRunnerFactory: () => FakeWebRunnerFactory(), }); testUsingContext('WebDriverService will throw when an invalid launch url is provided', () async { final WebDriverService service = setUpDriverService(); final FakeDevice device = FakeDevice(); const String invalidTestUrl = '::INVALID_URL::'; await expectLater( service.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile, webLaunchUrl: invalidTestUrl), true), throwsA(isA<FormatException>()), ); }, overrides: <Type, Generator>{ WebRunnerFactory: () => FakeWebRunnerFactory(), }); testUsingContext('WebDriverService forwards exception when run future fails before app starts', () async { final WebDriverService service = setUpDriverService(); final Device device = FakeDevice(); await expectLater( service.start(BuildInfo.profile, device, DebuggingOptions.enabled(BuildInfo.profile), true), throwsA('This is a test error'), ); }, overrides: <Type, Generator>{ WebRunnerFactory: () => FakeWebRunnerFactory( doResolveToError: true, ), }); } class FakeWebRunnerFactory implements WebRunnerFactory { FakeWebRunnerFactory({ this.doResolveToError = false, }); final bool doResolveToError; @override ResidentRunner createWebRunner( FlutterDevice device, { String? target, bool? stayResident, FlutterProject? flutterProject, bool? ipv6, DebuggingOptions? debuggingOptions, UrlTunneller? urlTunneller, Logger? logger, FileSystem? fileSystem, SystemClock? systemClock, Usage? usage, Analytics? analytics, bool machine = false, }) { expect(stayResident, isTrue); return FakeResidentRunner( doResolveToError: doResolveToError, ); } } class FakeResidentRunner extends Fake implements ResidentRunner { FakeResidentRunner({ required this.doResolveToError, }) { instance = this; } static late FakeResidentRunner instance; final bool doResolveToError; final Completer<int> _exitCompleter = Completer<int>(); final List<String> callLog = <String>[]; @override Uri get uri => Uri(); @override Future<int> run({ Completer<DebugConnectionInfo>? connectionInfoCompleter, Completer<void>? appStartedCompleter, bool enableDevTools = false, String? route, }) async { callLog.add('run'); if (doResolveToError) { return Future<int>.error('This is a test error'); } appStartedCompleter?.complete(); // Emulate stayResident by completing after exitApp is called. return _exitCompleter.future; } @override Future<void> exitApp() async { callLog.add('exitApp'); _exitCompleter.complete(0); } @override Future<void> cleanupAtFinish() async { callLog.add('cleanupAtFinish'); } } WebDriverService setUpDriverService() { final BufferLogger logger = BufferLogger.test(); return WebDriverService( logger: logger, processUtils: ProcessUtils( logger: logger, processManager: FakeProcessManager.any(), ), dartSdkPath: 'dart', ); } class FakeDevice extends Fake implements Device { @override final PlatformType platformType = PlatformType.web; @override Future<TargetPlatform> get targetPlatform async => TargetPlatform.android_arm; }
flutter/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/drive/web_driver_service_test.dart", "repo_id": "flutter", "token_count": 4935 }
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/memory.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/platform.dart'; import 'package:flutter_tools/src/fuchsia/fuchsia_sdk.dart'; import 'package:flutter_tools/src/fuchsia/fuchsia_workflow.dart'; import '../../src/common.dart'; import '../../src/fakes.dart'; void main() { final FileSystem fileSystem = MemoryFileSystem.test(); final File sshConfig = fileSystem.file('ssh_config'); final File ffx = fileSystem.file('ffx'); testWithoutContext('Fuchsia workflow does not apply to host platform if feature is disabled', () { final FuchsiaWorkflow fuchsiaWorkflow = FuchsiaWorkflow( featureFlags: TestFeatureFlags(), fuchsiaArtifacts: FuchsiaArtifacts(ffx: ffx, sshConfig: sshConfig), platform: FakePlatform(), ); expect(fuchsiaWorkflow.appliesToHostPlatform, false); }); testWithoutContext('Fuchsia workflow does not apply to host platform on Windows', () { final FuchsiaWorkflow fuchsiaWorkflow = FuchsiaWorkflow( featureFlags: TestFeatureFlags(isFuchsiaEnabled: true), fuchsiaArtifacts: FuchsiaArtifacts(ffx: ffx, sshConfig: sshConfig), platform: FakePlatform(operatingSystem: 'windows'), ); expect(fuchsiaWorkflow.appliesToHostPlatform, false); }); testWithoutContext('Fuchsia workflow can not list and launch devices if there is no ffx when using default workflow', () { final FuchsiaWorkflow fuchsiaWorkflow = FuchsiaWorkflow( featureFlags: TestFeatureFlags(), fuchsiaArtifacts: FuchsiaArtifacts(sshConfig: sshConfig), platform: FakePlatform(environment: <String, String>{}), ); expect(fuchsiaWorkflow.canLaunchDevices, false); expect(fuchsiaWorkflow.canListDevices, false); expect(fuchsiaWorkflow.canListEmulators, false); }); testWithoutContext('Fuchsia workflow can not launch devices if there is no ssh config when using default workflow', () { final FuchsiaWorkflow fuchsiaWorkflow = FuchsiaWorkflow( featureFlags: TestFeatureFlags(), fuchsiaArtifacts: FuchsiaArtifacts(ffx: ffx), platform: FakePlatform(environment: <String, String>{}), ); expect(fuchsiaWorkflow.canLaunchDevices, false); expect(fuchsiaWorkflow.canListDevices, true); expect(fuchsiaWorkflow.canListEmulators, false); }); testWithoutContext('Fuchsia workflow can list and launch devices supported with sufficient SDK artifacts when using default workflow', () { final FuchsiaWorkflow fuchsiaWorkflow = FuchsiaWorkflow( featureFlags: TestFeatureFlags(), fuchsiaArtifacts: FuchsiaArtifacts(sshConfig: sshConfig, ffx: ffx), platform: FakePlatform(environment: <String, String>{}), ); expect(fuchsiaWorkflow.canLaunchDevices, true); expect(fuchsiaWorkflow.canListDevices, true); expect(fuchsiaWorkflow.canListEmulators, false); }); testWithoutContext('Fuchsia workflow can list and launch devices supported with sufficient SDK artifacts on macOS', () { final FuchsiaWorkflow fuchsiaWorkflow = FuchsiaWorkflow( featureFlags: TestFeatureFlags(), fuchsiaArtifacts: FuchsiaArtifacts(sshConfig: sshConfig, ffx: ffx), platform: FakePlatform(operatingSystem: 'macOS', environment: <String, String>{}), ); expect(fuchsiaWorkflow.canLaunchDevices, true); expect(fuchsiaWorkflow.canListDevices, true); expect(fuchsiaWorkflow.canListEmulators, false); }); }
flutter/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_workflow_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/fuchsia/fuchsia_workflow_test.dart", "repo_id": "flutter", "token_count": 1200 }
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 'package:fake_async/fake_async.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/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/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/iproxy.dart'; import 'package:flutter_tools/src/ios/mac.dart'; import 'package:flutter_tools/src/ios/xcode_debug.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/macos/xcode.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:test/fake.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../../src/common.dart'; import '../../src/context.dart' hide FakeXcodeProjectInterpreter; import '../../src/fake_devices.dart'; import '../../src/fake_process_manager.dart'; import '../../src/fakes.dart'; List<String> _xattrArgs(FlutterProject flutterProject) { return <String>[ 'xattr', '-r', '-d', 'com.apple.FinderInfo', flutterProject.directory.path, ]; } const List<String> kRunReleaseArgs = <String>[ 'xcrun', 'xcodebuild', '-configuration', 'Release', '-quiet', '-workspace', 'Runner.xcworkspace', '-scheme', 'Runner', 'BUILD_DIR=/build/ios', '-sdk', 'iphoneos', '-destination', 'id=123', 'ONLY_ACTIVE_ARCH=YES', 'ARCHS=arm64', '-resultBundlePath', '/.tmp_rand0/flutter_ios_build_temp_dirrand0/temporary_xcresult_bundle', '-resultBundleVersion', '3', 'FLUTTER_SUPPRESS_ANALYTICS=true', 'COMPILER_INDEX_STORE_ENABLE=NO', ]; const String kConcurrentBuildErrorMessage = ''' "/Developer/Xcode/DerivedData/foo/XCBuildData/build.db": database is locked Possibly there are two concurrent builds running in the same filesystem location. '''; final FakePlatform macPlatform = FakePlatform( operatingSystem: 'macos', environment: <String, String>{}, ); void main() { late Artifacts artifacts; late String iosDeployPath; setUp(() { artifacts = Artifacts.test(); iosDeployPath = artifacts.getHostArtifact(HostArtifact.iosDeploy).path; }); group('IOSDevice.startApp succeeds in release mode', () { late MemoryFileSystem fileSystem; late FakeProcessManager processManager; late BufferLogger logger; late Xcode xcode; late FakeXcodeProjectInterpreter fakeXcodeProjectInterpreter; late XcodeProjectInfo projectInfo; late FakeAnalytics fakeAnalytics; setUp(() { logger = BufferLogger.test(); fileSystem = MemoryFileSystem.test(); processManager = FakeProcessManager.empty(); projectInfo = XcodeProjectInfo( <String>['Runner'], <String>['Debug', 'Release'], <String>['Runner'], logger, ); fakeXcodeProjectInterpreter = FakeXcodeProjectInterpreter(projectInfo: projectInfo); xcode = Xcode.test(processManager: FakeProcessManager.any(), xcodeProjectInterpreter: fakeXcodeProjectInterpreter); fileSystem.file('foo/.packages') ..createSync(recursive: true) ..writeAsStringSync('\n'); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: FakeFlutterVersion(), ); }); testUsingContext('missing TARGET_BUILD_DIR', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: processManager, logger: logger, artifacts: artifacts, ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); processManager.addCommand(FakeCommand(command: _xattrArgs(flutterProject))); processManager.addCommand(const FakeCommand(command: kRunReleaseArgs)); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); expect(launchResult.started, false); expect(logger.errorText, contains('Xcode build is missing expected TARGET_BUILD_DIR build setting')); expect(processManager, hasNoRemainingExpectations); expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'xcode-ios', ), true, ); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(buildSettings: const <String, String>{ 'WRAPPER_NAME': 'My Super Awesome App.app', 'DEVELOPMENT_TEAM': '3333CCCC33', }, projectInfo: projectInfo), Xcode: () => xcode, Analytics: () => fakeAnalytics, }); testUsingContext('missing project info', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); expect(launchResult.started, false); expect(logger.errorText, contains('Xcode project not found')); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(), Xcode: () => xcode, }); testUsingContext('with buildable app', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: processManager, logger: logger, artifacts: artifacts, ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); processManager.addCommand(FakeCommand(command: _xattrArgs(flutterProject))); processManager.addCommand(const FakeCommand(command: kRunReleaseArgs)); processManager.addCommand(const FakeCommand(command: <String>[ 'rsync', '-8', '-av', '--delete', 'build/ios/Release-iphoneos/My Super Awesome App.app', 'build/ios/iphoneos', ])); processManager.addCommand(FakeCommand( command: <String>[ iosDeployPath, '--id', '123', '--bundle', 'build/ios/iphoneos/My Super Awesome App.app', '--app_deltas', 'build/ios/app-delta', '--no-wifi', '--justlaunch', '--args', const <String>[ '--enable-dart-profiling', ].join(' '), ]) ); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, true); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); testUsingContext('with concurrent build failures', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: processManager, logger: logger, artifacts: artifacts, ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); processManager.addCommand(FakeCommand(command: _xattrArgs(flutterProject))); // The first xcrun call should fail with a // concurrent build exception. processManager.addCommand( const FakeCommand( command: kRunReleaseArgs, exitCode: 1, stdout: kConcurrentBuildErrorMessage, )); processManager.addCommand(const FakeCommand(command: kRunReleaseArgs)); processManager.addCommand(FakeCommand( command: <String>[ iosDeployPath, '--id', '123', '--bundle', 'build/ios/iphoneos/My Super Awesome App.app', '--no-wifi', '--justlaunch', '--args', const <String>[ '--enable-dart-profiling', '--disable-service-auth-codes', ].join(' '), ]) ); await FakeAsync().run((FakeAsync time) async { final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); time.elapse(const Duration(seconds: 2)); expect(logger.statusText, contains('Xcode build failed due to concurrent builds, will retry in 2 seconds')); expect(launchResult.started, true); expect(processManager, hasNoRemainingExpectations); }); }, overrides: <Type, Generator>{ ProcessManager: () => processManager, FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }, skip: true); // TODO(zanderso): clean up with https://github.com/flutter/flutter/issues/60675 }); group('IOSDevice.startApp for CoreDevice', () { late FileSystem fileSystem; late FakeProcessManager processManager; late BufferLogger logger; late Xcode xcode; late FakeXcodeProjectInterpreter fakeXcodeProjectInterpreter; late XcodeProjectInfo projectInfo; setUp(() { logger = BufferLogger.test(); fileSystem = MemoryFileSystem.test(); processManager = FakeProcessManager.empty(); projectInfo = XcodeProjectInfo( <String>['Runner'], <String>['Debug', 'Release'], <String>['Runner'], logger, ); fakeXcodeProjectInterpreter = FakeXcodeProjectInterpreter(projectInfo: projectInfo); xcode = Xcode.test(processManager: FakeProcessManager.any(), xcodeProjectInterpreter: fakeXcodeProjectInterpreter); fileSystem.file('foo/.packages') ..createSync(recursive: true) ..writeAsStringSync('\n'); }); group('in release mode', () { testUsingContext('succeeds when install and launch succeed', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl(), ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, true); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); testUsingContext('fails when install fails', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl( installSuccess: false, ), ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, false); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); testUsingContext('fails when launch fails', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl( launchSuccess: false, ), ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, false); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); testUsingContext('ensure arguments passed to launch', () async { final FakeIOSCoreDeviceControl coreDeviceControl = FakeIOSCoreDeviceControl(); final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: coreDeviceControl, ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.disabled(BuildInfo.release), platformArgs: <String, Object>{}, ); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, true); expect(processManager, hasNoRemainingExpectations); expect(coreDeviceControl.argumentsUsedForLaunch, isNotNull); expect(coreDeviceControl.argumentsUsedForLaunch, contains('--enable-dart-profiling')); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); }); group('in debug mode', () { testUsingContext('succeeds', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl(), xcodeDebug: FakeXcodeDebug( expectedProject: XcodeDebugProject( scheme: 'Runner', xcodeWorkspace: fileSystem.directory('/ios/Runner.xcworkspace'), xcodeProject: fileSystem.directory('/ios/Runner.xcodeproj'), hostAppProjectName: 'Runner', ), expectedDeviceId: '123', expectedLaunchArguments: <String>['--enable-dart-profiling'], ), ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final FakeDeviceLogReader deviceLogReader = FakeDeviceLogReader(); iosDevice.portForwarder = const NoOpDevicePortForwarder(); iosDevice.setLogReader(buildableIOSApp, deviceLogReader); // Start writing messages to the log reader. Timer.run(() { deviceLogReader.addLine('Foo'); deviceLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:456'); }); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.enabled(const BuildInfo( BuildMode.debug, null, buildName: '1.2.3', buildNumber: '4', treeShakeIcons: false, )), platformArgs: <String, Object>{}, ); expect(logger.errorText, isEmpty); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, true); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); group('with flavor', () { setUp(() { projectInfo = XcodeProjectInfo( <String>['Runner'], <String>['Debug', 'Release', 'Debug-free', 'Release-free'], <String>['Runner', 'free'], logger, ); fakeXcodeProjectInterpreter = FakeXcodeProjectInterpreter(projectInfo: projectInfo); xcode = Xcode.test(processManager: FakeProcessManager.any(), xcodeProjectInterpreter: fakeXcodeProjectInterpreter); }); testUsingContext('succeeds', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl(), xcodeDebug: FakeXcodeDebug( expectedProject: XcodeDebugProject( scheme: 'free', xcodeWorkspace: fileSystem.directory('/ios/Runner.xcworkspace'), xcodeProject: fileSystem.directory('/ios/Runner.xcodeproj'), hostAppProjectName: 'Runner', ), expectedDeviceId: '123', expectedLaunchArguments: <String>['--enable-dart-profiling'], expectedSchemeFilePath: '/ios/Runner.xcodeproj/xcshareddata/xcschemes/free.xcscheme', ), ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final FakeDeviceLogReader deviceLogReader = FakeDeviceLogReader(); iosDevice.portForwarder = const NoOpDevicePortForwarder(); iosDevice.setLogReader(buildableIOSApp, deviceLogReader); // Start writing messages to the log reader. Timer.run(() { deviceLogReader.addLine('Foo'); deviceLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:456'); }); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.enabled(const BuildInfo( BuildMode.debug, 'free', buildName: '1.2.3', buildNumber: '4', treeShakeIcons: false, )), platformArgs: <String, Object>{}, ); expect(logger.errorText, isEmpty); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, true); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); }); testUsingContext('updates Generated.xcconfig before and after launch', () async { final Completer<void> debugStartedCompleter = Completer<void>(); final Completer<void> debugEndedCompleter = Completer<void>(); final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl(), xcodeDebug: FakeXcodeDebug( expectedProject: XcodeDebugProject( scheme: 'Runner', xcodeWorkspace: fileSystem.directory('/ios/Runner.xcworkspace'), xcodeProject: fileSystem.directory('/ios/Runner.xcodeproj'), hostAppProjectName: 'Runner', expectedConfigurationBuildDir: '/build/ios/iphoneos', ), expectedDeviceId: '123', expectedLaunchArguments: <String>['--enable-dart-profiling'], debugStartedCompleter: debugStartedCompleter, debugEndedCompleter: debugEndedCompleter, ), ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final FakeDeviceLogReader deviceLogReader = FakeDeviceLogReader(); iosDevice.portForwarder = const NoOpDevicePortForwarder(); iosDevice.setLogReader(buildableIOSApp, deviceLogReader); // Start writing messages to the log reader. Timer.run(() { deviceLogReader.addLine('Foo'); deviceLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:456'); }); final Future<LaunchResult> futureLaunchResult = iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.enabled(const BuildInfo( BuildMode.debug, null, buildName: '1.2.3', buildNumber: '4', treeShakeIcons: false, )), platformArgs: <String, Object>{}, ); await debugStartedCompleter.future; // Validate CoreDevice build settings were used final File config = fileSystem.directory('ios').childFile('Flutter/Generated.xcconfig'); expect(config.existsSync(), isTrue); String contents = config.readAsStringSync(); expect(contents, contains('CONFIGURATION_BUILD_DIR=/build/ios/iphoneos')); debugEndedCompleter.complete(); await futureLaunchResult; // Validate CoreDevice build settings were removed after launch contents = config.readAsStringSync(); expect(contents.contains('CONFIGURATION_BUILD_DIR'), isFalse); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); testUsingContext('fails when Xcode project is not found', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl() ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.enabled(const BuildInfo( BuildMode.debug, null, buildName: '1.2.3', buildNumber: '4', treeShakeIcons: false, )), platformArgs: <String, Object>{}, ); expect(logger.errorText, contains('Xcode project not found')); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, false); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(), Xcode: () => xcode, }); testUsingContext('fails when Xcode workspace is not found', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl() ); setUpIOSProject(fileSystem, createWorkspace: false); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final LaunchResult launchResult = await iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.enabled(const BuildInfo( BuildMode.debug, null, buildName: '1.2.3', buildNumber: '4', treeShakeIcons: false, )), platformArgs: <String, Object>{}, ); expect(logger.errorText, contains('Unable to get Xcode workspace')); expect(fileSystem.directory('build/ios/iphoneos'), exists); expect(launchResult.started, false); expect(processManager, hasNoRemainingExpectations); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); testUsingContext('fails when scheme is not found', () async { final IOSDevice iosDevice = setUpIOSDevice( fileSystem: fileSystem, processManager: FakeProcessManager.any(), logger: logger, artifacts: artifacts, isCoreDevice: true, coreDeviceControl: FakeIOSCoreDeviceControl() ); setUpIOSProject(fileSystem); final FlutterProject flutterProject = FlutterProject.fromDirectory(fileSystem.currentDirectory); final BuildableIOSApp buildableIOSApp = BuildableIOSApp(flutterProject.ios, 'flutter', 'My Super Awesome App.app'); fileSystem.directory('build/ios/Release-iphoneos/My Super Awesome App.app').createSync(recursive: true); final FakeDeviceLogReader deviceLogReader = FakeDeviceLogReader(); iosDevice.portForwarder = const NoOpDevicePortForwarder(); iosDevice.setLogReader(buildableIOSApp, deviceLogReader); // Start writing messages to the log reader. Timer.run(() { deviceLogReader.addLine('Foo'); deviceLogReader.addLine('The Dart VM service is listening on http://127.0.0.1:456'); }); expect(() async => iosDevice.startApp( buildableIOSApp, debuggingOptions: DebuggingOptions.enabled(const BuildInfo( BuildMode.debug, 'Flavor', buildName: '1.2.3', buildNumber: '4', treeShakeIcons: false, )), platformArgs: <String, Object>{}, ), throwsToolExit()); }, overrides: <Type, Generator>{ ProcessManager: () => FakeProcessManager.any(), FileSystem: () => fileSystem, Logger: () => logger, Platform: () => macPlatform, XcodeProjectInterpreter: () => fakeXcodeProjectInterpreter, Xcode: () => xcode, }); }); }); } void setUpIOSProject(FileSystem fileSystem, {bool createWorkspace = true}) { fileSystem.file('pubspec.yaml').createSync(); fileSystem.file('.packages').writeAsStringSync('\n'); fileSystem.directory('ios').createSync(); if (createWorkspace) { fileSystem.directory('ios/Runner.xcworkspace').createSync(); } fileSystem.file('ios/Runner.xcodeproj/project.pbxproj').createSync(recursive: true); // This is the expected output directory. fileSystem.directory('build/ios/iphoneos/My Super Awesome App.app').createSync(recursive: true); } IOSDevice setUpIOSDevice({ String sdkVersion = '13.0.1', FileSystem? fileSystem, Logger? logger, ProcessManager? processManager, Artifacts? artifacts, bool isCoreDevice = false, IOSCoreDeviceControl? coreDeviceControl, FakeXcodeDebug? xcodeDebug, }) { artifacts ??= Artifacts.test(); final Cache cache = Cache.test( artifacts: <ArtifactSet>[ FakeDyldEnvironmentArtifact(), ], processManager: FakeProcessManager.any(), ); logger ??= BufferLogger.test(); return IOSDevice( '123', name: 'iPhone 1', sdkVersion: sdkVersion, fileSystem: fileSystem ?? MemoryFileSystem.test(), platform: macPlatform, iProxy: IProxy.test(logger: logger, processManager: processManager ?? FakeProcessManager.any()), logger: logger, iosDeploy: IOSDeploy( logger: logger, platform: macPlatform, processManager: processManager ?? FakeProcessManager.any(), artifacts: artifacts, cache: cache, ), iMobileDevice: IMobileDevice( logger: logger, processManager: processManager ?? FakeProcessManager.any(), artifacts: artifacts, cache: cache, ), coreDeviceControl: coreDeviceControl ?? FakeIOSCoreDeviceControl(), xcodeDebug: xcodeDebug ?? FakeXcodeDebug(), cpuArchitecture: DarwinArch.arm64, connectionInterface: DeviceConnectionInterface.attached, isConnected: true, isPaired: true, devModeEnabled: true, isCoreDevice: isCoreDevice, ); } class FakeXcodeProjectInterpreter extends Fake implements XcodeProjectInterpreter { FakeXcodeProjectInterpreter({ this.projectInfo, this.buildSettings = const <String, String>{ 'TARGET_BUILD_DIR': 'build/ios/Release-iphoneos', 'WRAPPER_NAME': 'My Super Awesome App.app', 'DEVELOPMENT_TEAM': '3333CCCC33', }, }); final Map<String, String> buildSettings; final XcodeProjectInfo? projectInfo; @override final bool isInstalled = true; @override final Version version = Version(1000, 0, 0); @override String get versionText => version.toString(); @override List<String> xcrunCommand() => <String>['xcrun']; @override Future<XcodeProjectInfo?> getInfo( String projectPath, { String? projectFilename, }) async => projectInfo; @override Future<Map<String, String>> getBuildSettings( String projectPath, { required XcodeProjectBuildContext buildContext, Duration timeout = const Duration(minutes: 1), }) async => buildSettings; } class FakeXcodeDebug extends Fake implements XcodeDebug { FakeXcodeDebug({ this.debugSuccess = true, this.expectedProject, this.expectedDeviceId, this.expectedLaunchArguments, this.expectedSchemeFilePath = '/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme', this.debugStartedCompleter, this.debugEndedCompleter, }); final bool debugSuccess; final XcodeDebugProject? expectedProject; final String? expectedDeviceId; final List<String>? expectedLaunchArguments; final Completer<void>? debugStartedCompleter; final Completer<void>? debugEndedCompleter; final String expectedSchemeFilePath; @override Future<bool> debugApp({ required XcodeDebugProject project, required String deviceId, required List<String> launchArguments, }) async { debugStartedCompleter?.complete(); if (expectedProject != null) { expect(project.scheme, expectedProject!.scheme); expect(project.xcodeWorkspace.path, expectedProject!.xcodeWorkspace.path); expect(project.xcodeProject.path, expectedProject!.xcodeProject.path); expect(project.isTemporaryProject, expectedProject!.isTemporaryProject); } if (expectedDeviceId != null) { expect(deviceId, expectedDeviceId); } if (expectedLaunchArguments != null) { expect(expectedLaunchArguments, launchArguments); } await debugEndedCompleter?.future; return debugSuccess; } @override void ensureXcodeDebuggerLaunchAction(File schemeFile) { expect(schemeFile.path, expectedSchemeFilePath); } } class FakeIOSCoreDeviceControl extends Fake implements IOSCoreDeviceControl { FakeIOSCoreDeviceControl({ this.installSuccess = true, this.launchSuccess = true }); final bool installSuccess; final bool launchSuccess; List<String>? _launchArguments; List<String>? get argumentsUsedForLaunch => _launchArguments; @override Future<bool> installApp({ required String deviceId, required String bundlePath, }) async { return installSuccess; } @override Future<bool> launchApp({ required String deviceId, required String bundleId, List<String> launchArguments = const <String>[], }) async { _launchArguments = launchArguments; return launchSuccess; } }
flutter/packages/flutter_tools/test/general.shard/ios/ios_device_start_nonprebuilt_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/ios/ios_device_start_nonprebuilt_test.dart", "repo_id": "flutter", "token_count": 15011 }
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:flutter_tools/src/isolated/native_assets/macos/native_assets_host.dart'; import '../../../src/common.dart'; void main() { test('framework name', () { expect( frameworkUri('libfoo.dylib', <String>{}), equals(Uri.file('foo.framework/foo')), ); expect( frameworkUri('foo', <String>{}), equals(Uri.file('foo.framework/foo')), ); expect( frameworkUri('foo_foo', <String>{}), equals(Uri.file('foo_foo.framework/foo_foo')), ); expect( frameworkUri('foo-foo', <String>{}), equals(Uri.file('foo-foo.framework/foo-foo')), ); expect( frameworkUri(r'foo$foo', <String>{}), equals(Uri.file('foofoo.framework/foofoo')), ); expect( frameworkUri('foo.foo', <String>{}), equals(Uri.file('foofoo.framework/foofoo')), ); expect( frameworkUri('libatoolongfilenameforaframework.dylib', <String>{}), equals(Uri.file('atoolongfilenameforaframework.framework/atoolongfilenameforaframework')), ); }); test('framework name conflicts', () { final Set<String> alreadyTakenNames = <String>{}; expect( frameworkUri('libfoo.dylib', alreadyTakenNames), equals(Uri.file('foo.framework/foo')), ); expect( frameworkUri('libfoo.dylib', alreadyTakenNames), equals(Uri.file('foo1.framework/foo1')), ); expect( frameworkUri('libfoo.dylib', alreadyTakenNames), equals(Uri.file('foo2.framework/foo2')), ); expect( frameworkUri('libatoolongfilenameforaframework.dylib', alreadyTakenNames), equals(Uri.file('atoolongfilenameforaframework.framework/atoolongfilenameforaframework')), ); expect( frameworkUri('libatoolongfilenameforaframework.dylib', alreadyTakenNames), equals(Uri.file('atoolongfilenameforaframework1.framework/atoolongfilenameforaframework1')), ); expect( frameworkUri('libatoolongfilenameforaframework.dylib', alreadyTakenNames), equals(Uri.file('atoolongfilenameforaframework2.framework/atoolongfilenameforaframework2')), ); }); }
flutter/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_host_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/isolated/macos/native_assets_host_test.dart", "repo_id": "flutter", "token_count": 912 }
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/base/version.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/ios/simulators.dart'; import 'package:flutter_tools/src/ios/xcodeproj.dart'; import 'package:flutter_tools/src/macos/xcode.dart'; import 'package:flutter_tools/src/macos/xcode_validator.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; import '../../src/fake_process_manager.dart'; void main() { group('Xcode validation', () { testWithoutContext('Emits missing status when Xcode is not installed', () async { final ProcessManager processManager = FakeProcessManager.any(); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager, version: null), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.missing); expect(result.statusInfo, isNull); expect(result.messages.last.type, ValidationMessageType.error); expect(result.messages.last.message, contains('Xcode not installed')); }); testWithoutContext('Emits missing status when Xcode installation is incomplete', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/Library/Developer/CommandLineTools', ), ]); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager, version: null), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.missing); expect(result.messages.last.type, ValidationMessageType.error); expect(result.messages.last.message, contains('Xcode installation is incomplete')); }); testWithoutContext('Emits partial status when Xcode version too low', () async { final ProcessManager processManager = FakeProcessManager.any(); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager, version: Version(7, 0, 1)), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.partial); expect(result.messages.last.type, ValidationMessageType.error); expect(result.messages.last.message, contains('Flutter requires Xcode 14 or higher')); }); testWithoutContext('Emits partial status when Xcode below recommended version', () async { final ProcessManager processManager = FakeProcessManager.any(); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager, version: Version(12, 4, null)), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.partial); expect(result.messages.last.type, ValidationMessageType.hint); expect(result.messages.last.message, contains('Flutter recommends a minimum Xcode version of 13')); }, skip: true); // [intended] Unskip and update when minimum and required check versions diverge. testWithoutContext('Emits partial status when Xcode EULA not signed', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/Library/Developer/CommandLineTools', ), const FakeCommand( command: <String>[ 'which', 'sysctl', ], ), const FakeCommand( command: <String>[ 'sysctl', 'hw.optional.arm64', ], exitCode: 1, ), const FakeCommand( command: <String>['xcrun', 'clang'], exitCode: 1, stderr: 'Xcode EULA has not been accepted.\nLaunch Xcode and accept the license.', ), const FakeCommand( command: <String>['xcrun', 'simctl', 'list', 'devices', 'booted'], ), ]); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.partial); expect(result.messages.last.type, ValidationMessageType.error); expect(result.messages.last.message, contains('code end user license agreement not signed')); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Emits partial status when simctl is not installed', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/Library/Developer/CommandLineTools', ), const FakeCommand( command: <String>[ 'which', 'sysctl', ], ), const FakeCommand( command: <String>[ 'sysctl', 'hw.optional.arm64', ], exitCode: 1, ), const FakeCommand( command: <String>['xcrun', 'clang'], ), const FakeCommand( command: <String>['xcrun', 'simctl', 'list', 'devices', 'booted'], exitCode: 1, ), ]); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.partial); expect(result.messages.last.type, ValidationMessageType.error); expect(result.messages.last.message, contains('Xcode requires additional components')); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Emits partial status when unable to find simulator SDK', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/Library/Developer/CommandLineTools', ), const FakeCommand( command: <String>[ 'which', 'sysctl', ], ), const FakeCommand( command: <String>[ 'sysctl', 'hw.optional.arm64', ], exitCode: 1, ), const FakeCommand( command: <String>['xcrun', 'clang'], ), const FakeCommand( command: <String>['xcrun', 'simctl', 'list', 'devices', 'booted'], ), const FakeCommand( command: <String>['xcrun', '--sdk', 'iphonesimulator', '--show-sdk-platform-version'], ), ]); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.partial); expect(result.messages.last.type, ValidationMessageType.error); expect(result.messages.last.message, contains('Unable to find the iPhone Simulator SDK')); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Emits partial status when unable to get simulator runtimes', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/Library/Developer/CommandLineTools', ), const FakeCommand( command: <String>[ 'which', 'sysctl', ], ), const FakeCommand( command: <String>[ 'sysctl', 'hw.optional.arm64', ], exitCode: 1, ), const FakeCommand( command: <String>['xcrun', 'clang'], ), const FakeCommand( command: <String>['xcrun', 'simctl', 'list', 'devices', 'booted'], ), const FakeCommand( command: <String>['xcrun', '--sdk', 'iphonesimulator', '--show-sdk-platform-version'], stdout: '17.0' ), ]); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager), ); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: FakeIOSSimulatorUtils(), ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.partial); expect(result.messages.last.type, ValidationMessageType.error); expect(result.messages.last.message, contains('Unable to get list of installed Simulator runtimes')); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Emits partial status with hint when simulator runtimes do not match SDK', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/Library/Developer/CommandLineTools', ), const FakeCommand( command: <String>[ 'which', 'sysctl', ], ), const FakeCommand( command: <String>[ 'sysctl', 'hw.optional.arm64', ], exitCode: 1, ), const FakeCommand( command: <String>['xcrun', 'clang'], ), const FakeCommand( command: <String>['xcrun', 'simctl', 'list', 'devices', 'booted'], ), const FakeCommand( command: <String>['xcrun', '--sdk', 'iphonesimulator', '--show-sdk-platform-version'], stdout: '17.0' ), ]); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager), ); final FakeIOSSimulatorUtils simulatorUtils = FakeIOSSimulatorUtils(runtimes: <IOSSimulatorRuntime>[ IOSSimulatorRuntime.fromJson(<String, String>{'version': '16.0'}), ]); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: simulatorUtils, ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.partial); expect(result.messages.last.type, ValidationMessageType.hint); expect(result.messages.last.message, contains('iOS 17.0 Simulator not installed')); expect(processManager, hasNoRemainingExpectations); }); testWithoutContext('Succeeds when all checks pass', () async { final ProcessManager processManager = FakeProcessManager.list(<FakeCommand>[ const FakeCommand( command: <String>['/usr/bin/xcode-select', '--print-path'], stdout: '/Library/Developer/CommandLineTools', ), const FakeCommand( command: <String>[ 'which', 'sysctl', ], ), const FakeCommand( command: <String>[ 'sysctl', 'hw.optional.arm64', ], exitCode: 1, ), const FakeCommand( command: <String>['xcrun', 'clang'], ), const FakeCommand( command: <String>['xcrun', 'simctl', 'list', 'devices', 'booted'], ), const FakeCommand( command: <String>['xcrun', '--sdk', 'iphonesimulator', '--show-sdk-platform-version'], stdout: '17.0' ), ]); final Xcode xcode = Xcode.test( processManager: processManager, xcodeProjectInterpreter: XcodeProjectInterpreter.test(processManager: processManager), ); final FakeIOSSimulatorUtils simulatorUtils = FakeIOSSimulatorUtils(runtimes: <IOSSimulatorRuntime>[ IOSSimulatorRuntime.fromJson(<String, String>{'version': '17.0'}), ]); final XcodeValidator validator = XcodeValidator( xcode: xcode, userMessages: UserMessages(), iosSimulatorUtils: simulatorUtils, ); final ValidationResult result = await validator.validate(); expect(result.type, ValidationType.success); expect(result.messages.length, 2); final ValidationMessage firstMessage = result.messages.first; expect(firstMessage.type, ValidationMessageType.information); expect(firstMessage.message, 'Xcode at /Library/Developer/CommandLineTools'); expect(result.statusInfo, '1000.0.0'); expect(result.messages[1].message, 'Build 13C100'); expect(processManager, hasNoRemainingExpectations); }); }); } class FakeIOSSimulatorUtils extends Fake implements IOSSimulatorUtils { FakeIOSSimulatorUtils({ this.runtimes, }); List<IOSSimulatorRuntime>? runtimes; List<IOSSimulatorRuntime> get _runtimesList { return runtimes ?? <IOSSimulatorRuntime>[]; } @override Future<List<IOSSimulatorRuntime>> getAvailableIOSRuntimes() async { return _runtimesList; } }
flutter/packages/flutter_tools/test/general.shard/macos/xcode_validator_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/macos/xcode_validator_test.dart", "repo_id": "flutter", "token_count": 6261 }
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:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/doctor_validator.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:package_config/package_config.dart'; import '../../src/common.dart'; void main() { testWithoutContext('DoctorResultEvent sends usage event for each sub validator', () async { final TestUsage usage = TestUsage(); final GroupedValidator groupedValidator = FakeGroupedValidator(<DoctorValidator>[ FakeDoctorValidator('a'), FakeDoctorValidator('b'), FakeDoctorValidator('c'), ]); final ValidationResult result = await groupedValidator.validate(); final DoctorResultEvent doctorResultEvent = DoctorResultEvent( validator: groupedValidator, result: result, flutterUsage: usage, ); expect(doctorResultEvent.send, returnsNormally); expect(usage.events.length, 3); expect(usage.events, contains( const TestUsageEvent('doctor-result', 'FakeDoctorValidator', label: 'crash'), )); }); testWithoutContext('DoctorResultEvent does not crash if a synthetic crash result was used instead' ' of validation. This happens when a grouped validator throws an exception, causing subResults to never ' ' be instantiated.', () async { final TestUsage usage = TestUsage(); final GroupedValidator groupedValidator = FakeGroupedValidator(<DoctorValidator>[ FakeDoctorValidator('a'), FakeDoctorValidator('b'), FakeDoctorValidator('c'), ]); final ValidationResult result = ValidationResult.crash(Object()); final DoctorResultEvent doctorResultEvent = DoctorResultEvent( validator: groupedValidator, result: result, flutterUsage: usage, ); expect(doctorResultEvent.send, returnsNormally); expect(usage.events.length, 1); expect(usage.events, contains( const TestUsageEvent('doctor-result', 'FakeGroupedValidator', label: 'crash'), )); }); testWithoutContext('Reports null safe analytics events', () { final TestUsage usage = TestUsage(); final PackageConfig packageConfig = PackageConfig(<Package>[ Package('foo', Uri.parse('file:///foo/'), languageVersion: LanguageVersion(2, 12)), Package('bar', Uri.parse('file:///fizz/'), languageVersion: LanguageVersion(2, 1)), Package('baz', Uri.parse('file:///bar/'), languageVersion: LanguageVersion(2, 2)), ]); NullSafetyAnalysisEvent( packageConfig, NullSafetyMode.sound, 'foo', usage, ).send(); expect(usage.events, unorderedEquals(<TestUsageEvent>[ const TestUsageEvent(NullSafetyAnalysisEvent.kNullSafetyCategory, 'runtime-mode', label: 'NullSafetyMode.sound'), TestUsageEvent(NullSafetyAnalysisEvent.kNullSafetyCategory, 'stats', parameters: CustomDimensions.fromMap(<String, String>{ 'cd49': '1', 'cd50': '3', })), const TestUsageEvent(NullSafetyAnalysisEvent.kNullSafetyCategory, 'language-version', label: '2.12'), ])); }); testWithoutContext('Does not crash if main package is missing', () { final TestUsage usage = TestUsage(); final PackageConfig packageConfig = PackageConfig(<Package>[ Package('foo', Uri.parse('file:///foo/lib/'), languageVersion: LanguageVersion(2, 12)), Package('bar', Uri.parse('file:///fizz/lib/'), languageVersion: LanguageVersion(2, 1)), Package('baz', Uri.parse('file:///bar/lib/'), languageVersion: LanguageVersion(2, 2)), ]); NullSafetyAnalysisEvent( packageConfig, NullSafetyMode.sound, 'something-unrelated', usage, ).send(); expect(usage.events, unorderedEquals(<TestUsageEvent>[ const TestUsageEvent(NullSafetyAnalysisEvent.kNullSafetyCategory, 'runtime-mode', label: 'NullSafetyMode.sound'), TestUsageEvent(NullSafetyAnalysisEvent.kNullSafetyCategory, 'stats', parameters: CustomDimensions.fromMap(<String, String>{ 'cd49': '1', 'cd50': '3', })), ])); }); testWithoutContext('a null language version is treated as unmigrated', () { final TestUsage usage = TestUsage(); final PackageConfig packageConfig = PackageConfig(<Package>[ Package('foo', Uri.parse('file:///foo/lib/')), ]); NullSafetyAnalysisEvent( packageConfig, NullSafetyMode.sound, 'something-unrelated', usage, ).send(); expect(usage.events, unorderedEquals(<TestUsageEvent>[ const TestUsageEvent(NullSafetyAnalysisEvent.kNullSafetyCategory, 'runtime-mode', label: 'NullSafetyMode.sound'), TestUsageEvent(NullSafetyAnalysisEvent.kNullSafetyCategory, 'stats', parameters: CustomDimensions.fromMap(<String, String>{ 'cd49': '0', 'cd50': '1', })), ])); }); } class FakeGroupedValidator extends GroupedValidator { FakeGroupedValidator(super.subValidators); } class FakeDoctorValidator extends DoctorValidator { FakeDoctorValidator(super.title); @override Future<ValidationResult> validate() async { return ValidationResult.crash(Object()); } }
flutter/packages/flutter_tools/test/general.shard/reporting/events_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/reporting/events_test.dart", "repo_id": "flutter", "token_count": 1729 }
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:flutter_tools/src/test/event_printer.dart'; import 'package:flutter_tools/src/test/test_device.dart'; import 'package:test/fake.dart'; import '../../src/common.dart'; void main() { group(EventPrinter, () { final Uri vmServiceUri = Uri.parse('http://localhost:1234'); late EventPrinter eventPrinter; late StringBuffer output; setUp(() { output = StringBuffer(); eventPrinter = EventPrinter(out: output); }); testWithoutContext('handles a null parent', () { final FakeDevice device = FakeDevice(); expect(() => eventPrinter.handleFinishedTest(device), returnsNormally); expect(() => eventPrinter.handleStartedDevice(vmServiceUri), returnsNormally); expect(() => eventPrinter.handleTestCrashed(device), returnsNormally); expect(() => eventPrinter.handleTestTimedOut(device), returnsNormally); }); group('handleStartedDevice', () { testWithoutContext('with non-null VM Service', () { eventPrinter.handleStartedDevice(vmServiceUri); expect( output.toString(), '\n' '[{"event":"test.startedProcess","params":{"vmServiceUri":"http://localhost:1234",' '"observatoryUri":"http://localhost:1234"}}]' '\n', ); }); testWithoutContext('with null VM Service', () { eventPrinter.handleStartedDevice(null); expect( output.toString(), '\n' '[{"event":"test.startedProcess","params":{"vmServiceUri":null,' '"observatoryUri":null}}]' '\n', ); }); }); }); } class FakeDevice extends Fake implements TestDevice { }
flutter/packages/flutter_tools/test/general.shard/test/event_printer_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/test/event_printer_test.dart", "repo_id": "flutter", "token_count": 707 }
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:file/memory.dart'; import 'package:flutter_tools/src/base/logger.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/targets/web.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/web/compile.dart'; import 'package:flutter_tools/src/web/file_generators/flutter_service_worker_js.dart'; import 'package:unified_analytics/unified_analytics.dart'; import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/fakes.dart'; import '../../src/test_build_system.dart'; void main() { late MemoryFileSystem fileSystem; late TestUsage testUsage; late FakeAnalytics fakeAnalytics; late BufferLogger logger; late FakeFlutterVersion flutterVersion; late FlutterProject flutterProject; setUp(() { fileSystem = MemoryFileSystem.test(); testUsage = TestUsage(); logger = BufferLogger.test(); flutterVersion = FakeFlutterVersion(frameworkVersion: '1.0.0', engineRevision: '9.8.7'); fakeAnalytics = getInitializedFakeAnalyticsInstance( fs: fileSystem, fakeFlutterVersion: flutterVersion, ); flutterProject = FlutterProject.fromDirectoryTest(fileSystem.currentDirectory); fileSystem.file('.packages').createSync(); }); testUsingContext('WebBuilder sets environment on success', () async { final TestBuildSystem buildSystem = TestBuildSystem.all(BuildResult(success: true), (Target target, Environment environment) { expect(target, isA<WebServiceWorker>()); expect(environment.defines, <String, String>{ 'TargetFile': 'target', 'HasWebPlugins': 'false', 'ServiceWorkerStrategy': ServiceWorkerStrategy.offlineFirst.cliName, 'BuildMode': 'debug', 'DartObfuscation': 'false', 'TrackWidgetCreation': 'true', 'TreeShakeIcons': 'false', }); expect(environment.engineVersion, '9.8.7'); expect(environment.generateDartPluginRegistry, isFalse); }); final WebBuilder webBuilder = WebBuilder( logger: logger, processManager: FakeProcessManager.any(), buildSystem: buildSystem, usage: testUsage, flutterVersion: flutterVersion, fileSystem: fileSystem, analytics: fakeAnalytics, ); await webBuilder.buildWeb( flutterProject, 'target', BuildInfo.debug, ServiceWorkerStrategy.offlineFirst, compilerConfigs: <WebCompilerConfig>[ const WasmCompilerConfig( optimizationLevel: 0, stripWasm: false, renderer: WebRendererMode.skwasm, ), const JsCompilerConfig.run( nativeNullAssertions: true, renderer: WebRendererMode.canvaskit, ), ], ); expect(logger.statusText, contains('Compiling target for the Web...')); expect(logger.errorText, isEmpty); // Runs ScrubGeneratedPluginRegistrant migrator. expect( logger.traceText, contains('generated_plugin_registrant.dart not found. Skipping.'), ); // Sends build config event expect( testUsage.events, unorderedEquals( <TestUsageEvent>[ const TestUsageEvent( 'build', 'web', label: 'web-compile', parameters: CustomDimensions( buildEventSettings: 'optimizationLevel: 4; web-renderer: skwasm,canvaskit; web-target: wasm,js;', ), ), ], ), ); expect( fakeAnalytics.sentEvents, containsAll(<Event>[ Event.flutterBuildInfo( label: 'web-compile', buildType: 'web', settings: 'optimizationLevel: 4; web-renderer: skwasm,canvaskit; web-target: wasm,js;', ), ]), ); // Sends timing event. final TestTimingEvent timingEvent = testUsage.timings.single; expect(timingEvent.category, 'build'); expect(timingEvent.variableName, 'dual-compile'); expect( analyticsTimingEventExists( sentEvents: fakeAnalytics.sentEvents, workflow: 'build', variableName: 'dual-compile', ), true, ); }); testUsingContext('WebBuilder throws tool exit on failure', () async { final TestBuildSystem buildSystem = TestBuildSystem.all(BuildResult( success: false, exceptions: <String, ExceptionMeasurement>{ 'hello': ExceptionMeasurement( 'hello', const FormatException('illegal character in input string'), StackTrace.current, ), }, )); final WebBuilder webBuilder = WebBuilder( logger: logger, processManager: FakeProcessManager.any(), buildSystem: buildSystem, usage: testUsage, flutterVersion: flutterVersion, fileSystem: fileSystem, analytics: fakeAnalytics, ); await expectLater( () async => webBuilder.buildWeb( flutterProject, 'target', BuildInfo.debug, ServiceWorkerStrategy.offlineFirst, compilerConfigs: <WebCompilerConfig>[ const JsCompilerConfig.run(nativeNullAssertions: true, renderer: WebRendererMode.auto), ] ), throwsToolExit(message: 'Failed to compile application for the Web.')); expect(logger.errorText, contains('Target hello failed: FormatException: illegal character in input string')); expect(testUsage.timings, isEmpty); expect(fakeAnalytics.sentEvents, isEmpty); }); }
flutter/packages/flutter_tools/test/general.shard/web/compile_web_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/web/compile_web_test.dart", "repo_id": "flutter", "token_count": 2303 }
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/file.dart'; import 'package:file/memory.dart'; import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/terminal.dart'; import 'package:flutter_tools/src/cmake_project.dart'; import 'package:flutter_tools/src/windows/migrations/version_migration.dart'; import 'package:test/fake.dart'; import '../../../src/common.dart'; void main () { group('Windows Flutter version migration', () { late MemoryFileSystem memoryFileSystem; late BufferLogger testLogger; late FakeWindowsProject mockProject; late File cmakeFile; late File resourceFile; setUp(() { memoryFileSystem = MemoryFileSystem.test(); cmakeFile = memoryFileSystem.file('CMakeLists.txt'); resourceFile = memoryFileSystem.file('Runner.rc'); testLogger = BufferLogger( terminal: Terminal.test(), outputPreferences: OutputPreferences.test(), ); mockProject = FakeWindowsProject(cmakeFile, resourceFile); }); testWithoutContext('skipped if CMake file is missing', () { const String resourceFileContents = 'Hello world'; resourceFile.writeAsStringSync(resourceFileContents); final VersionMigration migration = VersionMigration( mockProject, testLogger, ); migration.migrate(); expect(cmakeFile.existsSync(), isFalse); expect(resourceFile.existsSync(), isTrue); expect(testLogger.traceText, contains('windows/runner/CMakeLists.txt file not found, skipping version migration')); expect(testLogger.statusText, isEmpty); }); testWithoutContext('skipped if resource file is missing', () { const String cmakeFileContents = 'Hello world'; cmakeFile.writeAsStringSync(cmakeFileContents); final VersionMigration migration = VersionMigration( mockProject, testLogger, ); migration.migrate(); expect(cmakeFile.existsSync(), isTrue); expect(resourceFile.existsSync(), isFalse); expect(testLogger.traceText, contains('windows/runner/Runner.rc file not found, skipping version migration')); expect(testLogger.statusText, isEmpty); }); testWithoutContext('skipped if nothing to migrate', () { const String cmakeFileContents = 'Nothing to migrate'; const String resourceFileContents = 'Nothing to migrate'; cmakeFile.writeAsStringSync(cmakeFileContents); resourceFile.writeAsStringSync(resourceFileContents); final DateTime cmakeUpdatedAt = cmakeFile.lastModifiedSync(); final DateTime resourceUpdatedAt = resourceFile.lastModifiedSync(); final VersionMigration versionMigration = VersionMigration( mockProject, testLogger, ); versionMigration.migrate(); expect(cmakeFile.lastModifiedSync(), cmakeUpdatedAt); expect(cmakeFile.readAsStringSync(), cmakeFileContents); expect(resourceFile.lastModifiedSync(), resourceUpdatedAt); expect(resourceFile.readAsStringSync(), resourceFileContents); expect(testLogger.statusText, isEmpty); }); testWithoutContext('skipped if already migrated', () { const String cmakeFileContents = '# Apply the standard set of build settings. This can be removed for applications\n' '# that need different build settings.\n' 'apply_standard_settings(\${BINARY_NAME})\n' '\n' '# Add preprocessor definitions for the build version.\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\\"\${FLUTTER_VERSION}\\"")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=\${FLUTTER_VERSION_MAJOR}")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=\${FLUTTER_VERSION_MINOR}")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=\${FLUTTER_VERSION_PATCH}")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=\${FLUTTER_VERSION_BUILD}")\n' '\n' '# Disable Windows macros that collide with C++ standard library functions.\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "NOMINMAX")\n'; const String resourceFileContents = '#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)\n' '#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD\n' '#else\n' '#define VERSION_AS_NUMBER 1,0,0,0\n' '#endif\n' '\n' '#if defined(FLUTTER_VERSION)\n' '#define VERSION_AS_STRING FLUTTER_VERSION\n' '#else\n' '#define VERSION_AS_STRING "1.0.0"\n' '#endif\n'; cmakeFile.writeAsStringSync(cmakeFileContents); resourceFile.writeAsStringSync(resourceFileContents); final DateTime cmakeUpdatedAt = cmakeFile.lastModifiedSync(); final DateTime resourceUpdatedAt = resourceFile.lastModifiedSync(); final VersionMigration versionMigration = VersionMigration( mockProject, testLogger, ); versionMigration.migrate(); expect(cmakeFile.lastModifiedSync(), cmakeUpdatedAt); expect(cmakeFile.readAsStringSync(), cmakeFileContents); expect(resourceFile.lastModifiedSync(), resourceUpdatedAt); expect(resourceFile.readAsStringSync(), resourceFileContents); expect(testLogger.statusText, isEmpty); }); testWithoutContext('skipped if already migrated (CRLF)', () { const String cmakeFileContents = '# Apply the standard set of build settings. This can be removed for applications\r\n' '# that need different build settings.\r\n' 'apply_standard_settings(\${BINARY_NAME})\r\n' '\r\n' '# Add preprocessor definitions for the build version.\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\\"\${FLUTTER_VERSION}\\"")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=\${FLUTTER_VERSION_MAJOR}")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=\${FLUTTER_VERSION_MINOR}")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=\${FLUTTER_VERSION_PATCH}")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=\${FLUTTER_VERSION_BUILD}")\r\n' '\r\n' '# Disable Windows macros that collide with C++ standard library functions.\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "NOMINMAX")\r\n'; const String resourceFileContents = '#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)\r\n' '#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD\r\n' '#else\r\n' '#define VERSION_AS_NUMBER 1,0,0,0\r\n' '#endif\r\n' '\r\n' '#if defined(FLUTTER_VERSION)\r\n' '#define VERSION_AS_STRING FLUTTER_VERSION\r\n' '#else\r\n' '#define VERSION_AS_STRING "1.0.0"\r\n' '#endif\r\n'; cmakeFile.writeAsStringSync(cmakeFileContents); resourceFile.writeAsStringSync(resourceFileContents); final DateTime cmakeUpdatedAt = cmakeFile.lastModifiedSync(); final DateTime resourceUpdatedAt = resourceFile.lastModifiedSync(); final VersionMigration versionMigration = VersionMigration( mockProject, testLogger, ); versionMigration.migrate(); expect(cmakeFile.lastModifiedSync(), cmakeUpdatedAt); expect(cmakeFile.readAsStringSync(), cmakeFileContents); expect(resourceFile.lastModifiedSync(), resourceUpdatedAt); expect(resourceFile.readAsStringSync(), resourceFileContents); expect(testLogger.statusText, isEmpty); }); testWithoutContext('migrates project to set version information', () { cmakeFile.writeAsStringSync( '# Apply the standard set of build settings. This can be removed for applications\n' '# that need different build settings.\n' 'apply_standard_settings(\${BINARY_NAME})\n' '\n' '# Disable Windows macros that collide with C++ standard library functions.\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "NOMINMAX")\n' ); resourceFile.writeAsStringSync( '#ifdef FLUTTER_BUILD_NUMBER\n' '#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER\n' '#else\n' '#define VERSION_AS_NUMBER 1,0,0\n' '#endif\n' '\n' '#ifdef FLUTTER_BUILD_NAME\n' '#define VERSION_AS_STRING #FLUTTER_BUILD_NAME\n' '#else\n' '#define VERSION_AS_STRING "1.0.0"\n' '#endif\n' ); final VersionMigration versionMigration = VersionMigration( mockProject, testLogger, ); versionMigration.migrate(); expect(cmakeFile.readAsStringSync(), '# Apply the standard set of build settings. This can be removed for applications\n' '# that need different build settings.\n' 'apply_standard_settings(\${BINARY_NAME})\n' '\n' '# Add preprocessor definitions for the build version.\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\\"\${FLUTTER_VERSION}\\"")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=\${FLUTTER_VERSION_MAJOR}")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=\${FLUTTER_VERSION_MINOR}")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=\${FLUTTER_VERSION_PATCH}")\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=\${FLUTTER_VERSION_BUILD}")\n' '\n' '# Disable Windows macros that collide with C++ standard library functions.\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "NOMINMAX")\n' ); expect(resourceFile.readAsStringSync(), '#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)\n' '#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD\n' '#else\n' '#define VERSION_AS_NUMBER 1,0,0,0\n' '#endif\n' '\n' '#if defined(FLUTTER_VERSION)\n' '#define VERSION_AS_STRING FLUTTER_VERSION\n' '#else\n' '#define VERSION_AS_STRING "1.0.0"\n' '#endif\n' ); expect(testLogger.statusText, contains('windows/runner/CMakeLists.txt does not define version information, updating.')); expect(testLogger.statusText, contains('windows/runner/Runner.rc does not use Flutter version information, updating.')); }); testWithoutContext('migrates project to set version information (CRLF)', () { cmakeFile.writeAsStringSync( '# Apply the standard set of build settings. This can be removed for applications\r\n' '# that need different build settings.\r\n' 'apply_standard_settings(\${BINARY_NAME})\r\n' '\r\n' '# Disable Windows macros that collide with C++ standard library functions.\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "NOMINMAX")\r\n' ); resourceFile.writeAsStringSync( '#ifdef FLUTTER_BUILD_NUMBER\r\n' '#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER\r\n' '#else\r\n' '#define VERSION_AS_NUMBER 1,0,0\r\n' '#endif\r\n' '\r\n' '#ifdef FLUTTER_BUILD_NAME\r\n' '#define VERSION_AS_STRING #FLUTTER_BUILD_NAME\r\n' '#else\r\n' '#define VERSION_AS_STRING "1.0.0"\r\n' '#endif\r\n' ); final VersionMigration versionMigration = VersionMigration( mockProject, testLogger, ); versionMigration.migrate(); expect(cmakeFile.readAsStringSync(), '# Apply the standard set of build settings. This can be removed for applications\r\n' '# that need different build settings.\r\n' 'apply_standard_settings(\${BINARY_NAME})\r\n' '\r\n' '# Add preprocessor definitions for the build version.\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\\"\${FLUTTER_VERSION}\\"")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=\${FLUTTER_VERSION_MAJOR}")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=\${FLUTTER_VERSION_MINOR}")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=\${FLUTTER_VERSION_PATCH}")\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=\${FLUTTER_VERSION_BUILD}")\r\n' '\r\n' '# Disable Windows macros that collide with C++ standard library functions.\r\n' 'target_compile_definitions(\${BINARY_NAME} PRIVATE "NOMINMAX")\r\n' ); expect(resourceFile.readAsStringSync(), '#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)\r\n' '#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD\r\n' '#else\r\n' '#define VERSION_AS_NUMBER 1,0,0,0\r\n' '#endif\r\n' '\r\n' '#if defined(FLUTTER_VERSION)\r\n' '#define VERSION_AS_STRING FLUTTER_VERSION\r\n' '#else\r\n' '#define VERSION_AS_STRING "1.0.0"\r\n' '#endif\r\n' ); expect(testLogger.statusText, contains('windows/runner/CMakeLists.txt does not define version information, updating.')); expect(testLogger.statusText, contains('windows/runner/Runner.rc does not use Flutter version information, updating.')); }); }); } class FakeWindowsProject extends Fake implements WindowsProject { FakeWindowsProject(this.runnerCmakeFile, this.runnerResourceFile); @override final File runnerCmakeFile; @override final File runnerResourceFile; }
flutter/packages/flutter_tools/test/general.shard/windows/migrations/version_migration_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/general.shard/windows/migrations/version_migration_test.dart", "repo_id": "flutter", "token_count": 6057 }
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/file.dart'; import 'package:flutter_tools/src/base/io.dart'; import '../src/common.dart'; import 'test_utils.dart'; void main() { late Directory tempDir; setUp(() async { tempDir = createResolvedTempDirectorySync('run_test.'); }); tearDown(() async { tryToDelete(tempDir); }); testWithoutContext('build succeeds with api 33 features', () async { final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); ProcessResult result = await processManager.run(<String>[ flutterBin, 'create', tempDir.path, '--project-name=testapp', ], workingDirectory: tempDir.path); expect(result, const ProcessResultMatcher()); final File api33File = tempDir .childDirectory('android') .childDirectory('app') .childDirectory('src') .childDirectory('main') .childDirectory('java') .childFile('Android33Api.java'); api33File.createSync(recursive: true); // AccessibilityManager.isAudioDescriptionRequested() is an API 33 feature api33File.writeAsStringSync(''' import android.app.Activity; import android.view.accessibility.AccessibilityManager; import androidx.annotation.Keep; import io.flutter.Log; @Keep public final class Android33Api extends Activity { private AccessibilityManager accessibilityManager; public Android33Api() { accessibilityManager = getSystemService(AccessibilityManager.class); } public void doSomething() { if (accessibilityManager.isAudioDescriptionRequested()) { Log.e("flutter", "User has requested to enable audio descriptions"); } } } '''); result = await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'apk', ], workingDirectory: tempDir.path); expect(result, const ProcessResultMatcher(stdoutPattern: 'app-release.apk')); }); }
flutter/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/android_e2e_api_test.dart", "repo_id": "flutter", "token_count": 699 }
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 'package:file_testing/file_testing.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import '../src/common.dart'; import 'test_utils.dart'; void main() { test('flutter build ios --config only updates generated xcconfig file without performing build', () async { final String workingDirectory = fileSystem.path.join( getFlutterRoot(), 'dev', 'integration_tests', 'flutter_gallery', ); final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); await processManager.run(<String>[ flutterBin, ...getLocalEngineArguments(), 'clean', ], workingDirectory: workingDirectory); final List<String> buildCommand = <String>[ flutterBin, ...getLocalEngineArguments(), 'build', 'ios', '--config-only', '--release', '--obfuscate', '--split-debug-info=info', '--no-codesign', ]; final ProcessResult firstRunResult = await processManager.run(buildCommand, workingDirectory: workingDirectory); expect(firstRunResult, const ProcessResultMatcher(stdoutPattern: 'Running pod install')); final File generatedConfig = fileSystem.file(fileSystem.path.join( workingDirectory, 'ios', 'Flutter', 'Generated.xcconfig', )); // Config is updated if command succeeded. expect(generatedConfig, exists); expect(generatedConfig.readAsStringSync(), contains('DART_OBFUSCATION=true')); // file that only exists if app was fully built. final File frameworkPlist = fileSystem.file(fileSystem.path.join( workingDirectory, 'build', 'ios', 'iphoneos', 'Runner.app', 'AppFrameworkInfo.plist', )); expect(frameworkPlist, isNot(exists)); // Run again with no changes. final ProcessResult secondRunResult = await processManager.run(buildCommand, workingDirectory: workingDirectory); final String secondRunStdout = secondRunResult.stdout.toString(); expect(secondRunResult, const ProcessResultMatcher()); // Do not run "pod install" when nothing changes. expect(secondRunStdout, isNot(contains('pod install'))); }, skip: !platform.isMacOS); // [intended] iOS builds only work on macos. }
flutter/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/build_ios_config_only_test.dart", "repo_id": "flutter", "token_count": 864 }
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 '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/process.dart'; import 'package:flutter_tools/src/base/terminal.dart'; import '../src/common.dart'; import 'test_utils.dart'; const String _kInitialVersion = '3.0.0'; const String _kBranch = 'beta'; final Stdio stdio = Stdio(); final BufferLogger logger = BufferLogger.test( terminal: AnsiTerminal( platform: platform, stdio: stdio, ), outputPreferences: OutputPreferences.test(wrapText: true), ); final ProcessUtils processUtils = ProcessUtils(processManager: processManager, logger: logger); final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', platform.isWindows ? 'flutter.bat' : 'flutter'); /// A test for flutter upgrade & downgrade that checks out a parallel flutter repo. void main() { late Directory parentDirectory; setUp(() { parentDirectory = fileSystem.systemTempDirectory .createTempSync('flutter_tools.'); parentDirectory.createSync(recursive: true); }); tearDown(() { tryToDelete(parentDirectory); }); testWithoutContext('Can upgrade and downgrade a Flutter checkout', () async { final Directory testDirectory = parentDirectory.childDirectory('flutter'); testDirectory.createSync(recursive: true); // Enable longpaths for windows integration test. await processManager.run(<String>[ 'git', 'config', '--system', 'core.longpaths', 'true', ]); void checkExitCode(int code) { expect( exitCode, 0, reason: ''' trace: ${logger.traceText} status: ${logger.statusText} error: ${logger.errorText}''', ); } printOnFailure('Step 1 - clone the $_kBranch of flutter into the test directory'); exitCode = await processUtils.stream(<String>[ 'git', 'clone', 'https://github.com/flutter/flutter.git', ], workingDirectory: parentDirectory.path, trace: true); checkExitCode(exitCode); printOnFailure('Step 2 - switch to the $_kBranch'); exitCode = await processUtils.stream(<String>[ 'git', 'checkout', '--track', '-b', _kBranch, 'origin/$_kBranch', ], workingDirectory: testDirectory.path, trace: true); checkExitCode(exitCode); printOnFailure('Step 3 - revert back to $_kInitialVersion'); exitCode = await processUtils.stream(<String>[ 'git', 'reset', '--hard', _kInitialVersion, ], workingDirectory: testDirectory.path, trace: true); checkExitCode(exitCode); printOnFailure('Step 4 - upgrade to the newest $_kBranch'); // This should update the persistent tool state with the sha for HEAD // This is probably a source of flakes as it mutates system-global state. exitCode = await processUtils.stream(<String>[ flutterBin, 'upgrade', '--verbose', '--working-directory=${testDirectory.path}', // we intentionally run this in a directory outside the test repo to // verify the tool overrides the working directory when invoking git ], workingDirectory: parentDirectory.path, trace: true); checkExitCode(exitCode); printOnFailure('Step 5 - verify that the version is different'); final RunResult versionResult = await processUtils.run(<String>[ 'git', 'describe', '--match', '*.*.*', '--long', '--tags', ], workingDirectory: testDirectory.path); expect(versionResult.stdout, isNot(contains(_kInitialVersion))); printOnFailure('current version is ${versionResult.stdout.trim()}\ninitial was $_kInitialVersion'); printOnFailure('Step 6 - downgrade back to the initial version'); exitCode = await processUtils.stream(<String>[ flutterBin, 'downgrade', '--no-prompt', '--working-directory=${testDirectory.path}', ], workingDirectory: parentDirectory.path, trace: true); checkExitCode(exitCode); printOnFailure('Step 7 - verify downgraded version matches original version'); final RunResult oldVersionResult = await processUtils.run(<String>[ 'git', 'describe', '--match', '*.*.*', '--long', '--tags', ], workingDirectory: testDirectory.path); expect(oldVersionResult.stdout, contains(_kInitialVersion)); printOnFailure('current version is ${oldVersionResult.stdout.trim()}\ninitial was $_kInitialVersion'); }); }
flutter/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/downgrade_upgrade_integration_test.dart", "repo_id": "flutter", "token_count": 1623 }
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 'package:file/file.dart'; import '../src/common.dart'; import 'test_data/hot_reload_const_project.dart'; import 'test_driver.dart'; import 'test_utils.dart'; void main() { late Directory tempDir; final HotReloadConstProject project = HotReloadConstProject(); late FlutterRunTestDriver flutter; setUp(() async { tempDir = createResolvedTempDirectorySync('hot_reload_test.'); await project.setUpIn(tempDir); flutter = FlutterRunTestDriver(tempDir); }); tearDown(() async { await flutter.stop(); tryToDelete(tempDir); }); testWithoutContext('hot reload displays a formatted error message when removing a field from a const class', () async { await flutter.run(); project.removeFieldFromConstClass(); expect(flutter.hotReload(), throwsA(isA<Exception>().having((Exception e) => e.toString(), 'message', contains('Try performing a hot restart instead.')))); }); }
flutter/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/hot_reload_errors_test.dart", "repo_id": "flutter", "token_count": 339 }
792
flutter/test/full_app_fixtures/vanilla version:1.22.6_stable
flutter/packages/flutter_tools/test/integration.shard/test_data/full_apps/vanilla_app_1_22_6_stable.ensure/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/test_data/full_apps/vanilla_app_1_22_6_stable.ensure", "repo_id": "flutter", "token_count": 25 }
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 'dart:async'; import 'dart:convert'; import 'dart:io' as io; // flutter_ignore: dart_io_import import 'package:file/file.dart'; import 'package:flutter_tools/src/base/file_system.dart'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/utils.dart'; import 'package:process/process.dart'; import 'package:vm_service/vm_service.dart'; import 'package:vm_service/vm_service_io.dart'; import '../src/common.dart'; import 'test_utils.dart'; // Set this to true for debugging to get verbose logs written to stdout. // The logs include the following: // <=stdout= data that the flutter tool running in --verbose mode wrote to stdout. // <=stderr= data that the flutter tool running in --verbose mode wrote to stderr. // =stdin=> data that the test sent to the flutter tool over stdin. // =vm=> data that was sent over the VM service channel to the app running on the test device. // <=vm= data that was sent from the app on the test device over the VM service channel. // Messages regarding what the test is doing. // If this is false, then only critical errors and logs when things appear to be // taking a long time are printed to the console. const bool _printDebugOutputToStdOut = false; final DateTime startTime = DateTime.now(); const Duration defaultTimeout = Duration(seconds: 5); const Duration appStartTimeout = Duration(seconds: 120); const Duration quitTimeout = Duration(seconds: 10); abstract class FlutterTestDriver { FlutterTestDriver( this._projectFolder, { String? logPrefix, }) : _logPrefix = logPrefix != null ? '$logPrefix: ' : ''; final Directory _projectFolder; final String _logPrefix; Process? _process; int? _processPid; final StreamController<String> _stdout = StreamController<String>.broadcast(); final StreamController<String> _stderr = StreamController<String>.broadcast(); final StreamController<String> _allMessages = StreamController<String>.broadcast(); final StringBuffer _errorBuffer = StringBuffer(); String? _lastResponse; Uri? _vmServiceWsUri; int? _attachPort; bool _hasExited = false; VmService? _vmService; String get lastErrorInfo => _errorBuffer.toString(); Stream<String> get stdout => _stdout.stream; Stream<String> get stderr => _stderr.stream; int? get vmServicePort => _vmServiceWsUri?.port; bool get hasExited => _hasExited; Uri? get vmServiceWsUri => _vmServiceWsUri; String lastTime = ''; void _debugPrint(String message, { String topic = '' }) { const int maxLength = 2500; final String truncatedMessage = message.length > maxLength ? '${message.substring(0, maxLength)}...' : message; final String line = '${topic.padRight(10)} $truncatedMessage'; _allMessages.add(line); final int timeInSeconds = DateTime.now().difference(startTime).inSeconds; String time = '${timeInSeconds.toString().padLeft(5)}s '; if (time == lastTime) { time = ' ' * time.length; } else { lastTime = time; } if (_printDebugOutputToStdOut) { // This is the one place in this file that can call print. It is gated by // _printDebugOutputToStdOut which should not be set to true in CI; it is // intended only for use in local debugging. // ignore: avoid_print print('$time$_logPrefix$line'); } else { printOnFailure('$time$_logPrefix$line'); } } Future<void> _setupProcess( List<String> arguments, { String? script, bool withDebugger = false, }) async { final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter'); if (withDebugger) { arguments.add('--start-paused'); } if (_printDebugOutputToStdOut) { arguments.add('--verbose'); } if (script != null) { arguments.add(script); } _debugPrint('Spawning flutter $arguments in ${_projectFolder.path}'); const ProcessManager processManager = LocalProcessManager(); _process = await processManager.start( <String>[flutterBin] .followedBy(arguments) .toList(), workingDirectory: _projectFolder.path, // The web environment variable has the same effect as `flutter config --enable-web`. environment: <String, String>{ 'FLUTTER_TEST': 'true', 'FLUTTER_WEB': 'true', }, ); // This class doesn't use the result of the future. It's made available // via a getter for external uses. unawaited(_process!.exitCode.then((int code) { _debugPrint('Process exited ($code)'); _hasExited = true; })); transformToLines(_process!.stdout).listen(_stdout.add); transformToLines(_process!.stderr).listen(_stderr.add); // Capture stderr to a buffer so we can show it all if any requests fail. _stderr.stream.listen(_errorBuffer.writeln); // This is just debug printing to aid running/debugging tests locally. _stdout.stream.listen((String message) => _debugPrint(message, topic: '<=stdout=')); _stderr.stream.listen((String message) => _debugPrint(message, topic: '<=stderr=')); } Future<void> get done async => _process?.exitCode; Future<void> connectToVmService({ bool pauseOnExceptions = false }) async { _vmService = await vmServiceConnectUri('$_vmServiceWsUri'); _vmService!.onSend.listen((String s) => _debugPrint(s, topic: '=vm=>')); _vmService!.onReceive.listen((String s) => _debugPrint(s, topic: '<=vm=')); final Completer<void> isolateStarted = Completer<void>(); _vmService!.onIsolateEvent.listen((Event event) { if (event.kind == EventKind.kIsolateStart) { isolateStarted.complete(); } else if (event.kind == EventKind.kIsolateExit && event.isolate?.id == _flutterIsolateId) { // Hot restarts cause all the isolates to exit, so we need to refresh // our idea of what the Flutter isolate ID is. _flutterIsolateId = null; } }); await Future.wait(<Future<Success>>[ _vmService!.streamListen('Isolate'), _vmService!.streamListen('Debug'), ]); if ((await _vmService!.getVM()).isolates?.isEmpty ?? true) { await isolateStarted.future; } await waitForPause(); if (pauseOnExceptions) { await _vmService!.setIsolatePauseMode( await _getFlutterIsolateId(), exceptionPauseMode: ExceptionPauseMode.kUnhandled, ); } } Future<Response> callServiceExtension( String extension, { Map<String, Object?> args = const <String, Object>{}, }) async { final int? port = _vmServiceWsUri != null ? vmServicePort : _attachPort; final VmService vmService = await vmServiceConnectUri('ws://localhost:$port/ws'); final Isolate isolate = await waitForExtension(vmService, extension); return vmService.callServiceExtension( extension, isolateId: isolate.id, args: args, ); } Future<int> quit() => _killGracefully(); Future<int> _killGracefully() async { if (_processPid == null) { return -1; } // If we try to kill the process while it's paused, we'll end up terminating // it forcefully and it won't terminate child processes, so we need to ensure // it's running before terminating. await resume().timeout(defaultTimeout) .then( (Isolate? isolate) => isolate, onError: (Object e) { _debugPrint('Ignoring failure to resume during shutdown'); return null; }, ); _debugPrint('Sending SIGTERM to $_processPid..'); io.Process.killPid(_processPid!); return _process!.exitCode.timeout(quitTimeout, onTimeout: _killForcefully); } Future<int> _killForcefully() { _debugPrint('Sending SIGKILL to $_processPid..'); ProcessSignal.sigkill.send(_processPid!); return _process!.exitCode; } String? _flutterIsolateId; Future<String> _getFlutterIsolateId() async { // Currently these tests only have a single isolate. If this // ceases to be the case, this code will need changing. if (_flutterIsolateId == null) { final VM vm = await _vmService!.getVM(); _flutterIsolateId = vm.isolates!.single.id; } return _flutterIsolateId!; } Future<Isolate> getFlutterIsolate() async { final Isolate isolate = await _vmService!.getIsolate(await _getFlutterIsolateId()); return isolate; } /// Add a breakpoint and wait for it to trip the program execution. /// /// Only call this when you are absolutely sure that the program under test /// will hit the breakpoint _in the future_. /// /// In particular, do not call this if the program is currently racing to pass /// the line of code you are breaking on. Pretend that calling this will take /// an hour before setting the breakpoint. Would the code still eventually hit /// the breakpoint and stop? Future<void> breakAt(Uri uri, int line) async { final String isolateId = await _getFlutterIsolateId(); final Future<Event> event = subscribeToPauseEvent(isolateId); await addBreakpoint(uri, line); await waitForPauseEvent(isolateId, event); } Future<void> addBreakpoint(Uri uri, int line) async { _debugPrint('Sending breakpoint for: $uri:$line'); await _vmService!.addBreakpointWithScriptUri( await _getFlutterIsolateId(), uri.toString(), line, ); } Future<Event> subscribeToPauseEvent(String isolateId) => subscribeToDebugEvent('Pause', isolateId); Future<Event> subscribeToResumeEvent(String isolateId) => subscribeToDebugEvent('Resume', isolateId); Future<Isolate> waitForPauseEvent(String isolateId, Future<Event> event) => waitForDebugEvent('Pause', isolateId, event); Future<Isolate> waitForResumeEvent(String isolateId, Future<Event> event) => waitForDebugEvent('Resume', isolateId, event); Future<Isolate> waitForPause() async => subscribeAndWaitForDebugEvent('Pause', await _getFlutterIsolateId()); Future<Isolate> waitForResume() async => subscribeAndWaitForDebugEvent('Resume', await _getFlutterIsolateId()); Future<Isolate> subscribeAndWaitForDebugEvent(String kind, String isolateId) { final Future<Event> event = subscribeToDebugEvent(kind, isolateId); return waitForDebugEvent(kind, isolateId, event); } /// Subscribes to debug events containing [kind]. /// /// Returns a future that completes when the [kind] event is received. /// /// This method should be called before the command that triggers /// the event to subscribe to the event in time, for example: /// /// ```dart /// var event = subscribeToDebugEvent('Pause', id); // Subscribe to 'pause' events. /// ... // Code that pauses the app. /// await waitForDebugEvent('Pause', id, event); // Isolate is paused now. /// ``` Future<Event> subscribeToDebugEvent(String kind, String isolateId) { _debugPrint('Start listening for $kind events'); return _vmService!.onDebugEvent .where((Event event) { return event.isolate?.id == isolateId && (event.kind?.startsWith(kind) ?? false); }).first; } /// Wait for the [event] if needed. /// /// Return immediately if the isolate is already in the desired state. Future<Isolate> waitForDebugEvent(String kind, String isolateId, Future<Event> event) { return _timeoutWithMessages<Isolate>( () async { // But also check if the isolate was already at the state we need (only after we've // set up the subscription) to avoid races. If it already in the desired state, we // don't need to wait for the event. final VmService vmService = _vmService!; final Isolate isolate = await vmService.getIsolate(isolateId); if (isolate.pauseEvent?.kind?.startsWith(kind) ?? false) { _debugPrint('Isolate was already at "$kind" (${isolate.pauseEvent!.kind}).'); event.ignore(); } else { _debugPrint('Waiting for "$kind" event to arrive...'); await event; } return vmService.getIsolate(isolateId); }, task: 'Waiting for isolate to $kind', ); } Future<Isolate?> resume({ bool waitForNextPause = false }) => _resume(null, waitForNextPause); Future<Isolate?> stepOver({ bool waitForNextPause = true }) => _resume(StepOption.kOver, waitForNextPause); Future<Isolate?> stepOverAsync({ bool waitForNextPause = true }) => _resume(StepOption.kOverAsyncSuspension, waitForNextPause); Future<Isolate?> stepInto({ bool waitForNextPause = true }) => _resume(StepOption.kInto, waitForNextPause); Future<Isolate?> stepOut({ bool waitForNextPause = true }) => _resume(StepOption.kOut, waitForNextPause); Future<bool> isAtAsyncSuspension() async { final Isolate isolate = await getFlutterIsolate(); return isolate.pauseEvent?.atAsyncSuspension ?? false; } Future<Isolate?> stepOverOrOverAsyncSuspension({ bool waitForNextPause = true }) async { if (await isAtAsyncSuspension()) { return stepOverAsync(waitForNextPause: waitForNextPause); } return stepOver(waitForNextPause: waitForNextPause); } Future<Isolate?> _resume(String? step, bool waitForNextPause) async { final String isolateId = await _getFlutterIsolateId(); final Future<Event> resume = subscribeToResumeEvent(isolateId); final Future<Event> pause = subscribeToPauseEvent(isolateId); await _timeoutWithMessages<Object?>( () async => _vmService!.resume(isolateId, step: step), task: 'Resuming isolate (step=$step)', ); await waitForResumeEvent(isolateId, resume); return waitForNextPause ? waitForPauseEvent(isolateId, pause) : null; } Future<ObjRef> evaluateInFrame(String expression) async { return _timeoutWithMessages<ObjRef>( () async => await _vmService!.evaluateInFrame(await _getFlutterIsolateId(), 0, expression) as ObjRef, task: 'Evaluating expression ($expression)', ); } Future<ObjRef> evaluate(String targetId, String expression) async { return _timeoutWithMessages<ObjRef>( () async => await _vmService!.evaluate(await _getFlutterIsolateId(), targetId, expression) as ObjRef, task: 'Evaluating expression ($expression for $targetId)', ); } Future<Frame> getTopStackFrame() async { final String flutterIsolateId = await _getFlutterIsolateId(); final Stack stack = await _vmService!.getStack(flutterIsolateId); final List<Frame>? frames = stack.frames; if (frames == null || frames.isEmpty) { throw Exception('Stack is empty'); } return frames.first; } Future<SourcePosition?> getSourceLocation() async { final String flutterIsolateId = await _getFlutterIsolateId(); final Frame frame = await getTopStackFrame(); final Script script = await _vmService!.getObject(flutterIsolateId, frame.location!.script!.id!) as Script; return _lookupTokenPos(script.tokenPosTable!, frame.location!.tokenPos!); } SourcePosition? _lookupTokenPos(List<List<int>> table, int tokenPos) { for (final List<int> row in table) { final int lineNumber = row[0]; int index = 1; for (index = 1; index < row.length - 1; index += 2) { if (row[index] == tokenPos) { return SourcePosition(lineNumber, row[index + 1]); } } } return null; } Future<Map<String, Object?>> _waitFor({ String? event, int? id, Duration timeout = defaultTimeout, bool ignoreAppStopEvent = false, }) async { assert(event != null || id != null); assert(event == null || id == null); final String interestingOccurrence = event != null ? '$event event' : 'response to request $id'; final Completer<Map<String, Object?>> response = Completer<Map<String, Object?>>(); StreamSubscription<String>? subscription; subscription = _stdout.stream.listen((String line) async { final Map<String, Object?>? json = parseFlutterResponse(line); _lastResponse = line; if (json == null) { return; } if ((event != null && json['event'] == event) || (id != null && json['id'] == id)) { await subscription?.cancel(); _debugPrint('OK ($interestingOccurrence)'); response.complete(json); } else if (!ignoreAppStopEvent && json['event'] == 'app.stop') { await subscription?.cancel(); final StringBuffer error = StringBuffer(); error.write('Received app.stop event while waiting for $interestingOccurrence\n\n$_errorBuffer'); final Object? jsonParams = json['params']; if (jsonParams is Map<String, Object?>) { if (jsonParams['error'] != null) { error.write('${jsonParams['error']}\n\n'); } final Object? trace = jsonParams['trace']; if (trace != null) { error.write('$trace\n\n'); } } response.completeError(Exception(error.toString())); } }); return _timeoutWithMessages( () => response.future, timeout: timeout, task: 'Expecting $interestingOccurrence', ).whenComplete(subscription.cancel); } Future<T> _timeoutWithMessages<T>( Future<T> Function() callback, { required String task, Duration timeout = defaultTimeout, }) { if (_printDebugOutputToStdOut) { _debugPrint('$task...'); final Timer longWarning = Timer(timeout, () => _debugPrint('$task is taking longer than usual...')); return callback().whenComplete(longWarning.cancel); } // We're not showing all output to the screen, so let's capture the output // that we would have printed if we were, and output it if we take longer // than the timeout or if we get an error. final StringBuffer messages = StringBuffer('$task\n'); final DateTime start = DateTime.now(); bool timeoutExpired = false; void logMessage(String logLine) { final int ms = DateTime.now().difference(start).inMilliseconds; final String formattedLine = '[+ ${ms.toString().padLeft(5)}] $logLine'; messages.writeln(formattedLine); } final StreamSubscription<String> subscription = _allMessages.stream.listen(logMessage); final Timer longWarning = Timer(timeout, () { _debugPrint(messages.toString()); timeoutExpired = true; _debugPrint('$task is taking longer than usual...'); }); final Future<T> future = callback().whenComplete(longWarning.cancel); return future.then( (T t) => t, onError: (Object error) { if (!timeoutExpired) { timeoutExpired = true; _debugPrint(messages.toString()); } throw error; // ignore: only_throw_errors }, ).whenComplete(() => subscription.cancel()); } } class FlutterRunTestDriver extends FlutterTestDriver { FlutterRunTestDriver( super.projectFolder, { super.logPrefix, this.spawnDdsInstance = true, }); String? _currentRunningAppId; String? _currentRunningDeviceId; String? _currentRunningMode; String? get currentRunningDeviceId => _currentRunningDeviceId; String? get currentRunningMode => _currentRunningMode; Future<void> run({ bool withDebugger = false, bool startPaused = false, bool pauseOnExceptions = false, bool chrome = false, bool expressionEvaluation = true, bool structuredErrors = false, bool serveObservatory = false, String? script, List<String>? additionalCommandArgs, }) async { await _setupProcess( <String>[ 'run', if (!chrome) '--disable-service-auth-codes', '--machine', if (!spawnDdsInstance) '--no-dds', '--${serveObservatory ? '' : 'no-'}serve-observatory', ...getLocalEngineArguments(), '-d', if (chrome) ...<String>[ 'chrome', '--web-run-headless', if (!expressionEvaluation) '--no-web-enable-expression-evaluation', ] else 'flutter-tester', if (structuredErrors) '--dart-define=flutter.inspector.structuredErrors=true', ...?additionalCommandArgs, ], withDebugger: withDebugger, startPaused: startPaused, pauseOnExceptions: pauseOnExceptions, script: script, ); } Future<void> attach( int port, { bool withDebugger = false, bool startPaused = false, bool pauseOnExceptions = false, bool serveObservatory = false, List<String>? additionalCommandArgs, }) async { _attachPort = port; await _setupProcess( <String>[ 'attach', ...getLocalEngineArguments(), '--machine', if (!spawnDdsInstance) '--no-dds', '--${serveObservatory ? '' : 'no-'}serve-observatory', '-d', 'flutter-tester', '--debug-port', '$port', ...?additionalCommandArgs, ], withDebugger: withDebugger, startPaused: startPaused, pauseOnExceptions: pauseOnExceptions, attachPort: port, ); } @override Future<void> _setupProcess( List<String> args, { String? script, bool withDebugger = false, bool startPaused = false, bool pauseOnExceptions = false, int? attachPort, }) async { assert(!startPaused || withDebugger); await super._setupProcess( args, script: script, withDebugger: withDebugger, ); final Completer<void> prematureExitGuard = Completer<void>(); // If the process exits before all of the `await`s below are done, then it // exited prematurely. This causes the currently suspended `await` to // deadlock until the test times out. Instead, this causes the test to fail // fast. unawaited(_process?.exitCode.then((_) { if (!prematureExitGuard.isCompleted) { prematureExitGuard.completeError(Exception('Process exited prematurely: ${args.join(' ')}: $_errorBuffer')); } })); unawaited(() async { try { // Stash the PID so that we can terminate the VM more reliably than using // _process.kill() (`flutter` is a shell script so _process itself is a // shell, not the flutter tool's Dart process). final Map<String, Object?> connected = await _waitFor(event: 'daemon.connected'); _processPid = (connected['params'] as Map<String, Object?>?)?['pid'] as int?; // Set this up now, but we don't wait it yet. We want to make sure we don't // miss it while waiting for debugPort below. final Future<Map<String, Object?>> start = _waitFor(event: 'app.start', timeout: appStartTimeout); final Future<Map<String, Object?>> started = _waitFor(event: 'app.started', timeout: appStartTimeout); if (withDebugger) { final Map<String, Object?> debugPort = await _waitFor(event: 'app.debugPort', timeout: appStartTimeout); final String wsUriString = (debugPort['params']! as Map<String, Object?>)['wsUri']! as String; _vmServiceWsUri = Uri.parse(wsUriString); await connectToVmService(pauseOnExceptions: pauseOnExceptions); if (!startPaused) { await resume(); } } // In order to call service extensions from test runners started with // attach, we need to store the port that the test runner was attached // to. if (_vmServiceWsUri == null && attachPort != null) { _attachPort = attachPort; } // Now await the start/started events; if it had already happened the future will // have already completed. final Map<String, Object?>? startParams = (await start)['params'] as Map<String, Object?>?; final Map<String, Object?>? startedParams = (await started)['params'] as Map<String, Object?>?; _currentRunningAppId = startedParams?['appId'] as String?; _currentRunningDeviceId = startParams?['deviceId'] as String?; _currentRunningMode = startParams?['mode'] as String?; prematureExitGuard.complete(); } on Exception catch (error, stackTrace) { prematureExitGuard.completeError(Exception(error.toString()), stackTrace); } }()); return prematureExitGuard.future; } Future<void> hotRestart({ bool pause = false, bool debounce = false}) => _restart(fullRestart: true, pause: pause); Future<void> hotReload({ bool debounce = false, int? debounceDurationOverrideMs }) => _restart(debounce: debounce, debounceDurationOverrideMs: debounceDurationOverrideMs); Future<void> scheduleFrame() async { if (_currentRunningAppId == null) { throw Exception('App has not started yet'); } await _sendRequest( 'app.callServiceExtension', <String, Object?>{'appId': _currentRunningAppId, 'methodName': 'ext.ui.window.scheduleFrame'}, ); } Future<void> _restart({ bool fullRestart = false, bool pause = false, bool debounce = false, int? debounceDurationOverrideMs }) async { if (_currentRunningAppId == null) { throw Exception('App has not started yet'); } _debugPrint('Performing ${ pause ? "paused " : "" }${ fullRestart ? "hot restart" : "hot reload" }...'); final Map<String, Object?>? hotReloadResponse = await _sendRequest( 'app.restart', <String, Object?>{'appId': _currentRunningAppId, 'fullRestart': fullRestart, 'pause': pause, 'debounce': debounce, 'debounceDurationOverrideMs': debounceDurationOverrideMs}, ) as Map<String, Object?>?; _debugPrint('${fullRestart ? "Hot restart" : "Hot reload"} complete.'); if (hotReloadResponse == null || hotReloadResponse['code'] != 0) { _throwErrorResponse('Hot ${fullRestart ? 'restart' : 'reload'} request failed'); } } Future<int> detach() async { final Process? process = _process; if (process == null) { return 0; } final VmService? vmService = _vmService; if (vmService != null) { _debugPrint('Closing VM service...'); await vmService.dispose(); } if (_currentRunningAppId != null) { _debugPrint('Detaching from app...'); await Future.any<void>(<Future<void>>[ process.exitCode, _sendRequest( 'app.detach', <String, Object?>{'appId': _currentRunningAppId}, ), ]).timeout( quitTimeout, onTimeout: () { _debugPrint('app.detach did not return within $quitTimeout'); }, ); _currentRunningAppId = null; } _debugPrint('Waiting for process to end...'); return process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully); } Future<int> stop() async { final VmService? vmService = _vmService; if (vmService != null) { _debugPrint('Closing VM service...'); await vmService.dispose(); } final Process? process = _process; if (_currentRunningAppId != null) { _debugPrint('Stopping application...'); await Future.any<void>(<Future<void>>[ process!.exitCode, _sendRequest( 'app.stop', <String, Object?>{'appId': _currentRunningAppId}, ), ]).timeout( quitTimeout, onTimeout: () { _debugPrint('app.stop did not return within $quitTimeout'); }, ); _currentRunningAppId = null; } if (process != null) { _debugPrint('Waiting for process to end...'); return process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully); } return 0; } int id = 1; Future<Object?> _sendRequest(String method, Object? params) async { final int requestId = id++; final Map<String, Object?> request = <String, Object?>{ 'id': requestId, 'method': method, 'params': params, }; final String jsonEncoded = json.encode(<Map<String, Object?>>[request]); _debugPrint(jsonEncoded, topic: '=stdin=>'); // Set up the response future before we send the request to avoid any // races. If the method we're calling is app.stop then we tell _waitFor not // to throw if it sees an app.stop event before the response to this request. final Future<Map<String, Object?>> responseFuture = _waitFor( id: requestId, ignoreAppStopEvent: method == 'app.stop' || method == 'app.detach', ); _process?.stdin.writeln(jsonEncoded); final Map<String, Object?> response = await responseFuture; if (response['error'] != null || response['result'] == null) { _throwErrorResponse('Unexpected error response'); } return response['result']; } void _throwErrorResponse(String message) { throw Exception('$message\n\n$_lastResponse\n\n$_errorBuffer'.trim()); } final bool spawnDdsInstance; } class FlutterTestTestDriver extends FlutterTestDriver { FlutterTestTestDriver(super.projectFolder, {super.logPrefix}); Future<void> test({ String testFile = 'test/test.dart', String? deviceId, bool withDebugger = false, bool pauseOnExceptions = false, bool coverage = false, Future<void> Function()? beforeStart, }) async { await _setupProcess(<String>[ 'test', ...getLocalEngineArguments(), '--disable-service-auth-codes', '--machine', if (coverage) '--coverage', if (deviceId != null) ...<String>['-d', deviceId], ], script: testFile, withDebugger: withDebugger, pauseOnExceptions: pauseOnExceptions, beforeStart: beforeStart); } @override Future<void> _setupProcess( List<String> args, { String? script, bool withDebugger = false, bool pauseOnExceptions = false, Future<void> Function()? beforeStart, }) async { await super._setupProcess( args, script: script, withDebugger: withDebugger, ); // Stash the PID so that we can terminate the VM more reliably than using // _proc.kill() (because _proc is a shell, because `flutter` is a shell // script). final Map<String, Object?>? version = await _waitForJson(); _processPid = version?['pid'] as int?; if (withDebugger) { final Map<String, Object?> startedProcessParams = (await _waitFor(event: 'test.startedProcess', timeout: appStartTimeout))['params']! as Map<String, Object?>; final String vmServiceHttpString = startedProcessParams['vmServiceUri']! as String; _vmServiceWsUri = Uri.parse(vmServiceHttpString).replace(scheme: 'ws', path: '/ws'); await connectToVmService(pauseOnExceptions: pauseOnExceptions); // Allow us to run code before we start, eg. to set up breakpoints. if (beforeStart != null) { await beforeStart(); } await resume(); } } Future<Map<String, Object?>?> _waitForJson({ Duration timeout = defaultTimeout, }) async { return _timeoutWithMessages<Map<String, Object?>?>( () => _stdout.stream.map<Map<String, Object?>?>(_parseJsonResponse) .firstWhere((Map<String, Object?>? output) => output != null), timeout: timeout, task: 'Waiting for JSON', ); } Map<String, Object?>? _parseJsonResponse(String line) { try { return castStringKeyedMap(json.decode(line)); } on Exception { // Not valid JSON, so likely some other output. return null; } } Future<void> waitForCompletion() async { final Completer<bool> done = Completer<bool>(); // Waiting for `{"success":true,"type":"done",...}` line indicating // end of test run. final StreamSubscription<String> subscription = _stdout.stream.listen( (String line) async { final Map<String, Object?>? json = _parseJsonResponse(line); if (json != null && json['type'] != null && json['success'] != null) { done.complete(json['type'] == 'done' && json['success'] == true); } }); await resume(); final Future<void> timeoutFuture = Future<void>.delayed(defaultTimeout); await Future.any<void>(<Future<void>>[done.future, timeoutFuture]); await subscription.cancel(); if (!done.isCompleted) { await quit(); } } } Stream<String> transformToLines(Stream<List<int>> byteStream) { return byteStream.transform<String>(utf8.decoder).transform<String>(const LineSplitter()); } Map<String, Object?>? parseFlutterResponse(String line) { if (line.startsWith('[') && line.endsWith(']') && line.length > 2) { try { final Map<String, Object?>? response = castStringKeyedMap((json.decode(line) as List<Object?>)[0]); return response; } on FormatException { // Not valid JSON, so likely some other output that was surrounded by [brackets] return null; } } return null; } class SourcePosition { SourcePosition(this.line, this.column); final int line; final int column; } Future<Isolate> waitForExtension(VmService vmService, String extension) async { final Completer<void> completer = Completer<void>(); try { await vmService.streamListen(EventStreams.kExtension); } on RPCError { // Do nothing, already subscribed. } vmService.onExtensionEvent.listen((Event event) { if (event.json?['extensionKind'] == 'Flutter.FrameworkInitialization') { completer.complete(); } }); final IsolateRef isolateRef = (await vmService.getVM()).isolates!.first; final Isolate isolate = await vmService.getIsolate(isolateRef.id!); if (isolate.extensionRPCs!.contains(extension)) { return isolate; } await completer.future; return isolate; }
flutter/packages/flutter_tools/test/integration.shard/test_driver.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/integration.shard/test_driver.dart", "repo_id": "flutter", "token_count": 12179 }
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:flutter_tools/src/application_package.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/project.dart'; /// A list of fake devices to test JSON serialization /// (`Device.toJson()` and `--machine` flag for `devices` command) List<FakeDeviceJsonData> fakeDevices = <FakeDeviceJsonData>[ FakeDeviceJsonData( FakeDevice('ephemeral', 'ephemeral', type: PlatformType.android), <String, Object>{ 'name': 'ephemeral', 'id': 'ephemeral', 'isSupported': true, 'targetPlatform': 'android-arm', 'emulator': true, 'sdk': 'Test SDK (1.2.3)', 'capabilities': <String, Object>{ 'hotReload': true, 'hotRestart': true, 'screenshot': false, 'fastStart': false, 'flutterExit': true, 'hardwareRendering': true, 'startPaused': true, }, } ), FakeDeviceJsonData( FakeDevice('webby', 'webby') ..targetPlatform = Future<TargetPlatform>.value(TargetPlatform.web_javascript) ..sdkNameAndVersion = Future<String>.value('Web SDK (1.2.4)'), <String,Object>{ 'name': 'webby', 'id': 'webby', 'isSupported': true, 'targetPlatform': 'web-javascript', 'emulator': true, 'sdk': 'Web SDK (1.2.4)', 'capabilities': <String, Object>{ 'hotReload': true, 'hotRestart': true, 'screenshot': false, 'fastStart': false, 'flutterExit': true, 'hardwareRendering': true, 'startPaused': true, }, }, ), FakeDeviceJsonData( FakeDevice( 'wireless android', 'wireless-android', type: PlatformType.android, connectionInterface: DeviceConnectionInterface.wireless, ), <String, Object>{ 'name': 'wireless android', 'id': 'wireless-android', 'isSupported': true, 'targetPlatform': 'android-arm', 'emulator': true, 'sdk': 'Test SDK (1.2.3)', 'capabilities': <String, Object>{ 'hotReload': true, 'hotRestart': true, 'screenshot': false, 'fastStart': false, 'flutterExit': true, 'hardwareRendering': true, 'startPaused': true, }, } ), FakeDeviceJsonData( FakeDevice( 'wireless ios', 'wireless-ios', type:PlatformType.ios, connectionInterface: DeviceConnectionInterface.wireless, ) ..targetPlatform = Future<TargetPlatform>.value(TargetPlatform.ios) ..sdkNameAndVersion = Future<String>.value('iOS 16'), <String,Object>{ 'name': 'wireless ios', 'id': 'wireless-ios', 'isSupported': true, 'targetPlatform': 'ios', 'emulator': true, 'sdk': 'iOS 16', 'capabilities': <String, Object>{ 'hotReload': true, 'hotRestart': true, 'screenshot': false, 'fastStart': false, 'flutterExit': true, 'hardwareRendering': true, 'startPaused': true, }, }, ), ]; /// Fake device to test `devices` command. class FakeDevice extends Device { FakeDevice(this.name, String id, { bool ephemeral = true, bool isSupported = true, bool isSupportedForProject = true, this.isConnected = true, this.connectionInterface = DeviceConnectionInterface.attached, PlatformType type = PlatformType.web, LaunchResult? launchResult, this.deviceLogReader, bool supportsFlavors = false, }) : _isSupported = isSupported, _isSupportedForProject = isSupportedForProject, _launchResult = launchResult ?? LaunchResult.succeeded(), _supportsFlavors = supportsFlavors, super( id, platformType: type, category: Category.mobile, ephemeral: ephemeral, ); final bool _isSupported; final bool _isSupportedForProject; final bool _supportsFlavors; final LaunchResult _launchResult; DeviceLogReader? deviceLogReader; @override final String name; @override Future<LaunchResult> startApp(ApplicationPackage? package, { String? mainPath, String? route, DebuggingOptions? debuggingOptions, Map<String, dynamic>? platformArgs, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, }) async => _launchResult; @override Future<bool> stopApp(ApplicationPackage? app, { String? userIdentifier, }) async => true; @override Future<bool> uninstallApp( ApplicationPackage app, { String? userIdentifier, }) async => true; @override Future<void> dispose() async {} @override Future<TargetPlatform> targetPlatform = Future<TargetPlatform>.value(TargetPlatform.android_arm); @override void noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); @override bool isSupportedForProject(FlutterProject flutterProject) => _isSupportedForProject; @override bool isSupported() => _isSupported; @override bool get supportsFlavors => _supportsFlavors; @override bool isConnected; @override DeviceConnectionInterface connectionInterface; @override Future<bool> isLocalEmulator = Future<bool>.value(true); @override Future<String> sdkNameAndVersion = Future<String>.value('Test SDK (1.2.3)'); @override FutureOr<DeviceLogReader> getLogReader({ ApplicationPackage? app, bool includePastLogs = false, }) => deviceLogReader ?? FakeDeviceLogReader(); } /// Combines fake device with its canonical JSON representation. class FakeDeviceJsonData { FakeDeviceJsonData(this.dev, this.json); final FakeDevice dev; final Map<String, Object> json; } class FakePollingDeviceDiscovery extends PollingDeviceDiscovery { FakePollingDeviceDiscovery({ this.requiresExtendedWirelessDeviceDiscovery = false, }) : super('mock'); final List<Device> _devices = <Device>[]; final StreamController<Device> _onAddedController = StreamController<Device>.broadcast(); final StreamController<Device> _onRemovedController = StreamController<Device>.broadcast(); @override Future<List<Device>> pollingGetDevices({ Duration? timeout }) async { lastPollingTimeout = timeout; return _devices; } Duration? lastPollingTimeout; @override bool get supportsPlatform => true; @override bool get canListAnything => true; @override bool requiresExtendedWirelessDeviceDiscovery; void addDevice(Device device) { _devices.add(device); _onAddedController.add(device); } void _removeDevice(Device device) { _devices.remove(device); _onRemovedController.add(device); } void setDevices(List<Device> devices) { while (_devices.isNotEmpty) { _removeDevice(_devices.first); } devices.forEach(addDevice); } bool discoverDevicesCalled = false; @override Future<List<Device>> discoverDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, }) { discoverDevicesCalled = true; return super.discoverDevices(timeout: timeout); } @override Stream<Device> get onAdded => _onAddedController.stream; @override Stream<Device> get onRemoved => _onRemovedController.stream; @override List<String> wellKnownIds = <String>[]; List<String> diagnostics = <String>[]; @override Future<List<String>> getDiagnostics() => Future<List<String>>.value(diagnostics); } /// A fake implementation of the [DeviceLogReader]. class FakeDeviceLogReader extends DeviceLogReader { @override String get name => 'FakeLogReader'; bool disposed = false; final List<String> _lineQueue = <String>[]; late final StreamController<String> _linesController = StreamController<String> .broadcast(onListen: () { _lineQueue.forEach(_linesController.add); _lineQueue.clear(); }); @override Stream<String> get logLines => _linesController.stream; void addLine(String line) { if (_linesController.hasListener) { _linesController.add(line); } else { _lineQueue.add(line); } } @override Future<void> dispose() async { _lineQueue.clear(); await _linesController.close(); disposed = true; } }
flutter/packages/flutter_tools/test/src/fake_devices.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/src/fake_devices.dart", "repo_id": "flutter", "token_count": 3055 }
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 'package:file/file.dart'; import 'package:vm_service/vm_service.dart'; import '../integration.shard/test_data/basic_project.dart'; import '../integration.shard/test_data/tests_project.dart'; import '../integration.shard/test_driver.dart'; import '../integration.shard/test_utils.dart'; import '../src/common.dart'; void main() { group('Flutter run for web', () { final BasicProject project = BasicProject(); late Directory tempDir; late FlutterRunTestDriver flutter; setUp(() async { tempDir = createResolvedTempDirectorySync('run_expression_eval_test.'); await project.setUpIn(tempDir); flutter = FlutterRunTestDriver(tempDir); flutter.stdout.listen((String line) { expect(line, isNot(contains('Unresolved uri:'))); expect(line, isNot(contains('No module for'))); }); }); tearDown(() async { await flutter.stop(); tryToDelete(tempDir); }); Future<void> start({required bool expressionEvaluation}) async { // The non-test project has a loop around its breakpoints. // No need to start paused as all breakpoint would be eventually reached. await flutter.run( withDebugger: true, chrome: true, expressionEvaluation: expressionEvaluation, additionalCommandArgs: <String>['--verbose', '--web-renderer=html']); } Future<void> breakInBuildMethod(FlutterTestDriver flutter) async { await flutter.breakAt( project.buildMethodBreakpointUri, project.buildMethodBreakpointLine, ); } Future<void> breakInTopLevelFunction(FlutterTestDriver flutter) async { await flutter.breakAt( project.topLevelFunctionBreakpointUri, project.topLevelFunctionBreakpointLine, ); } testWithoutContext('cannot evaluate expression if feature is disabled', () async { await start(expressionEvaluation: false); await breakInTopLevelFunction(flutter); await failToEvaluateExpression(flutter); }); testWithoutContext('shows no native javascript objects in static scope', () async { await start(expressionEvaluation: true); await breakInTopLevelFunction(flutter); await checkStaticScope(flutter); }); testWithoutContext('can handle compilation errors', () async { await start(expressionEvaluation: true); await breakInTopLevelFunction(flutter); await evaluateErrorExpressions(flutter); }); testWithoutContext('can evaluate trivial expressions in top level function', () async { await start(expressionEvaluation: true); await breakInTopLevelFunction(flutter); await evaluateTrivialExpressions(flutter); }); testWithoutContext('can evaluate trivial expressions in build method', () async { await start(expressionEvaluation: true); await breakInBuildMethod(flutter); await evaluateTrivialExpressions(flutter); }); testWithoutContext('can evaluate complex expressions in top level function', () async { await start(expressionEvaluation: true); await breakInTopLevelFunction(flutter); await evaluateComplexExpressions(flutter); }); testWithoutContext('can evaluate complex expressions in build method', () async { await start(expressionEvaluation: true); await breakInBuildMethod(flutter); await evaluateComplexExpressions(flutter); }); testWithoutContext('can evaluate trivial expressions in library without pause', () async { await start(expressionEvaluation: true); await evaluateTrivialExpressionsInLibrary(flutter); }); testWithoutContext('can evaluate complex expressions in library without pause', () async { await start(expressionEvaluation: true); await evaluateComplexExpressionsInLibrary(flutter); }); testWithoutContext('evaluated expression includes web library environment defines', () async { await start(expressionEvaluation: true); await evaluateWebLibraryBooleanFromEnvironmentInLibrary(flutter); }); }); group('Flutter test for web', () { final TestsProject project = TestsProject(); late Directory tempDir; late FlutterRunTestDriver flutter; setUp(() async { tempDir = createResolvedTempDirectorySync('run_expression_eval_test.'); await project.setUpIn(tempDir); flutter = FlutterRunTestDriver(tempDir); }); tearDown(() async { await flutter.stop(); tryToDelete(tempDir); }); Future<Isolate?> breakInMethod(FlutterTestDriver flutter) async { await flutter.addBreakpoint( project.breakpointAppUri, project.breakpointLine, ); return flutter.resume(waitForNextPause: true); } Future<void> startPaused({required bool expressionEvaluation}) { // The test project does not have a loop around its breakpoints. // Start paused so we can set a breakpoint before passing it // in the execution. return flutter.run( withDebugger: true, chrome: true, expressionEvaluation: expressionEvaluation, startPaused: true, script: project.testFilePath, additionalCommandArgs: <String>['--verbose', '--web-renderer=html']); } testWithoutContext('cannot evaluate expressions if feature is disabled', () async { await startPaused(expressionEvaluation: false); await breakInMethod(flutter); await failToEvaluateExpression(flutter); }); testWithoutContext('can evaluate trivial expressions in a test', () async { await startPaused(expressionEvaluation: true); await breakInMethod(flutter); await evaluateTrivialExpressions(flutter); }); testWithoutContext('can evaluate complex expressions in a test', () async { await startPaused(expressionEvaluation: true); await breakInMethod(flutter); await evaluateComplexExpressions(flutter); }); testWithoutContext('can evaluate trivial expressions in library without pause', () async { await startPaused(expressionEvaluation: true); await evaluateTrivialExpressionsInLibrary(flutter); }); testWithoutContext('can evaluate complex expressions in library without pause', () async { await startPaused(expressionEvaluation: true); await evaluateComplexExpressionsInLibrary(flutter); }); testWithoutContext('evaluated expression includes web library environment defines', () async { await startPaused(expressionEvaluation: true); await evaluateWebLibraryBooleanFromEnvironmentInLibrary(flutter); }); }); } Future<void> failToEvaluateExpression(FlutterTestDriver flutter) async { await expectLater( flutter.evaluateInFrame('"test"'), throwsA(isA<RPCError>().having( (RPCError error) => error.message, 'message', contains('Expression evaluation is not supported for this configuration'), )), ); } Future<void> checkStaticScope(FlutterTestDriver flutter) async { final Frame res = await flutter.getTopStackFrame(); expect(res.vars, equals(<BoundVariable>[])); } Future<void> evaluateErrorExpressions(FlutterTestDriver flutter) async { final ObjRef res = await flutter.evaluateInFrame('typo'); expectError(res, 'CompilationError:'); } Future<void> evaluateTrivialExpressions(FlutterTestDriver flutter) async { ObjRef res; res = await flutter.evaluateInFrame('"test"'); expectInstance(res, InstanceKind.kString, 'test'); res = await flutter.evaluateInFrame('1'); expectInstance(res, InstanceKind.kDouble, 1.toString()); res = await flutter.evaluateInFrame('true'); expectInstance(res, InstanceKind.kBool, true.toString()); } Future<void> evaluateComplexExpressions(FlutterTestDriver flutter) async { final ObjRef res = await flutter.evaluateInFrame('new DateTime.now().year'); expectInstance(res, InstanceKind.kDouble, DateTime.now().year.toString()); } Future<void> evaluateTrivialExpressionsInLibrary(FlutterTestDriver flutter) async { final LibraryRef library = await getRootLibrary(flutter); final ObjRef res = await flutter.evaluate(library.id!, '"test"'); expectInstance(res, InstanceKind.kString, 'test'); } Future<void> evaluateComplexExpressionsInLibrary(FlutterTestDriver flutter) async { final LibraryRef library = await getRootLibrary(flutter); final ObjRef res = await flutter.evaluate(library.id!, 'new DateTime.now().year'); expectInstance(res, InstanceKind.kDouble, DateTime.now().year.toString()); } Future<void> evaluateWebLibraryBooleanFromEnvironmentInLibrary(FlutterTestDriver flutter) async { final LibraryRef library = await getRootLibrary(flutter); final ObjRef res = await flutter.evaluate(library.id!, 'const bool.fromEnvironment("dart.library.html")'); expectInstance(res, InstanceKind.kBool, true.toString()); } Future<LibraryRef> getRootLibrary(FlutterTestDriver flutter) async { // `isolate.rootLib` returns incorrect library, so find the // entrypoint manually here instead. // // Issue: https://github.com/dart-lang/sdk/issues/44760 final Isolate isolate = await flutter.getFlutterIsolate(); return isolate.libraries! .firstWhere((LibraryRef l) => l.uri!.contains('org-dartlang-app')); } void expectInstance(ObjRef result, String kind, String message) { expect(result, const TypeMatcher<InstanceRef>() .having((InstanceRef instance) => instance.kind, 'kind', kind) .having((InstanceRef instance) => instance.valueAsString, 'valueAsString', message)); } void expectError(ObjRef result, String message) { expect(result, const TypeMatcher<ErrorRef>() .having((ErrorRef instance) => instance.message, 'message', contains(message))); }
flutter/packages/flutter_tools/test/web.shard/expression_evaluation_web_test.dart/0
{ "file_path": "flutter/packages/flutter_tools/test/web.shard/expression_evaluation_web_test.dart", "repo_id": "flutter", "token_count": 3201 }
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. import 'dart:async'; import 'package:flutter/services.dart'; import 'plugin_registry.dart'; /// A named channel for sending events to the framework-side using streams. /// /// This is the platform-side equivalent of [EventChannel]. Whereas /// [EventChannel] receives a stream of events from platform plugins, this /// channel sends a stream of events to the handler listening on the /// framework-side. /// /// If no [codec] is provided, then [StandardMethodCodec] is used. If no /// [binaryMessenger] is provided, then [pluginBinaryMessenger], which sends /// messages to the framework-side, is used. /// /// Channels created using this class implement two methods for /// subscribing to the event stream. The methods use the encoding of /// the specified [codec]. /// /// The first method is `listen`. When called, it begins forwarding /// messages to the framework side when they are added to the /// `controller`. This triggers the [StreamController.onListen] callback /// on the `controller`. /// /// The other method is `cancel`. When called, it stops forwarding /// events to the framework. This triggers the [StreamController.onCancel] /// callback on the `controller`. /// /// Events added to the `controller` when the framework is not /// subscribed are silently discarded. class PluginEventChannel<T> { /// Creates a new plugin event channel. const PluginEventChannel( this.name, [ this.codec = const StandardMethodCodec(), this.binaryMessenger, ]); /// The logical channel on which communication happens. final String name; /// The message codec used by this channel. /// /// Defaults to [StandardMethodCodec]. final MethodCodec codec; /// The messenger used by this channel to send platform messages. /// /// When this is null, the [pluginBinaryMessenger] is used instead, /// which sends messages from the platform-side to the /// framework-side. final BinaryMessenger? binaryMessenger; /// Use [setController] instead. /// /// This setter is deprecated because it has no corresponding getter, /// and providing a getter would require making this class non-const. @Deprecated( 'Replace calls to the "controller" setter with calls to the "setController" method. ' 'This feature was deprecated after v1.23.0-7.0.pre.' ) set controller(StreamController<T> controller) { // ignore: avoid_setters_without_getters setController(controller); } /// Changes the stream controller for this event channel. /// /// Setting the controller to null disconnects from the channel (setting /// the message handler on the [binaryMessenger] to null). void setController(StreamController<T>? controller) { final BinaryMessenger messenger = binaryMessenger ?? pluginBinaryMessenger; if (controller == null) { messenger.setMessageHandler(name, null); } else { // The handler object is kept alive via its handle() method // keeping a reference to itself. Ideally we would keep a // reference to it so that there was a clear ownership model, // but that would require making this class non-const. Having // this class be const is convenient since it allows references // to be obtained by using the constructor rather than having // to literally pass references around. final _EventChannelHandler<T> handler = _EventChannelHandler<T>( name, codec, controller, messenger, ); messenger.setMessageHandler(name, handler.handle); } } } class _EventChannelHandler<T> { _EventChannelHandler( this.name, this.codec, this.controller, this.messenger, ); final String name; final MethodCodec codec; final StreamController<T> controller; final BinaryMessenger messenger; StreamSubscription<T>? subscription; Future<ByteData>? handle(ByteData? message) { final MethodCall call = codec.decodeMethodCall(message); switch (call.method) { case 'listen': assert(call.arguments == null); return _listen(); case 'cancel': assert(call.arguments == null); return _cancel(); } return null; } Future<ByteData> _listen() async { // Cancel any existing subscription. await subscription?.cancel(); subscription = controller.stream.listen((dynamic event) { messenger.send(name, codec.encodeSuccessEnvelope(event)); }, onError: (dynamic error) { messenger.send(name, codec.encodeErrorEnvelope(code: 'error', message: '$error')); }); return codec.encodeSuccessEnvelope(null); } Future<ByteData> _cancel() async { if (subscription == null) { return codec.encodeErrorEnvelope( code: 'error', message: 'No active subscription to cancel.', ); } await subscription!.cancel(); subscription = null; return codec.encodeSuccessEnvelope(null); } }
flutter/packages/flutter_web_plugins/lib/src/plugin_event_channel.dart/0
{ "file_path": "flutter/packages/flutter_web_plugins/lib/src/plugin_event_channel.dart", "repo_id": "flutter", "token_count": 1529 }
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. import 'dart:io' show ProcessResult; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../common/logging.dart'; import '../common/network.dart'; /// An error raised when a command fails to run within the [SshCommandRunner]. /// /// This occurs for both connection failures, and for failure to /// run the command on the remote device. This error is raised when the /// subprocess running the SSH command returns a nonzero exit code. class SshCommandError extends Error { /// Basic constructor outlining the reason for the SSH command failure through /// the message string. SshCommandError(this.message); /// The reason for the command failure. final String message; @override String toString() { return '$SshCommandError: $message\n${super.stackTrace}'; } } /// Runs commands remotely on a Fuchsia device. /// /// Requires a Fuchsia root and build type (to load the ssh config), /// and the address of the Fuchsia device. class SshCommandRunner { /// Instantiates the command runner, pointing to an `address` as well as /// an optional SSH config file path. /// /// If the SSH config path is supplied as an empty string, behavior is /// undefined. /// /// [ArgumentError] is thrown in the event that `address` is neither valid /// IPv4 nor IPv6. When connecting to a link local address (`fe80::` is /// usually at the start of the address), an interface should be supplied. SshCommandRunner({ required this.address, this.interface = '', this.sshConfigPath, }) : _processManager = const LocalProcessManager() { validateAddress(address); } /// Private constructor for dependency injection of the process manager. @visibleForTesting SshCommandRunner.withProcessManager( this._processManager, { required this.address, this.interface = '', this.sshConfigPath, }) { validateAddress(address); } final Logger _log = Logger('SshCommandRunner'); final ProcessManager _processManager; /// The IPv4 address to access the Fuchsia machine over SSH. final String address; /// The path to the SSH config (optional). final String? sshConfigPath; /// The name of the machine's network interface (for use with IPv6 /// connections. Ignored otherwise). final String interface; /// Runs a command on a Fuchsia device through an SSH tunnel. /// /// If the subprocess creating the SSH tunnel returns a nonzero exit status, /// then an [SshCommandError] is raised. Future<List<String>> run(String command) async { final List<String> args = <String>[ 'ssh', if (sshConfigPath != null) ...<String>['-F', sshConfigPath!], if (isIpV6Address(address)) ...<String>['-6', if (interface.isEmpty) address else '$address%$interface'] else address, command, ]; _log.fine('Running command through SSH: ${args.join(' ')}'); final ProcessResult result = await _processManager.run(args); if (result.exitCode != 0) { throw SshCommandError( 'Command failed: $command\nstdout: ${result.stdout}\nstderr: ${result.stderr}'); } _log.fine('SSH command stdout in brackets:[${result.stdout}]'); return (result.stdout as String).split('\n'); } }
flutter/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart/0
{ "file_path": "flutter/packages/fuchsia_remote_debug_protocol/lib/src/runners/ssh_command_runner.dart", "repo_id": "flutter", "token_count": 1047 }
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. package dev.flutter.plugins.integration_test; import android.util.Log; import androidx.test.rule.ActivityTestRule; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.concurrent.ExecutionException; import org.junit.Rule; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runner.Runner; import org.junit.runner.notification.Failure; import org.junit.runner.notification.RunNotifier; public class FlutterTestRunner extends Runner { private static final String TAG = "FlutterTestRunner"; final Class<?> testClass; TestRule rule = null; public FlutterTestRunner(Class<?> testClass) { super(); this.testClass = testClass; // Look for an `ActivityTestRule` annotated `@Rule` and invoke `launchActivity()` Field[] fields = testClass.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Rule.class)) { try { Object instance = testClass.getDeclaredConstructor().newInstance(); if (field.get(instance) instanceof ActivityTestRule) { rule = (TestRule) field.get(instance); break; } } catch (InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException("Unable to contruct " + testClass.getName() + " object for testing"); } catch (InstantiationException | IllegalAccessException e) { // This might occur if the developer did not make the rule public. // We could call field.setAccessible(true) but it seems better to throw. throw new RuntimeException("Unable to access activity rule", e); } } } } @Override public Description getDescription() { return Description.createTestDescription(testClass, "Flutter Tests"); } @Override public void run(RunNotifier notifier) { if (rule == null) { throw new RuntimeException("Unable to run tests due to missing activity rule"); } try { if (rule instanceof ActivityTestRule) { ((ActivityTestRule) rule).launchActivity(null); } } catch (RuntimeException e) { Log.v(TAG, "launchActivity failed, possibly because the activity was already running. " + e); Log.v( TAG, "Try disabling auto-launch of the activity, e.g. ActivityTestRule<>(MainActivity.class, true, false);"); } Map<String, String> results = null; try { results = IntegrationTestPlugin.testResults.get(); } catch (ExecutionException | InterruptedException e) { throw new IllegalThreadStateException("Unable to get test results"); } for (String name : results.keySet()) { Description d = Description.createTestDescription(testClass, name); notifier.fireTestStarted(d); String outcome = results.get(name); if (!outcome.equals("success")) { Exception dummyException = new Exception(outcome); notifier.fireTestFailure(new Failure(d, dummyException)); } notifier.fireTestFinished(d); } } }
flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterTestRunner.java/0
{ "file_path": "flutter/packages/integration_test/android/src/main/java/dev/flutter/plugins/integration_test/FlutterTestRunner.java", "repo_id": "flutter", "token_count": 1114 }
799
// 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 "IntegrationTestIosTest.h" #import "IntegrationTestPlugin.h" #import "FLTIntegrationTestRunner.h" #pragma mark - Deprecated #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-implementations" @implementation IntegrationTestIosTest - (BOOL)testIntegrationTest:(NSString **)testResult { NSLog(@"==================== Test Results ====================="); NSMutableArray<NSString *> *failedTests = [NSMutableArray array]; NSMutableArray<NSString *> *testNames = [NSMutableArray array]; [[FLTIntegrationTestRunner new] testIntegrationTestWithResults:^(SEL testSelector, BOOL success, NSString *message) { NSString *testName = NSStringFromSelector(testSelector); [testNames addObject:testName]; if (success) { NSLog(@"%@ passed.", testName); } else { NSLog(@"%@ failed: %@", testName, message); [failedTests addObject:testName]; } }]; NSLog(@"================== Test Results End ===================="); BOOL testPass = failedTests.count == 0; if (!testPass && testResult != NULL) { *testResult = [NSString stringWithFormat:@"Detected failed integration test(s) %@ among %@", failedTests.description, testNames.description]; } return testPass; } @end #pragma clang diagnostic pop
flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.m/0
{ "file_path": "flutter/packages/integration_test/ios/Classes/IntegrationTestIosTest.m", "repo_id": "flutter", "token_count": 514 }
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. import 'package:flutter/services.dart'; /// The method channel used to report the result of the tests to the platform. /// On Android, this is relevant when running instrumented tests. const MethodChannel integrationTestChannel = MethodChannel('plugins.flutter.io/integration_test');
flutter/packages/integration_test/lib/src/channel.dart/0
{ "file_path": "flutter/packages/integration_test/lib/src/channel.dart", "repo_id": "flutter", "token_count": 110 }
801
# Analog Clock This app is an example of an analog clock. It has a light theme and a dark theme, and displays sample weather and location data. <img src='analog.gif' width='350'> <img src='analog_dark.png' width='350'> <img src='analog_light.png' width='350'>
flutter_clock/analog_clock/README.md/0
{ "file_path": "flutter_clock/analog_clock/README.md", "repo_id": "flutter_clock", "token_count": 84 }
802
## [0.0.1] - TODO: Add release date. * TODO: Describe initial release.
flutter_clock/flutter_clock_helper/CHANGELOG.md/0
{ "file_path": "flutter_clock/flutter_clock_helper/CHANGELOG.md", "repo_id": "flutter_clock", "token_count": 28 }
803
## Development <details> <summary>Generating localizations</summary> If this is the first time building the Flutter Gallery, the localized code will not be present in the project directory. However, after running the application for the first time, a synthetic package will be generated containing the app's localizations through importing `package:flutter_gen/gen_l10n/`. ```bash flutter pub get flutter pub run grinder l10n ``` See separate [README](lib/l10n/README.md) for more details. </details> <details> <summary>Generating highlighted code segments</summary> ```bash flutter pub get flutter pub run grinder update-code-segments ``` See separate [README](tool/codeviewer_cli/README.md) for more details. </details> <details> <summary>Including a new splash animation</summary> 1. Convert your animation to a `.gif` file. Ideally, use a background color of `0xFF030303` to ensure the animation blends into the background of the app. 2. Add your new `.gif` file to the assets directory under `assets/splash_effects`. Ensure the name follows the format `splash_effect_$num.gif`. The number should be the next number after the current largest number in the repository. 3. Update the map `_effectDurations` in [splash.dart](lib/pages/splash.dart) to include the number of the new `.gif` as well as its estimated duration. The duration is used to determine how long to display the splash animation at launch. </details> ## Releasing *must be a `flutter-hackers` member* A set of GitHub workflows are available to help with releasing the Flutter Gallery, one per releasing platform. 1. For Android, download the relevant [Firebase configuration file](https://firebase.corp.google.com/u/0/project/gallery-flutter-dev/settings/general) (e.g. `google-services.json`). 1. Bump the `pubspec.yaml` version number. This can be in a PR making a change or a separate PR. Use [semantic versioning](https://semver.org/) to determine which part to increment. **The version number after the `+` should also be incremented**. For example `1.2.3+010203` with a patch should become `1.2.4+010204`. 1. Run GitHub workflow. - [Deploy to web](https://github.com/flutter/gallery/actions/workflows/release_deploy_web.yml): Deploys a web build to the Firebase-hosted [staging](https://gallery-flutter-staging.web.app) or [production](https://gallery.flutter.dev) site. - [Deploy to Play Store](https://github.com/flutter/gallery/actions/workflows/release_deploy_play_store.yml): Uses Fastlane to create a [beta](https://play.google.com/console/u/0/developers/7661132837216938445/app/4974617875198505129/tracks/open-testing) (freely available on the [Play Store](https://play.google.com/apps/testing/io.flutter.demo.gallery)) or promote an existing beta to [production](https://play.google.com/console/u/0/developers/7661132837216938445/app/4974617875198505129/tracks/production) ([Play Store](https://play.google.com/store/apps/details?id=io.flutter.demo.gallery)). > **Note** > Once an .aab is created with a particular version number, it can't be replaced. The pubspec version number must be incremented again. - [Draft GitHub release](https://github.com/flutter/gallery/actions/workflows/release_draft_github_release.yml): Drafts a GitHub release, including packaged builds for Android, macOS, Linux, and Windows. Release notes can be automatically generated. The release draft is private until published. Upon being published, the specified version tag will be created. - [Publish on Windows Store](): Releasing to the Windows Store. > **Note** > This repository is not currently set up to publish new versions of [the current Windows Store listing](https://www.microsoft.com/store/productId/9PDWCTDFC7QQ). Requires running `msstore init` within the repository and setting repository/environment secrets . > See the instructions in the [documentation](https://docs.flutter.dev/deployment/windows#github-actions-cicd) for more information. <details> <summary>Escape hatch</summary> If the above GitHub workflows aren't functional (#759), releasing can be done semi-manually. Since this requires obtaining environment secrets, this can only be done by a Googler. See go/flutter-gallery-manual-deployment. </details> ## Tests The gallery has its own set of unit, golden, and integration tests. In addition, Flutter itself uses the gallery in tests. To enable breaking changes, the gallery version is pinned in two places: - `flutter analyze`: https://github.com/flutter/tests/blob/master/registry/flutter_gallery.test - DeviceLab tests: https://github.com/flutter/flutter/blob/master/dev/devicelab/lib/versions/gallery.dart [latest release]: https://github.com/flutter/gallery/releases/latest
gallery/DEVELOPING.md/0
{ "file_path": "gallery/DEVELOPING.md", "repo_id": "gallery", "token_count": 1371 }
804
{ "hosting": [ { "site": "flutter-gallery-archive", "public": "build/web", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] }, { "site": "gallery-flutter-dev", "public": "build/web", "redirects": [ { "source": "/", "destination": "https://docs.flutter.dev/gallery", "type": 301 } ], "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] } ] }
gallery/firebase.json/0
{ "file_path": "gallery/firebase.json", "repo_id": "gallery", "token_count": 308 }
805
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM"> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="EHf-IW-A2E"> <objects> <viewController id="01J-lp-oVM" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/> <viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3"> <rect key="frame" x="0.0" y="0.0" width="414" height="896"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4"> <rect key="frame" x="207" y="448" width="0.5" height="0.5"/> </imageView> </subviews> <color key="backgroundColor" red="0.011764705882352941" green="0.011764705882352941" blue="0.011764705882352941" alpha="1" colorSpace="calibratedRGB"/> <constraints> <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/> <constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/> </constraints> </view> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="76.811594202898561" y="251.11607142857142"/> </scene> </scenes> <resources> <image name="LaunchImage" width="0.5" height="0.5"/> </resources> </document>
gallery/ios/Runner/Base.lproj/LaunchScreen.storyboard/0
{ "file_path": "gallery/ios/Runner/Base.lproj/LaunchScreen.storyboard", "repo_id": "gallery", "token_count": 1300 }
806
// 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'; import 'package:gallery/data/gallery_options.dart'; import 'package:gallery/demos/cupertino/demo_types.dart'; // BEGIN cupertinoAlertDemo class CupertinoAlertDemo extends StatefulWidget { const CupertinoAlertDemo({ super.key, required this.type, }); final AlertDemoType type; @override State<CupertinoAlertDemo> createState() => _CupertinoAlertDemoState(); } class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> with RestorationMixin { RestorableStringN lastSelectedValue = RestorableStringN(null); late RestorableRouteFuture<String> _alertDialogRoute; late RestorableRouteFuture<String> _alertWithTitleDialogRoute; late RestorableRouteFuture<String> _alertWithButtonsDialogRoute; late RestorableRouteFuture<String> _alertWithButtonsOnlyDialogRoute; late RestorableRouteFuture<String> _modalPopupRoute; @override String get restorationId => 'cupertino_alert_demo'; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration( lastSelectedValue, 'last_selected_value', ); registerForRestoration( _alertDialogRoute, 'alert_demo_dialog_route', ); registerForRestoration( _alertWithTitleDialogRoute, 'alert_with_title_press_demo_dialog_route', ); registerForRestoration( _alertWithButtonsDialogRoute, 'alert_with_title_press_demo_dialog_route', ); registerForRestoration( _alertWithButtonsOnlyDialogRoute, 'alert_with_title_press_demo_dialog_route', ); registerForRestoration( _modalPopupRoute, 'modal_popup_route', ); } void _setSelectedValue(String value) { setState(() { lastSelectedValue.value = value; }); } @override void initState() { super.initState(); _alertDialogRoute = RestorableRouteFuture<String>( onPresent: (navigator, arguments) { return navigator.restorablePush(_alertDemoDialog); }, onComplete: _setSelectedValue, ); _alertWithTitleDialogRoute = RestorableRouteFuture<String>( onPresent: (navigator, arguments) { return navigator.restorablePush(_alertWithTitleDialog); }, onComplete: _setSelectedValue, ); _alertWithButtonsDialogRoute = RestorableRouteFuture<String>( onPresent: (navigator, arguments) { return navigator.restorablePush(_alertWithButtonsDialog); }, onComplete: _setSelectedValue, ); _alertWithButtonsOnlyDialogRoute = RestorableRouteFuture<String>( onPresent: (navigator, arguments) { return navigator.restorablePush(_alertWithButtonsOnlyDialog); }, onComplete: _setSelectedValue, ); _modalPopupRoute = RestorableRouteFuture<String>( onPresent: (navigator, arguments) { return navigator.restorablePush(_modalRoute); }, onComplete: _setSelectedValue, ); } String _title(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; switch (widget.type) { case AlertDemoType.alert: return localizations.demoCupertinoAlertTitle; case AlertDemoType.alertTitle: return localizations.demoCupertinoAlertWithTitleTitle; case AlertDemoType.alertButtons: return localizations.demoCupertinoAlertButtonsTitle; case AlertDemoType.alertButtonsOnly: return localizations.demoCupertinoAlertButtonsOnlyTitle; case AlertDemoType.actionSheet: return localizations.demoCupertinoActionSheetTitle; } } static Route<String> _alertDemoDialog( BuildContext context, Object? arguments, ) { final localizations = GalleryLocalizations.of(context)!; return CupertinoDialogRoute<String>( context: context, builder: (context) => ApplyTextOptions( child: CupertinoAlertDialog( title: Text(localizations.dialogDiscardTitle), actions: [ CupertinoDialogAction( isDestructiveAction: true, onPressed: () { Navigator.of( context, ).pop(localizations.cupertinoAlertDiscard); }, child: Text( localizations.cupertinoAlertDiscard, ), ), CupertinoDialogAction( isDefaultAction: true, onPressed: () => Navigator.of( context, ).pop( localizations.cupertinoAlertCancel, ), child: Text( localizations.cupertinoAlertCancel, ), ), ], ), ), ); } static Route<String> _alertWithTitleDialog( BuildContext context, Object? arguments, ) { final localizations = GalleryLocalizations.of(context)!; return CupertinoDialogRoute<String>( context: context, builder: (context) => ApplyTextOptions( child: CupertinoAlertDialog( title: Text( localizations.cupertinoAlertLocationTitle, ), content: Text( localizations.cupertinoAlertLocationDescription, ), actions: [ CupertinoDialogAction( onPressed: () => Navigator.of( context, ).pop( localizations.cupertinoAlertDontAllow, ), child: Text( localizations.cupertinoAlertDontAllow, ), ), CupertinoDialogAction( onPressed: () => Navigator.of( context, ).pop( localizations.cupertinoAlertAllow, ), child: Text( localizations.cupertinoAlertAllow, ), ), ], ), ), ); } static Route<String> _alertWithButtonsDialog( BuildContext context, Object? arguments, ) { final localizations = GalleryLocalizations.of(context)!; return CupertinoDialogRoute<String>( context: context, builder: (context) => ApplyTextOptions( child: CupertinoDessertDialog( title: Text( localizations.cupertinoAlertFavoriteDessert, ), content: Text( localizations.cupertinoAlertDessertDescription, ), ), ), ); } static Route<String> _alertWithButtonsOnlyDialog( BuildContext context, Object? arguments, ) { return CupertinoDialogRoute<String>( context: context, builder: (context) => const ApplyTextOptions( child: CupertinoDessertDialog(), ), ); } static Route<String> _modalRoute( BuildContext context, Object? arguments, ) { final localizations = GalleryLocalizations.of(context)!; return CupertinoModalPopupRoute<String>( builder: (context) => ApplyTextOptions( child: CupertinoActionSheet( title: Text( localizations.cupertinoAlertFavoriteDessert, ), message: Text( localizations.cupertinoAlertDessertDescription, ), actions: [ CupertinoActionSheetAction( onPressed: () => Navigator.of( context, ).pop( localizations.cupertinoAlertCheesecake, ), child: Text( localizations.cupertinoAlertCheesecake, ), ), CupertinoActionSheetAction( onPressed: () => Navigator.of( context, ).pop( localizations.cupertinoAlertTiramisu, ), child: Text( localizations.cupertinoAlertTiramisu, ), ), CupertinoActionSheetAction( onPressed: () => Navigator.of( context, ).pop( localizations.cupertinoAlertApplePie, ), child: Text( localizations.cupertinoAlertApplePie, ), ), ], cancelButton: CupertinoActionSheetAction( isDefaultAction: true, onPressed: () => Navigator.of( context, ).pop( localizations.cupertinoAlertCancel, ), child: Text( localizations.cupertinoAlertCancel, ), ), ), ), ); } @override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: CupertinoNavigationBar( automaticallyImplyLeading: false, middle: Text(_title(context)), ), child: Builder( builder: (context) { return Column( children: [ Expanded( child: Center( child: CupertinoButton.filled( onPressed: () { switch (widget.type) { case AlertDemoType.alert: _alertDialogRoute.present(); break; case AlertDemoType.alertTitle: _alertWithTitleDialogRoute.present(); break; case AlertDemoType.alertButtons: _alertWithButtonsDialogRoute.present(); break; case AlertDemoType.alertButtonsOnly: _alertWithButtonsOnlyDialogRoute.present(); break; case AlertDemoType.actionSheet: _modalPopupRoute.present(); break; } }, child: Text( GalleryLocalizations.of(context)!.cupertinoShowAlert, ), ), ), ), if (lastSelectedValue.value != null) Padding( padding: const EdgeInsets.all(16), child: Text( GalleryLocalizations.of(context)! .dialogSelectedOption(lastSelectedValue.value!), style: CupertinoTheme.of(context).textTheme.textStyle, textAlign: TextAlign.center, ), ), ], ); }, ), ); } } class CupertinoDessertDialog extends StatelessWidget { const CupertinoDessertDialog({ super.key, this.title, this.content, }); final Widget? title; final Widget? content; @override Widget build(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; return CupertinoAlertDialog( title: title, content: content, actions: [ CupertinoDialogAction( onPressed: () { Navigator.of( context, ).pop( localizations.cupertinoAlertCheesecake, ); }, child: Text( localizations.cupertinoAlertCheesecake, ), ), CupertinoDialogAction( onPressed: () { Navigator.of( context, ).pop( localizations.cupertinoAlertTiramisu, ); }, child: Text( localizations.cupertinoAlertTiramisu, ), ), CupertinoDialogAction( onPressed: () { Navigator.of( context, ).pop( localizations.cupertinoAlertApplePie, ); }, child: Text( localizations.cupertinoAlertApplePie, ), ), CupertinoDialogAction( onPressed: () { Navigator.of( context, ).pop( localizations.cupertinoAlertChocolateBrownie, ); }, child: Text( localizations.cupertinoAlertChocolateBrownie, ), ), CupertinoDialogAction( isDestructiveAction: true, onPressed: () { Navigator.of( context, ).pop( localizations.cupertinoAlertCancel, ); }, child: Text( localizations.cupertinoAlertCancel, ), ), ], ); } } // END
gallery/lib/demos/cupertino/cupertino_alert_demo.dart/0
{ "file_path": "gallery/lib/demos/cupertino/cupertino_alert_demo.dart", "repo_id": "gallery", "token_count": 6308 }
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. import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_gen/gen_l10n/gallery_localizations.dart'; // BEGIN bottomAppBarDemo class BottomAppBarDemo extends StatefulWidget { const BottomAppBarDemo({super.key}); @override State createState() => _BottomAppBarDemoState(); } class _BottomAppBarDemoState extends State<BottomAppBarDemo> with RestorationMixin { final RestorableBool _showFab = RestorableBool(true); final RestorableBool _showNotch = RestorableBool(true); final RestorableInt _currentFabLocation = RestorableInt(0); @override String get restorationId => 'bottom_app_bar_demo'; @override void restoreState(RestorationBucket? oldBucket, bool initialRestore) { registerForRestoration(_showFab, 'show_fab'); registerForRestoration(_showNotch, 'show_notch'); registerForRestoration(_currentFabLocation, 'fab_location'); } @override void dispose() { _showFab.dispose(); _showNotch.dispose(); _currentFabLocation.dispose(); super.dispose(); } // Since FloatingActionButtonLocation is not an enum, the index of the // selected FloatingActionButtonLocation is used for state restoration. static const List<FloatingActionButtonLocation> _fabLocations = [ FloatingActionButtonLocation.endDocked, FloatingActionButtonLocation.centerDocked, FloatingActionButtonLocation.endFloat, FloatingActionButtonLocation.centerFloat, ]; void _onShowNotchChanged(bool value) { setState(() { _showNotch.value = value; }); } void _onShowFabChanged(bool value) { setState(() { _showFab.value = value; }); } void _onFabLocationChanged(int? value) { setState(() { _currentFabLocation.value = value!; }); } @override Widget build(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text(localizations.demoBottomAppBarTitle), ), body: ListView( padding: const EdgeInsets.only(bottom: 88), children: [ SwitchListTile( title: Text( localizations.demoFloatingButtonTitle, ), value: _showFab.value, onChanged: _onShowFabChanged, ), SwitchListTile( title: Text(localizations.bottomAppBarNotch), value: _showNotch.value, onChanged: _onShowNotchChanged, ), Padding( padding: const EdgeInsets.all(16), child: Text(localizations.bottomAppBarPosition), ), RadioListTile<int>( title: Text( localizations.bottomAppBarPositionDockedEnd, ), value: 0, groupValue: _currentFabLocation.value, onChanged: _onFabLocationChanged, ), RadioListTile<int>( title: Text( localizations.bottomAppBarPositionDockedCenter, ), value: 1, groupValue: _currentFabLocation.value, onChanged: _onFabLocationChanged, ), RadioListTile<int>( title: Text( localizations.bottomAppBarPositionFloatingEnd, ), value: 2, groupValue: _currentFabLocation.value, onChanged: _onFabLocationChanged, ), RadioListTile<int>( title: Text( localizations.bottomAppBarPositionFloatingCenter, ), value: 3, groupValue: _currentFabLocation.value, onChanged: _onFabLocationChanged, ), ], ), floatingActionButton: _showFab.value ? Semantics( container: true, sortKey: const OrdinalSortKey(0), child: FloatingActionButton( onPressed: () {}, tooltip: localizations.buttonTextCreate, child: const Icon(Icons.add), ), ) : null, floatingActionButtonLocation: _fabLocations[_currentFabLocation.value], bottomNavigationBar: _DemoBottomAppBar( fabLocation: _fabLocations[_currentFabLocation.value], shape: _showNotch.value ? const CircularNotchedRectangle() : null, ), ); } } class _DemoBottomAppBar extends StatelessWidget { const _DemoBottomAppBar({ required this.fabLocation, this.shape, }); final FloatingActionButtonLocation fabLocation; final NotchedShape? shape; static final centerLocations = <FloatingActionButtonLocation>[ FloatingActionButtonLocation.centerDocked, FloatingActionButtonLocation.centerFloat, ]; @override Widget build(BuildContext context) { final localizations = GalleryLocalizations.of(context)!; return Semantics( sortKey: const OrdinalSortKey(1), container: true, label: localizations.bottomAppBar, child: BottomAppBar( shape: shape, child: IconTheme( data: IconThemeData(color: Theme.of(context).colorScheme.onPrimary), child: Row( children: [ IconButton( tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip, icon: const Icon(Icons.menu), onPressed: () {}, ), if (centerLocations.contains(fabLocation)) const Spacer(), IconButton( tooltip: localizations.starterAppTooltipSearch, icon: const Icon(Icons.search), onPressed: () {}, ), IconButton( tooltip: localizations.starterAppTooltipFavorite, icon: const Icon(Icons.favorite), onPressed: () {}, ) ], ), ), ), ); } } // END
gallery/lib/demos/material/bottom_app_bar_demo.dart/0
{ "file_path": "gallery/lib/demos/material/bottom_app_bar_demo.dart", "repo_id": "gallery", "token_count": 2651 }
808
{ "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": "প্ৰসংগ মেনুখন চাবলৈ ফ্লাটাৰ ল’গ’টোত হেঁচি ধৰি ৰাখক।", "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": "Aৰ পৰা Zলৈ", "demoSharedYAxisAlbumCount": "২৬৮ টা এলবাম", "demoSharedYAxisTitle": "শ্বেয়াৰ কৰা y অক্ষ", "demoSharedXAxisCreateAccountButtonText": "একাউণ্ট সৃষ্টি কৰক", "demoFadeScaleAlertDialogDiscardButton": "বাতিল কৰক", "demoSharedXAxisSignInTextFieldLabel": "ইমেইল অথবা ফ’ন নম্বৰ", "demoSharedXAxisSignInSubtitleText": "আপোনাৰ একাউণ্টৰ জৰিয়তে ছাইন ইন কৰক", "demoSharedXAxisSignInWelcomeText": "নমস্কাৰ ডেভিড পাৰ্ক", "demoSharedXAxisIndividualCourseSubtitle": "ব্যক্তিগতভাৱে প্ৰদশৰ্ন কৰা হয়", "demoSharedXAxisBundledCourseSubtitle": "বাণ্ডল হৈ থকা", "demoFadeThroughAlbumsDestination": "এলবাম", "demoSharedXAxisDesignCourseTitle": "ডিজাইন", "demoSharedXAxisIllustrationCourseTitle": "চিত্ৰসহ ব্যখ্যামূলক বৰ্ণনা", "demoSharedXAxisBusinessCourseTitle": "ব্যৱসায়", "demoSharedXAxisArtsAndCraftsCourseTitle": "কলা আৰু হস্তশিল্প", "demoMotionPlaceholderSubtitle": "গৌণ পাঠ", "demoFadeScaleAlertDialogCancelButton": "বাতিল কৰক", "demoFadeScaleAlertDialogHeader": "সতৰ্কতা সম্পৰ্কীয় ডায়লগ", "demoFadeScaleHideFabButton": "FAB লুকুৱাওক", "demoFadeScaleShowFabButton": "FAB দেখুৱাওক", "demoFadeScaleShowAlertDialogButton": "মডেল দেখুৱাওক", "demoFadeScaleDescription": "অনুজ্জ্বল আৰ্হিটো স্ক্ৰীনখনৰ মাজভাগত অনুজ্জ্বল হৈ পৰা এটা ডায়লগৰ দৰে স্ক্ৰীনৰ সীমাৰ ভিতৰত ওলোৱা সোমোৱা কৰা ইউআই উপাদানসমূহৰ বাবে ব্যৱহাৰ কৰা হয়।", "demoFadeScaleTitle": "অনুজ্জ্বল", "demoFadeThroughTextPlaceholder": "১২৩ খন ফট’", "demoFadeThroughSearchDestination": "Search", "demoFadeThroughPhotosDestination": "Photos", "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": "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": "এটা বস্তুৰ ডিজাইনৰ সময় বাছনি কৰোঁতা থকা কোনো ডায়ল'গ প্ৰদৰ্শন কৰে।", "demoPickersShowPicker": "বাছনি কৰোঁতা প্ৰদৰ্শন কৰক", "demoTabsScrollingTitle": "স্ক্ৰ’ল হোৱা", "demoTabsNonScrollingTitle": "স্ক্ৰ’ল নোহোৱা", "craneHours": "{hours,plural,=1{১ ঘ}other{{hours} ঘ}}", "craneMinutes": "{minutes,plural,=1{১ মি}other{{minutes} মি}}", "craneFlightDuration": "{hoursShortForm} {minutesShortForm}", "dataTableHeader": "পৰিপুষ্টি", "demoDatePickerTitle": "তাৰিখ বাছনি কৰোঁতা", "demoPickersSubtitle": "তাৰিখ আৰু সময়ৰ বাছনি", "demoPickersTitle": "বাছনি কৰোঁতাসকল", "demo2dTransformationsEditTooltip": "টাইল সম্পাদনা কৰক", "demoDataTableDescription": "ডেটাৰ তালিকাসমূহে শাৰী আৰু স্তম্ভবোৰৰ গ্ৰিডৰ দৰে এটা ফৰ্মেটত তথ্য প্ৰদৰ্শন কৰে। সেইবোৰে সহজে স্কেন কৰিব পৰাকৈ তথ্য সংগঠিত কৰে, যাতে ব্যৱহাৰকাৰীসকলে আৰ্হি আৰু অন্তৰ্দৃষ্টিসমূহ চাব পাৰে।", "demo2dTransformationsDescription": "টাইলসমূহ সম্পাদনা কৰিবলৈ টিপক আৰু দৃশ্যটো সকলোফালে চাবলৈ নিৰ্দেশসমূহ ব্যৱহাৰ কৰক। পেন কৰিবলৈ টানি আনি এৰক, জুম কৰিবলৈ পিঞ্চ কৰক, দুটা আঙুলিৰে ৰ’টেট কৰক। আৰম্ভণিৰ দিশটোলৈ উভতি যাবলৈ ৰিছেট বুটামটো টিপক।", "demo2dTransformationsSubtitle": "পেন, জুম, ৰ’টেট", "demo2dTransformationsTitle": "2D ৰূপান্তৰণসমূহ", "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": "তামিলনাডুত ফুৰিবলগীয়া শীৰ্ষৰ ১০ খন চহৰ", "cardsDemoTravelDestinationDescription1": "সংখ্যা ১০", "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": "Chat", "cupertinoTabBarHomeTab": "গৃহ", "demoCupertinoTabBarDescription": "এটা iOS-শৈলীৰ বুটাম নেভিগেশ্বন টেবৰ দণ্ড। একাধিক টেব প্ৰদর্শন কৰে, য'ত ডিফ'ল্ট হিচাপে প্ৰথম টেবটো সক্ৰিয় হৈ থাকে।", "demoCupertinoTabBarSubtitle": "iOS-শৈলীৰ বুটামৰ টেবৰ দণ্ড", "demoOptionsFeatureTitle": "বিকল্পসমূহ চাওক", "demoOptionsFeatureDescription": "এই ডেম’টোৰ বাবে উপলব্ধ বিকল্পসমূহ চাবলৈ ইয়াত টিপক।", "demoCodeViewerCopyAll": "সকলো প্ৰতিলিপি কৰক", "shrineScreenReaderRemoveProductButton": "{product} আঁতৰাওক", "shrineScreenReaderProductAddToCart": "কাৰ্টত যোগ কৰক", "shrineScreenReaderCart": "{quantity,plural,=0{শ্বপিং কাৰ্ট, কোনো বস্তু নাই}=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": "টাইপেই ১০১ স্কাইস্ক্ৰেপাৰ", "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": "Search", "demoTabsDescription": "টেবসমূহে সমলক বিভিন্ন স্ক্ৰীনসমূহত, ডেটা ছেটসমূহত আৰু অন্য ভাব-বিনিময়সমূহত সংগঠিত কৰে।", "demoTabsSubtitle": "স্বতন্ত্ৰভাৱে স্ক্ৰ’ল কৰিবপৰা ভিউসমূহৰ সৈতে টেবসমূহ", "demoTabsTitle": "টেবসমূহ", "rallyBudgetAmount": "{budgetName}ৰ {amountTotal}ৰ ভিতৰত {amountUsed} ব্যৱহাৰ কৰা হৈছে, {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{আপোনাৰ সম্ভাব্য কৰ কটাৰ পৰিমাণ বৃদ্ধি কৰক! ১ টা আবণ্টন নকৰা লেনদেনত শিতানসমূহ আবণ্টন কৰক।}other{আপোনাৰ সম্ভাব্য কৰ কটাৰ পৰিমাণ বৃদ্ধি কৰক! {count} টা আবণ্টন নকৰা লেনদেনত শিতানসমূহ আবণ্টন কৰক।}}", "craneFormTime": "সময় বাছনি কৰক", "craneFormLocation": "অৱস্থান বাছনি কৰক", "craneFormTravelers": "ভ্ৰমণকাৰীসকল", "craneEat8": "আটলাণ্টা, মাৰ্কিন যুক্তৰাষ্ট্ৰ", "craneFormDestination": "গন্তব্যস্থান বাছনি কৰক", "craneFormDates": "তাৰিখবোৰ বাছনি কৰক", "craneFly": "উৰণ", "craneSleep": "টোপনি", "craneEat": "খোৱা", "craneFlySubhead": "গন্তব্যস্থানৰ অনুসৰি ফ্লাইটবোৰ অন্বেষণ কৰক", "craneSleepSubhead": "গন্তব্যস্থান অনুসৰি সম্পত্তিসমূহ অন্বেষণ কৰক", "craneEatSubhead": "গন্তব্যস্থান অনুসৰি ৰেষ্টুৰেণ্টসমূহ অন্বেষণ কৰক", "craneFlyStops": "{numberOfStops,plural,=0{কোনো আস্থান নাই}=1{১ টা আস্থান}other{{numberOfStops} টা আস্থান}}", "craneSleepProperties": "{totalProperties,plural,=0{কোনো উপলব্ধ সম্পত্তি নাই}=1{১ টা উপলব্ধ সম্পত্তি}other{{totalProperties} টা উপলব্ধ সম্পত্তি}}", "craneEatRestaurants": "{totalRestaurants,plural,=0{কোনো ৰেষ্টুৰেণ্ট নাই}=1{১ খন ৰেষ্টুৰেণ্ট}other{{totalRestaurants} খন ৰেষ্টুৰেণ্ট}}", "craneFly0": "এছপেন, মার্কিন যুক্তৰাষ্ট্ৰ", "demoCupertinoSegmentedControlSubtitle": "iOS-শৈলীৰ বিভাজিত নিয়ন্ত্ৰণ", "craneSleep10": "কাইৰ', ঈজিপ্ত", "craneEat9": "মাদ্ৰিদ, স্পেইন", "craneFly1": "বিগ ছুৰ, মাৰ্কিন যুক্তৰাষ্ট্ৰ", "craneEat7": "নাশ্বভিল্লে, মার্কিন যুক্তৰাষ্ট্ৰ", "craneEat6": "ছিট্টেল, আমেৰিকা যুক্তৰাষ্ট্ৰ", "craneFly8": "ছিংগাপুৰ", "craneEat4": "পেৰিছ, ফ্ৰান্স", "craneEat3": "পৰ্টলেণ্ড, মাৰ্কিন যুক্তৰাষ্ট্ৰ", "craneEat2": "কৰড'বা, আর্জেণ্টিনা", "craneEat1": "ডাল্লাছ, মার্কিন যুক্তৰাষ্ট্ৰ", "craneEat0": "নেপলচ, ইটালী", "craneSleep11": "তাইপেই, তাইৱান", "craneSleep3": "হানাভা, কিউবা", "shrineLogoutButtonCaption": "লগ আউট কৰক", "rallyTitleBills": "বিলসমূহ", "rallyTitleAccounts": "একাউণ্টসমূহ", "shrineProductVagabondSack": "Vagabond sack", "rallyAccountDetailDataInterestYtd": "সুদ YTD", "shrineProductWhitneyBelt": "Whitney belt", "shrineProductGardenStrand": "Garden strand", "shrineProductStrutEarrings": "Strut earrings", "shrineProductVarsitySocks": "Varsity socks", "shrineProductWeaveKeyring": "Weave keyring", "shrineProductGatsbyHat": "Gatsby hat", "shrineProductShrugBag": "Shrug bag", "shrineProductGiltDeskTrio": "Gilt desk trio", "shrineProductCopperWireRack": "Copper wire rack", "shrineProductSootheCeramicSet": "Soothe ceramic set", "shrineProductHurrahsTeaSet": "Hurrahs tea set", "shrineProductBlueStoneMug": "Blue stone mug", "shrineProductRainwaterTray": "Rainwater tray", "shrineProductChambrayNapkins": "Chambray napkins", "shrineProductSucculentPlanters": "Succulent planters", "shrineProductQuartetTable": "Quartet table", "shrineProductKitchenQuattro": "Kitchen quattro", "shrineProductClaySweater": "Clay sweater", "shrineProductSeaTunic": "Sea tunic", "shrineProductPlasterTunic": "Plaster tunic", "rallyBudgetCategoryRestaurants": "ৰেষ্টুৰেণ্টসমূহ", "shrineProductChambrayShirt": "Chambray shirt", "shrineProductSeabreezeSweater": "Seabreeze sweater", "shrineProductGentryJacket": "Gentry jacket", "shrineProductNavyTrousers": "Navy trousers", "shrineProductWalterHenleyWhite": "Walter henley (white)", "shrineProductSurfAndPerfShirt": "Surf and perf shirt", "shrineProductGingerScarf": "Ginger scarf", "shrineProductRamonaCrossover": "Ramona crossover", "shrineProductClassicWhiteCollar": "Classic white collar", "shrineProductSunshirtDress": "Sunshirt dress", "rallyAccountDetailDataInterestRate": "সুদৰ হাৰ", "rallyAccountDetailDataAnnualPercentageYield": "বাৰ্ষিক আয়ৰ শতাংশ", "rallyAccountDataVacation": "বন্ধৰ দিন", "shrineProductFineLinesTee": "Fine lines tee", "rallyAccountDataHomeSavings": "ঘৰৰ সঞ্চয়", "rallyAccountDataChecking": "চেকিং", "rallyAccountDetailDataInterestPaidLastYear": "যোৱা বছৰ পৰিশোধ কৰা সুদ", "rallyAccountDetailDataNextStatement": "পৰৱর্তী বিবৃতি", "rallyAccountDetailDataAccountOwner": "একাউণ্টৰ গৰাকী", "rallyBudgetCategoryCoffeeShops": "কফিৰ দোকানসমূহ", "rallyBudgetCategoryGroceries": "গেলামাল", "shrineProductCeriseScallopTee": "Cerise scallop tee", "rallyBudgetCategoryClothing": "পোছাক", "rallySettingsManageAccounts": "একাউণ্টসমূহ পৰিচালনা কৰক", "rallyAccountDataCarSavings": "গাড়ীৰ সঞ্চয়", "rallySettingsTaxDocuments": "কৰ সম্পর্কীয় নথিসমূহ", "rallySettingsPasscodeAndTouchId": "পাছক’ড আৰু স্পৰ্শ আইডি", "rallySettingsNotifications": "জাননীসমূহ", "rallySettingsPersonalInformation": "ব্যক্তিগত তথ্য", "rallySettingsPaperlessSettings": "কাকতবিহীন ছেটিংসমূহ", "rallySettingsFindAtms": "এটিএম বিচাৰক", "rallySettingsHelp": "সহায়", "rallySettingsSignOut": "ছাইন আউট কৰক", "rallyAccountTotal": "সৰ্বমুঠ", "rallyBillsDue": "সম্পূৰ্ণ কৰাৰ শেষ তাৰিখ", "rallyBudgetLeft": "বাওঁ", "rallyAccounts": "একাউণ্টসমূহ", "rallyBills": "বিলসমূহ", "rallyBudgets": "বাজেটসমূহ", "rallyAlerts": "সতৰ্কবার্তাসমূহ", "rallySeeAll": "সকলো চাওক", "rallyFinanceLeft": "বাওঁ", "rallyTitleOverview": "অৱলোকন", "shrineProductShoulderRollsTee": "Shoulder rolls tee", "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{১ টা বস্তু}other{{quantity} টা বস্তু}}", "shrineCartClearButtonCaption": "কাৰ্টত থকা সমল মচক", "shrineCartTotalCaption": "সর্বমুঠ", "shrineCartSubtotalCaption": "প্ৰাথমিক মুঠ:", "shrineCartShippingCaption": "শ্বিপিং:", "shrineProductGreySlouchTank": "Grey slouch tank", "shrineProductStellaSunglasses": "Stella sunglasses", "shrineProductWhitePinstripeShirt": "White pinstripe shirt", "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": "ইউএছডি", "demoTextFieldNoMoreThan": "৮টাতকৈ অধিক বর্ণ নহয়।", "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": "Search", "starterAppTooltipShare": "শ্বেয়াৰ কৰক", "starterAppTooltipFavorite": "প্ৰিয়", "starterAppTooltipAdd": "যোগ কৰক", "bottomNavigationCalendarTab": "Calendar", "starterAppDescription": "এটা প্ৰতিক্ৰিয়াশীল ষ্টাৰ্টাৰ লে’আউট", "starterAppTitle": "ষ্টাৰ্টাৰ এপ্‌", "aboutFlutterSamplesRepo": "Flutterৰ আর্হিসমূহ GitHub ৰেপ’", "bottomNavigationContentPlaceholder": "{title} টেবৰ বাবে প্লে’চহ’ল্ডাৰ", "bottomNavigationCameraTab": "কেমেৰা", "bottomNavigationAlarmTab": "এলাৰ্ম", "bottomNavigationAccountTab": "একাউণ্ট", "demoTextFieldYourEmailAddress": "আপোনাৰ ইমেইল ঠিকনা", "demoToggleButtonDescription": "প্ৰাসংগিক বিকল্পসমূহ একগোট কৰিবলৈ ট’গল বুটামসমূহ ব্যৱহাৰ কৰিব পৰা যায়। প্ৰাসংগিক ট’গল বুটামসমূহৰ গোটসমূহক প্ৰাধান্য দিবলৈ, এটা গোটে এটা সাধাৰণ কণ্টেনাৰ শ্বেয়াৰ কৰা উচিত", "colorsGrey": "ধোঁৱাবৰণীয়া", "colorsBrown": "মাটীয়া", "colorsDeepOrange": "গাঢ় কমলা", "colorsOrange": "কমলা", "colorsAmber": "এম্বাৰ", "colorsYellow": "হালধীয়া", "colorsLime": "নেমুৰঙী", "colorsLightGreen": "পাতল সেউজীয়া", "colorsGreen": "সেউজীয়া", "homeHeaderGallery": "Gallery", "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": "আপুনি এপ্‌টো ব্যৱহাৰ কৰি থাকোঁতে \"Maps\"ক আপোনাৰ অৱস্থান এক্সেছ কৰিবলৈ অনুমতি দিবনে?", "cupertinoAlertLocationDescription": "আপোনাৰ বর্তমানৰ অৱস্থানটো মেপত প্ৰদর্শন কৰা হ'ব আৰু দিক্-নিৰ্দেশনাসমূহ, নিকটৱৰ্তী সন্ধানৰ ফলাফলসমূহ আৰু আনুমানিক যাত্ৰাৰ সময়বোৰৰ বাবে এইটো ব্যৱহাৰ কৰা হ'ব।", "cupertinoAlertAllow": "অনুমতি দিয়ক", "cupertinoAlertDontAllow": "অনুমতি নিদিব", "cupertinoAlertFavoriteDessert": "প্ৰিয় ডিজার্ট বাছনি কৰক", "cupertinoAlertDessertDescription": "অনুগ্ৰহ কৰি, তলৰ সূচীখনৰ পৰা আপোনাৰ প্ৰিয় ডিজার্টৰ প্ৰকাৰ বাছনি কৰক। আপুনি কৰা বাছনি পৰামর্শ হিচাপে আগবঢ়োৱা আপোনাৰ এলেকাত থকা খাদ্যৰ দোকানসমূহৰ সূচীখন কাষ্টমাইজ কৰিবলৈ ব্যৱহাৰ কৰা হয়।", "cupertinoAlertCheesecake": "চীজেৰে প্ৰস্তুত কৰা কেক", "cupertinoAlertTiramisu": "টিৰামিছু", "cupertinoAlertApplePie": "Apple Pie", "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_as.arb/0
{ "file_path": "gallery/lib/l10n/intl_as.arb", "repo_id": "gallery", "token_count": 57704 }
809
{ "loading": "Ladataan", "deselect": "Poista valinta", "select": "Valitse", "selectable": "Valittavissa (pitkä painallus)", "selected": "Valittu", "demo": "Esittely", "bottomAppBar": "Alaosan sovelluspalkki", "notSelected": "Ei valittu", "demoCupertinoSearchTextFieldTitle": "Hakutekstikenttä", "demoCupertinoPicker": "Valitsija", "demoCupertinoSearchTextFieldSubtitle": "iOS-tyylinen hakutekstikenttä", "demoCupertinoSearchTextFieldDescription": "Hakutekstikenttä, jonka avulla käyttäjä voi tehdä hakuja kirjoittamalla tekstiä ja joka voi tarjota ja suodattaa ehdotuksia.", "demoCupertinoSearchTextFieldPlaceholder": "Kirjoita tekstiä", "demoCupertinoScrollbarTitle": "Vierityspalkki", "demoCupertinoScrollbarSubtitle": "iOS-tyylinen vierityspalkki", "demoCupertinoScrollbarDescription": "Vierityspalkki, joka sisältää kyseisen vierityspalkin", "demoTwoPaneItem": "Tuote {value}", "demoTwoPaneList": "Lista", "demoTwoPaneFoldableLabel": "Taitettava", "demoTwoPaneSmallScreenLabel": "Pieni näyttö", "demoTwoPaneSmallScreenDescription": "TwoPane käyttäytyy näin pieninäyttöisellä laitteella.", "demoTwoPaneTabletLabel": "Tabletti/pöytätietokone", "demoTwoPaneTabletDescription": "TwoPane käyttäytyy näin suuremmalla näytöllä, esim. tabletilla tai tietokoneella.", "demoTwoPaneTitle": "TwoPane", "demoTwoPaneSubtitle": "Responsiivinen asettelu taitettavilla, suurilla ja pienillä näytöillä", "splashSelectDemo": "Valitse demo", "demoTwoPaneFoldableDescription": "TwoPane käyttäytyy näin taitettavalla laitteella.", "demoTwoPaneDetails": "Tiedot", "demoTwoPaneSelectItem": "Valitse kohde", "demoTwoPaneItemDetails": "Tuote {value}: tiedot", "demoCupertinoContextMenuActionText": "Kosketa Flutter-logoa pitkään nähdäksesi kontekstivalikon", "demoCupertinoContextMenuDescription": "iOS-tyylinen koko näytön kontekstivalikko, joka tulee näkyviin, kun elementtiä painetaan pitkään.", "demoAppBarTitle": "Sovelluspalkki", "demoAppBarDescription": "Sovelluspalkki tarjoaa nykyiseen näyttöön liittyvää sisältöä ja toimintoja. Sitä käytetään brändäykseen, näytön otsikoihin, siirtymiseen ja toimintoihin", "demoDividerTitle": "Jakaja", "demoDividerSubtitle": "Jakaja on ohut viiva, joka ryhmittelee sisältöä listoihin ja asetteluihin.", "demoDividerDescription": "Jakajia voi käyttää sisällön erotteluun esimerkiksi listoissa ja vetopaneeleissa.", "demoVerticalDividerTitle": "Pystysuuntainen jakaja", "demoCupertinoContextMenuTitle": "Kontekstivalikko", "demoCupertinoContextMenuSubtitle": "iOS-tyylinen kontekstivalikko", "demoAppBarSubtitle": "Näyttää tietoja ja toimintoja nykyisestä näytöstä", "demoCupertinoContextMenuActionOne": "Toiminto yksi", "demoCupertinoContextMenuActionTwo": "Toiminto kaksi", "demoDateRangePickerDescription": "Näyttää Material Design ‑päivämäärävalitsimen sisältävän valintaikkunan.", "demoDateRangePickerTitle": "Ajanjakson valitsin", "demoNavigationDrawerUserName": "Käyttäjätunnus", "demoNavigationDrawerUserEmail": "[email protected]", "demoNavigationDrawerText": "Voit nähdä vetopaneelin pyyhkäisemällä reunasta tai napauttamalla ylempänä vasemmalla olevaa kuvaketta", "demoNavigationRailTitle": "Navigointipalkki", "demoNavigationRailSubtitle": "Näytetään siirtymispalkki sovelluksessa", "demoNavigationRailDescription": "Materiaaliwidgetiä käytetään muutamien näkymien (yleensä 3–5) välillä siirtymiseen. Widgetin pitäisi näkyä sovelluksen vasemmassa tai oikeassa reunassa.", "demoNavigationRailFirst": "Ensimmäinen", "demoNavigationDrawerTitle": "Navigointipaneeli", "demoNavigationRailThird": "Kolmas", "replyStarredLabel": "Tähdellä merkitty", "demoTextButtonDescription": "Tekstipainike värjää tekstin painettaessa, mutta ei nosta painiketta. Käytä tekstipainikkeita yläpalkeissa, valintaikkunoissa ja tekstirivillä, jossa on täytettä", "demoElevatedButtonTitle": "Kohopainike", "demoElevatedButtonDescription": "Kohopainikkeet lisäävät ulottuvuutta enimmäkseen litteisiin asetteluihin. Ne korostavat toimintoja täysissä tai laajoissa tiloissa.", "demoOutlinedButtonTitle": "Ääriviivallinen painike", "demoOutlinedButtonDescription": "Ääriviivalliset painikkeet muuttuvat läpinäkyviksi ja nousevat painettaessa. Niistä muodostetaan usein kohopainikkeiden kanssa pari vaihtoehtoisen toissijaisen toiminnon ilmaisemiseksi.", "demoContainerTransformDemoInstructions": "Kortit, luettelot ja kelluva toimintopainike", "demoNavigationDrawerSubtitle": "Näytetään vetopaneeli sovelluspalkissa", "replyDescription": "Tehokas sähköpostin erityissovellus", "demoNavigationDrawerDescription": "Material design ‑paneeli, joka tulee näkyviin vaakasuunnassa näytön reunasta, siirtymislinkkien näyttämiseksi sovelluksessa.", "replyDraftsLabel": "Luonnokset", "demoNavigationDrawerToPageOne": "Kohde yksi", "replyInboxLabel": "Postilaatikko", "demoSharedXAxisDemoInstructions": "Seuraava- ja takaisin-painikkeet", "replySpamLabel": "Roskaposti", "replyTrashLabel": "Roskakori", "replySentLabel": "Lähetetty", "demoNavigationRailSecond": "Toinen", "demoNavigationDrawerToPageTwo": "Kohde kaksi", "demoFadeScaleDemoInstructions": "Kelluva toimintopainike ja modaalinen", "demoFadeThroughDemoInstructions": "Alanavigointi", "demoSharedZAxisDemoInstructions": "Asetuskuvakkeen painike", "demoSharedYAxisDemoInstructions": "Lajittele viimeksi soitettujen mukaan", "demoTextButtonTitle": "Tekstipainike", "demoSharedZAxisBeefSandwichRecipeTitle": "Lihavoileipä", "demoSharedZAxisDessertRecipeDescription": "Jälkiruokaresepti", "demoSharedYAxisAlbumTileSubtitle": "Artisti", "demoSharedYAxisAlbumTileTitle": "Albumi", "demoSharedYAxisRecentSortTitle": "Viimeksi toistetut", "demoSharedYAxisAlphabeticalSortTitle": "A–Ö", "demoSharedYAxisAlbumCount": "268 albumia", "demoSharedYAxisTitle": "Jaettu y-akseli", "demoSharedXAxisCreateAccountButtonText": "LUO TILI", "demoFadeScaleAlertDialogDiscardButton": "HYLKÄÄ", "demoSharedXAxisSignInTextFieldLabel": "Sähköpostiosoite tai puhelinnumero", "demoSharedXAxisSignInSubtitleText": "Kirjaudu sisään tililläsi", "demoSharedXAxisSignInWelcomeText": "Hei David Park", "demoSharedXAxisIndividualCourseSubtitle": "Näytetään erikseen", "demoSharedXAxisBundledCourseSubtitle": "Paketissa", "demoFadeThroughAlbumsDestination": "Albumit", "demoSharedXAxisDesignCourseTitle": "Design", "demoSharedXAxisIllustrationCourseTitle": "Piirtäminen", "demoSharedXAxisBusinessCourseTitle": "Talous", "demoSharedXAxisArtsAndCraftsCourseTitle": "Taide ja askartelu", "demoMotionPlaceholderSubtitle": "Toissijainen teksti", "demoFadeScaleAlertDialogCancelButton": "PERUUTA", "demoFadeScaleAlertDialogHeader": "Ilmoitusikkuna", "demoFadeScaleHideFabButton": "PIILOTA KELLUVA TOIMINTOPAINIKE", "demoFadeScaleShowFabButton": "NÄYTÄ KELLUVA TOIMINTOPAINIKE", "demoFadeScaleShowAlertDialogButton": "NÄYTÄ MODAALI", "demoFadeScaleDescription": "Tätä häivytystä käytetään sellaisten käyttöliittymäelementtien kanssa, jotka tulevat näkyviin tai poistuvat näytön sisällä, esimerkiksi valintaikkunan häivytys näytön keskellä.", "demoFadeScaleTitle": "Häivytys", "demoFadeThroughTextPlaceholder": "123 kuvaa", "demoFadeThroughSearchDestination": "Haku", "demoFadeThroughPhotosDestination": "Kuvat", "demoSharedXAxisCoursePageSubtitle": "Paketeiksi kootut kategoriat näkyvät fiidissä ryhminä. Voit muuttaa asetusta myöhemmin.", "demoFadeThroughDescription": "Tätä häivytystä käytetään siirryttäessä sellaisten käyttöliittymäelementtien välillä, jotka eivät liity vahvasti toisiinsa.", "demoFadeThroughTitle": "Täysi häivytys", "demoSharedZAxisHelpSettingLabel": "Ohje", "demoMotionSubtitle": "Kaikki ennalta asetetut siirtymät", "demoSharedZAxisNotificationSettingLabel": "Ilmoitukset", "demoSharedZAxisProfileSettingLabel": "Profiili", "demoSharedZAxisSavedRecipesListTitle": "Tallennetut reseptit", "demoSharedZAxisBeefSandwichRecipeDescription": "Lihavoileivän resepti", "demoSharedZAxisCrabPlateRecipeDescription": "Rapuannoksen resepti", "demoSharedXAxisCoursePageTitle": "Kurssit selkeämmiksi", "demoSharedZAxisCrabPlateRecipeTitle": "Rapu", "demoSharedZAxisShrimpPlateRecipeDescription": "Katkarapuannoksen resepti", "demoSharedZAxisShrimpPlateRecipeTitle": "Katkarapu", "demoContainerTransformTypeFadeThrough": "TÄYSI HÄIVYTYS", "demoSharedZAxisDessertRecipeTitle": "Jälkiruoka", "demoSharedZAxisSandwichRecipeDescription": "Voileipäresepti", "demoSharedZAxisSandwichRecipeTitle": "Voileipä", "demoSharedZAxisBurgerRecipeDescription": "Hampurilaisresepti", "demoSharedZAxisBurgerRecipeTitle": "Hampurilainen", "demoSharedZAxisSettingsPageTitle": "Asetukset", "demoSharedZAxisTitle": "Jaettu z-akseli", "demoSharedZAxisPrivacySettingLabel": "Tietosuoja", "demoMotionTitle": "Liike", "demoContainerTransformTitle": "Muuntuva säilö", "demoContainerTransformDescription": "Muuntuvaa säilöä käytetään käyttöliittymäelementtien välisessä siirtymässä, kun niihin liittyy säilö. Näin kahden käyttöliittymäelementin välille syntyy näkyvä yhteys.", "demoContainerTransformModalBottomSheetTitle": "Häivytystapa", "demoContainerTransformTypeFade": "HÄIVYTYS", "demoSharedYAxisAlbumTileDurationUnit": "min.", "demoMotionPlaceholderTitle": "Nimi", "demoSharedXAxisForgotEmailButtonText": "UNOHDITKO SÄHKÖPOSTIOSOITTEEN?", "demoMotionSmallPlaceholderSubtitle": "Toissijainen", "demoMotionDetailsPageTitle": "Tietosivu", "demoMotionListTileTitle": "Listan osa", "demoSharedAxisDescription": "Jaettua akselia käytetään käyttöliittymäelementtien väliseen siirtymään, kun niillä on tilaan tai navigointiin liittyvä suhde. Silloin yhtäaikainen siirtyminen x-, y- tai z-akselilla vahvistaa elementtien välistä suhdetta.", "demoSharedXAxisTitle": "Jaettu x-akseli", "demoSharedXAxisBackButtonText": "TAKAISIN", "demoSharedXAxisNextButtonText": "SEURAAVA", "demoSharedXAxisCulinaryCourseTitle": "Ruoanlaitto", "githubRepo": "GitHub-datasäilö: {repoName}", "fortnightlyMenuUS": "Yhdysvallat", "fortnightlyMenuBusiness": "Talous", "fortnightlyMenuScience": "Tiede", "fortnightlyMenuSports": "Urheilu", "fortnightlyMenuTravel": "Matkailu", "fortnightlyMenuCulture": "Kulttuuri", "fortnightlyTrendingTechDesign": "TechDesign", "rallyBudgetDetailAmountLeft": "Jäljellä oleva summa", "fortnightlyHeadlineArmy": "Vihreä armeija uudistuu sisältä päin", "fortnightlyDescription": "Sisältökeskeinen uutissovellus", "rallyBillDetailAmountDue": "Erääntyvä summa", "rallyBudgetDetailTotalCap": "Kokonaisrajoitus", "rallyBudgetDetailAmountUsed": "Käytetty summa", "fortnightlyTrendingHealthcareRevolution": "HealthcareRevolution", "fortnightlyMenuFrontPage": "Etusivu", "fortnightlyMenuWorld": "Ulkomaat", "rallyBillDetailAmountPaid": "Maksettu summa", "fortnightlyMenuPolitics": "Politiikka", "fortnightlyHeadlineBees": "Maaseudun mehiläiskato", "fortnightlyHeadlineGasoline": "Bensiinin tulevaisuus", "fortnightlyTrendingGreenArmy": "GreenArmy", "fortnightlyHeadlineFeminists": "Feministit kyseenalaistavat puolueellisuuden", "fortnightlyHeadlineFabrics": "Tulevaisuuden kankaita kehitetään teknologian avulla", "fortnightlyHeadlineStocks": "Osakkeiden kasvun hidastuessa katseet kääntyvät valuuttaan", "fortnightlyTrendingReform": "Reform", "fortnightlyMenuTech": "Tekniikka", "fortnightlyHeadlineWar": "Sodan erottamat amerikkalaiselämät", "fortnightlyHeadlineHealthcare": "Terveydenhuollon hiljainen mutta vaikuttava vallankumous", "fortnightlyLatestUpdates": "Viimeisimmät päivitykset", "fortnightlyTrendingStocks": "Stocks", "rallyBillDetailTotalAmount": "Kokonaissumma", "demoCupertinoPickerDateTime": "Päivämäärä ja aika", "signIn": "KIRJAUDU SISÄÄN", "dataTableRowWithSugar": "{value} sokerilla", "dataTableRowApplePie": "Omenapiirakka", "dataTableRowDonut": "Donitsi", "dataTableRowHoneycomb": "Hunajamakeinen", "dataTableRowLollipop": "Tikkari", "dataTableRowJellyBean": "Jelly bean ‑karkki", "dataTableRowGingerbread": "Piparkakku", "dataTableRowCupcake": "Kuppikakku", "dataTableRowEclair": "Eclair", "dataTableRowIceCreamSandwich": "Jäätelökeksi", "dataTableRowFrozenYogurt": "Jääjogurtti", "dataTableColumnIron": "Rauta (%)", "dataTableColumnCalcium": "Kalsium (%)", "dataTableColumnSodium": "Natrium (mg)", "demoTimePickerTitle": "Ajan valitsin", "demo2dTransformationsResetTooltip": "Nollaa muunnokset", "dataTableColumnFat": "Rasva (g)", "dataTableColumnCalories": "Kalorit", "dataTableColumnDessert": "Jälkiruoka (1 annos)", "cardsDemoTravelDestinationLocation1": "Thanjavur, Tamil Nadu", "demoTimePickerDescription": "Näyttää Material Design ‑aikavalitsimen sisältävän valintaikkunan.", "demoPickersShowPicker": "NÄYTÄ VALITSIN", "demoTabsScrollingTitle": "Vieritettävä", "demoTabsNonScrollingTitle": "Ei vieritettävä", "craneHours": "{hours,plural,=1{1 h}other{{hours} h}}", "craneMinutes": "{minutes,plural,=1{1 min}other{{minutes} min}}", "craneFlightDuration": "{hoursShortForm} {minutesShortForm}", "dataTableHeader": "Ravinto", "demoDatePickerTitle": "Päivämäärävalitsin", "demoPickersSubtitle": "Päivämäärän ja ajan valinta", "demoPickersTitle": "Valitsimet", "demo2dTransformationsEditTooltip": "Muokkaa osaa", "demoDataTableDescription": "Datataulukot näyttävät tiedot ruudukonkaltaisessa muodossa eli riveinä ja sarakkeina. Ne järjestävät tiedot helposti katseltavaan muotoon, jotta käyttäjät voivat etsiä kaavoja ja vinkkejä.", "demo2dTransformationsDescription": "Napauta muokataksesi osia ja liiku kuvassa eleiden avulla. Panoroi vetämällä, zoomaa nipistämällä ja kierrä kahdella sormella. Palaa alkuperäiseen näkymään painamalla nollauspainiketta.", "demo2dTransformationsSubtitle": "Panorointi, zoomaus, kierto", "demo2dTransformationsTitle": "2D-muunnokset", "demoCupertinoTextFieldPIN": "PIN-koodi", "demoCupertinoTextFieldDescription": "Tekstikentän avulla käyttäjä voi lisätä tekstiä joko laite- tai näyttönäppäimistöllä.", "demoCupertinoTextFieldSubtitle": "iOS-tyyliset tekstikentät", "demoCupertinoTextFieldTitle": "Tekstikentät", "demoDatePickerDescription": "Näyttää Material Design ‑päivämäärävalitsimen sisältävän valintaikkunan.", "demoCupertinoPickerTime": "Aika", "demoCupertinoPickerDate": "Päivämäärä", "demoCupertinoPickerTimer": "Ajastin", "demoCupertinoPickerDescription": "iOS-tyylinen valitsin-widget, jolla voidaan valita merkkijonoja, päivämääriä, aikoja tai molempia.", "demoCupertinoPickerSubtitle": "iOS-tyyliset valitsimet", "demoCupertinoPickerTitle": "Valitsimet", "dataTableRowWithHoney": "{value} hunajalla", "cardsDemoTravelDestinationCity2": "Chettinad", "bannerDemoResetText": "Nollaa banneri", "bannerDemoMultipleText": "Useita toimintoja", "bannerDemoLeadingText": "Johtokuvake", "dismiss": "OHITA", "cardsDemoTappable": "Napautettava", "cardsDemoSelectable": "Valittava (pitkä painallus)", "cardsDemoExplore": "Tutustu", "cardsDemoExploreSemantics": "Tutustu: {destinationName}", "cardsDemoShareSemantics": "Jaa: {destinationName}", "cardsDemoTravelDestinationTitle1": "Tamil Nadun 10 parasta kaupunkia", "cardsDemoTravelDestinationDescription1": "Numero 10", "cardsDemoTravelDestinationCity1": "Thanjavur", "dataTableColumnProtein": "Proteiini (g)", "cardsDemoTravelDestinationTitle2": "Etelä-Intian artisaanit", "cardsDemoTravelDestinationDescription2": "Silkintekijät", "bannerDemoText": "Salasanasi päivitettiin toisella laitteellasi. Kirjaudu sisään uudelleen.", "cardsDemoTravelDestinationLocation2": "Sivaganga, Tamil Nadu", "cardsDemoTravelDestinationTitle3": "Brihadisvaran temppeli", "cardsDemoTravelDestinationDescription3": "Temppelit", "demoBannerTitle": "Banneri", "demoBannerSubtitle": "Näytetään banneri luettelon sisällä", "demoBannerDescription": "Banneri näyttää tärkeän, ytimekkään viestin ja tarjoaa käyttäjille toimintoja, joita he voivat tehdä (tai ohittaa bannerin). Käyttäjän toimia tarvitaan sen ohittamiseen.", "demoCardTitle": "Kortit", "demoCardSubtitle": "Peruskortit pyöristetyillä kulmilla", "demoCardDescription": "Kortti on tiettyä materiaalia oleva arkki, jolla ilmaistaan asiaan liittyvä tietoa, esimerkiksi albumi, maantieteellinen sijainti, ateria, yhteystiedot jne.", "demoDataTableTitle": "Datataulukot", "demoDataTableSubtitle": "Rivit ja sarakkeet täynnä tietoa", "dataTableColumnCarbs": "Hiilihydraatit (g)", "placeTanjore": "Thanjavur", "demoGridListsTitle": "Ruudukkolistat", "placeFlowerMarket": "Kukkatori", "placeBronzeWorks": "Pronssipaja", "placeMarket": "Tori", "placeThanjavurTemple": "Thanjavurin temppeli", "placeSaltFarm": "Suolaviljelmä", "placeScooters": "Skootterit", "placeSilkMaker": "Silkinkutoja", "placeLunchPrep": "Lounaan tekeminen", "placeBeach": "Ranta", "placeFisherman": "Kalastaja", "demoMenuSelected": "{value} valittu", "demoMenuRemove": "Poista", "demoMenuGetLink": "Hae linkki", "demoMenuShare": "Jaa", "demoBottomAppBarSubtitle": "Näyttää siirtymisen ja toiminnot alaosassa", "demoMenuAnItemWithASectionedMenu": "Elementti, jolla on osioihin jaettu valikko", "demoMenuADisabledMenuItem": "Käytöstä poistettu valikon kohta", "demoLinearProgressIndicatorTitle": "Lineaarinen edistymisen osoitin", "demoMenuContextMenuItemOne": "Ensimmäinen kontekstivalikon kohta", "demoMenuAnItemWithASimpleMenu": "Elementti, jolla on yksinkertainen valikko", "demoCustomSlidersTitle": "Omat liukusäätimet", "demoMenuAnItemWithAChecklistMenu": "Elementti, jolla on muistilistavalikko", "demoCupertinoActivityIndicatorTitle": "Toimintaosoitin", "demoCupertinoActivityIndicatorSubtitle": "iOS-tyyliset toimintaosoittimet", "demoCupertinoActivityIndicatorDescription": "iOS-tyylinen toimintaosoitin, joka pyörii myötäpäivään.", "demoCupertinoNavigationBarTitle": "Navigointipalkki", "demoCupertinoNavigationBarSubtitle": "iOS-tyylinen siirtymispalkki", "demoCupertinoNavigationBarDescription": "iOS-tyylinen siirtymispalkki. Navigointipalkki koostuu pienimmillään sivun otsikosta, joka sijaitsee yläpalkin keskellä.", "demoCupertinoPullToRefreshTitle": "Vetämällä päivittäminen", "demoCupertinoPullToRefreshSubtitle": "iOS-tyylinen vetämällä päivittämisen asetus", "demoCupertinoPullToRefreshDescription": "Widget, joka tekee vetämällä päivittämisen asetuksesta iOS-tyylisen.", "demoProgressIndicatorTitle": "Edistymisen osoittimet", "demoProgressIndicatorSubtitle": "Lineaariset, ympyränmuotoiset, määrittelemättömät", "demoCircularProgressIndicatorTitle": "Ympyränmuotoinen edistymisen osoitin", "demoCircularProgressIndicatorDescription": "Material designin ympyränmuotoinen edistymisen osoitin, jonka pyöriminen osoittaa sovelluksen olevan varattu.", "demoMenuFour": "Neljä", "demoLinearProgressIndicatorDescription": "Material designin lineaarinen edistymisen osoitin, jota kutsutaan myös etenemispalkiksi.", "demoTooltipTitle": "Työkaluvinkit", "demoTooltipSubtitle": "Lyhyt viesti, joka näkyy pitkällä painalluksella tai hiiren ollessa elementin päällä", "demoTooltipDescription": "Työkaluvinkki on tekstikenttä, joka selittää painikkeen toimintaa tai käyttöliittymän muuta toimintoa. Vinkin teksti näkyy, kun käyttäjä vie hiiren elementin päälle, tarkentaa siihen tai painaa sitä pitkään.", "demoTooltipInstructions": "Paina pitkään tai vie hiiri elementin päälle, niin vihjeteksti tulee esiin.", "placeChennai": "Chennai", "demoMenuChecked": "Ruutu {value} valittu", "placeChettinad": "Chettinad", "demoMenuPreview": "Esikatselu", "demoBottomAppBarTitle": "Alaosan sovelluspalkki", "demoBottomAppBarDescription": "Alaosan sovelluspalkkien kautta voidaan käyttää alaosan navigointipaneelia ja jopa neljää toimintoa, mukaan lukien kelluvaa toimintopainiketta.", "bottomAppBarNotch": "Lovi", "bottomAppBarPosition": "Kelluvan toimintopainikkeen sijainti", "bottomAppBarPositionDockedEnd": "Telakoitu – lopussa", "bottomAppBarPositionDockedCenter": "Telakoitu – keskellä", "bottomAppBarPositionFloatingEnd": "Kelluva – lopussa", "bottomAppBarPositionFloatingCenter": "Kelluva – keskellä", "demoSlidersEditableNumericalValue": "Muokattava numeerinen arvo", "demoGridListsSubtitle": "Rivi- ja sarakeasettelu", "demoGridListsDescription": "Ruudukkolistat toimivat parhaiten, kun esitetään samanmuotoista dataa, yleensä kuvia. Ruudukon osia kutsutaan ruuduiksi.", "demoGridListsImageOnlyTitle": "Vain kuva", "demoGridListsHeaderTitle": "Sisältää otsikon", "demoGridListsFooterTitle": "Sisältää alatunnisteen", "demoSlidersTitle": "Liukusäätimet", "demoSlidersSubtitle": "Widgetit arvon valitsemiseen pyyhkäisemällä", "demoSlidersDescription": "Liukusäätimet kuvastavat erilaisia arvoja palkissa, josta käyttäjät voivat valita yksittäisen arvon. Ne sopivat erinomaisesti asetusten (kuten äänenvoimakkuuden tai kirkkauden) muuttamiseen tai kuvasuodattimien käyttöönottoon.", "demoRangeSlidersTitle": "Välin liukusäätimet", "demoRangeSlidersDescription": "Liukusäätimet kuvastavat erilaisia arvoja palkissa. Niiden kummassakin päässä voi olla kuvake, joka osoittaa erilaisia arvoja. Ne sopivat erinomaisesti asetusten (kuten äänenvoimakkuuden tai kirkkauden) muuttamiseen tai kuvasuodattimien käyttöönottoon.", "demoMenuAnItemWithAContextMenuButton": "Elementti, jolla on kontekstivalikko", "demoCustomSlidersDescription": "Liukusäätimet kuvastavat erilaisia arvoja palkissa, josta käyttäjät voivat valita yksittäisen arvon tai useita erilaisia arvoja. Liukusäätimiä voi jakaa teemoihin ja muokata.", "demoSlidersContinuousWithEditableNumericalValue": "Jatkuva arvo, jonka numeroa voi muokata", "demoSlidersDiscrete": "Diskreetti", "demoSlidersDiscreteSliderWithCustomTheme": "Diskreetti liukusäädin, jonka teemaa voi muokata", "demoSlidersContinuousRangeSliderWithCustomTheme": "Jatkuva välin liukusäädin, jonka teemaa voi muokata", "demoSlidersContinuous": "Jatkuva", "placePondicherry": "Pondicherry", "demoMenuTitle": "Valikko", "demoContextMenuTitle": "Kontekstivalikko", "demoSectionedMenuTitle": "Osioihin jaettu valikko", "demoSimpleMenuTitle": "Yksinkertainen valikko", "demoChecklistMenuTitle": "Muistilistavalikko", "demoMenuSubtitle": "Valikon painikkeet ja yksinkertaiset valikot", "demoMenuDescription": "Valikossa näytetään lista vaihtoehtoja väliaikaista taustaa vasten. Ne tulevat näkyviin, kun käyttäjä valitsee painikkeen, toiminnon tai muun säätimen.", "demoMenuItemValueOne": "Ensimmäinen valikon kohta", "demoMenuItemValueTwo": "Toinen valikon kohta", "demoMenuItemValueThree": "Kolmas valikon kohta", "demoMenuOne": "Yksi", "demoMenuTwo": "Kaksi", "demoMenuThree": "Kolme", "demoMenuContextMenuItemThree": "Kolmas kontekstivalikon kohta", "demoCupertinoSwitchSubtitle": "iOS-tyylinen kytkin", "demoSnackbarsText": "Tämä on pikatiedote.", "demoCupertinoSliderSubtitle": "iOS-tyylinen liukusäädin", "demoCupertinoSliderDescription": "Liukusäätimellä voi valita jatkuvasta tai diskreetistä arvojoukosta.", "demoCupertinoSliderContinuous": "Jatkuva: {value}", "demoCupertinoSliderDiscrete": "Diskreetti: {value}", "demoSnackbarsAction": "Valitsit pikatiedotteen toiminnon.", "backToGallery": "Takaisin Galleriaan", "demoCupertinoTabBarTitle": "Välilehtirivi", "demoCupertinoSwitchDescription": "Kytkimellä tietty asetus laitetaan päälle tai pois päältä.", "demoSnackbarsActionButtonLabel": "TOIMINTO", "cupertinoTabBarProfileTab": "Profiili", "demoSnackbarsButtonLabel": "NÄYTÄ PIKATIEDOTE", "demoSnackbarsDescription": "Pikatiedotteet ilmoittavat käyttäjille prosesseista, jotka sovellus on suorittanut tai tulee suorittamaan. Ne näkyvät väliaikaisesti näytön alaosassa. Niiden ei pitäisi häiritä käyttökokemusta, ja ne katoavat itsestään.", "demoSnackbarsSubtitle": "Pikatiedotteet näyttävät viestejä näytön alareunassa", "demoSnackbarsTitle": "Pikatiedotteet", "demoCupertinoSliderTitle": "Liukusäädin", "cupertinoTabBarChatTab": "Chat", "cupertinoTabBarHomeTab": "Koti", "demoCupertinoTabBarDescription": "iOS-tyylinen alareunan välilehtipalkki siirtymistä varten. Näyttää useita välilehtiä, joista yksi on aktiivinen (oletuksena ensimmäinen välilehti).", "demoCupertinoTabBarSubtitle": "iOS-tyylinen alareunan välilehtipalkki", "demoOptionsFeatureTitle": "Näytä asetukset", "demoOptionsFeatureDescription": "Voit näyttää esittelystä saatavilla olevat vaihtoehdot napauttamalla tästä.", "demoCodeViewerCopyAll": "KOPIOI KAIKKI", "shrineScreenReaderRemoveProductButton": "Poista {product}", "shrineScreenReaderProductAddToCart": "Lisää ostoskoriin", "shrineScreenReaderCart": "{quantity,plural,=0{Ostoskori, ei tuotteita}=1{Ostoskori, 1 tuote}other{Ostoskori, {quantity} tuotetta}}", "demoCodeViewerFailedToCopyToClipboardMessage": "Kopiointi leikepöydälle epäonnistui: {error}", "demoCodeViewerCopiedToClipboardMessage": "Kopioitu leikepöydälle.", "craneSleep8SemanticLabel": "Mayalaiset rauniot kalliolla rannan yläpuolella", "craneSleep4SemanticLabel": "Järvenrantahotelli vuorten edessä", "craneSleep2SemanticLabel": "Machu Picchun linnake", "craneSleep1SemanticLabel": "Talvimökki lumisessa maisemassa ja ikivihreitä puita", "craneSleep0SemanticLabel": "Vedenpäällisiä taloja", "craneFly13SemanticLabel": "Meriallas ja palmuja", "craneFly12SemanticLabel": "Uima-allas ja palmuja", "craneFly11SemanticLabel": "Tiilimajakka meressä", "craneFly10SemanticLabel": "Al-Azhar-moskeijan tornit auringonlaskun aikaan", "craneFly9SemanticLabel": "Mies nojaamassa siniseen antiikkiautoon", "craneFly8SemanticLabel": "Supertree Grove", "craneEat9SemanticLabel": "Kahvilan tiski, jossa leivonnaisia", "craneEat2SemanticLabel": "Hampurilainen", "craneFly5SemanticLabel": "Järvenrantahotelli vuorten edessä", "demoSelectionControlsSubtitle": "Valintaruudut, valintanapit ja päälle/pois-valitsimet", "craneEat10SemanticLabel": "Nainen pitää kädessään suurta pastrami-voileipää", "craneFly4SemanticLabel": "Vedenpäällisiä taloja", "craneEat7SemanticLabel": "Leipomon sisäänkäynti", "craneEat6SemanticLabel": "Katkarapuannos", "craneEat5SemanticLabel": "Taiteellinen ravintolan istuma-alue", "craneEat4SemanticLabel": "Suklaajälkiruoka", "craneEat3SemanticLabel": "Korealainen taco", "craneFly3SemanticLabel": "Machu Picchun linnake", "craneEat1SemanticLabel": "Tyhjä baaritiski ja amerikkalaisravintolan tyyliset tuolit", "craneEat0SemanticLabel": "Pizza puu-uunissa", "craneSleep11SemanticLabel": "Taipei 101 ‑pilvenpiirtäjä", "craneSleep10SemanticLabel": "Al-Azhar-moskeijan tornit auringonlaskun aikaan", "craneSleep9SemanticLabel": "Tiilimajakka meressä", "craneEat8SemanticLabel": "Lautasellinen rapuja", "craneSleep7SemanticLabel": "Värikkäitä rakennuksia Riberia Squarella", "craneSleep6SemanticLabel": "Uima-allas ja palmuja", "craneSleep5SemanticLabel": "Teltta pellolla", "settingsButtonCloseLabel": "Sulje asetukset", "demoSelectionControlsCheckboxDescription": "Valintaruutujen avulla käyttäjä voi valita useita vaihtoehtoja joukosta. Valintaruudun tavalliset arvovaihtoehdot ovat tosi ja epätosi, ja kolmisuuntaisen valintaruudun arvo voi myös olla tyhjä.", "settingsButtonLabel": "Asetukset", "demoListsTitle": "Luettelot", "demoListsSubtitle": "Vieritettävien luetteloiden ulkoasut", "demoListsDescription": "Yksi korkeudeltaan kiinteä rivi, joka sisältää yleensä tekstiä ja jonka alussa tai lopussa on kuvake.", "demoOneLineListsTitle": "Yksi rivi", "demoTwoLineListsTitle": "Kaksi riviä", "demoListsSecondary": "Toissijainen teksti", "demoSelectionControlsTitle": "Valintaohjaimet", "craneFly7SemanticLabel": "Mount Rushmore", "demoSelectionControlsCheckboxTitle": "Valintaruutu", "craneSleep3SemanticLabel": "Mies nojaamassa siniseen antiikkiautoon", "demoSelectionControlsRadioTitle": "Valintanappi", "demoSelectionControlsRadioDescription": "Valintanapin avulla käyttäjä voi valita yhden vaihtoehdon joukosta. Käytä valintanappeja, kun käyttäjä voi valita vain yhden vaihtoehdon ja hänen pitää nähdä kaikki vaihtoehdot vierekkäin.", "demoSelectionControlsSwitchTitle": "Valitsin", "demoSelectionControlsSwitchDescription": "Päälle/pois-valitsimet vaihtavat yksittäisen asetuksen tilan. Valitsimen ohjaama vaihtoehto sekä sen nykyinen tila pitäisi näkyä selkeästi sen tunnuksesta.", "craneFly0SemanticLabel": "Talvimökki lumisessa maisemassa ja ikivihreitä puita", "craneFly1SemanticLabel": "Teltta pellolla", "craneFly2SemanticLabel": "Rukouslippuja lumisen vuoren edessä", "craneFly6SemanticLabel": "Ilmanäkymä Palacio de Bellas Artesista", "rallySeeAllAccounts": "Näytä kaikki tilit", "rallyBillAmount": "Lasku {billName}, {amount} {date} mennessä", "shrineTooltipCloseCart": "Sulje ostoskori", "shrineTooltipCloseMenu": "Sulje valikko", "shrineTooltipOpenMenu": "Avaa valikko", "shrineTooltipSettings": "Asetukset", "shrineTooltipSearch": "Haku", "demoTabsDescription": "Välilehdille järjestetään sisältöä eri näytöiltä, datajoukoista ja muista tilanteista.", "demoTabsSubtitle": "Välilehdet, joiden näkymiä voidaan selata erikseen", "demoTabsTitle": "Välilehdet", "rallyBudgetAmount": "Budjetti {budgetName}, {amountUsed} käytetty, kokonaismäärä {amountTotal}, {amountLeft} jäljellä", "shrineTooltipRemoveItem": "Poista tuote", "rallyAccountAmount": "{accountName}tili {accountNumber}, jolla on {amount}.", "rallySeeAllBudgets": "Näytä kaikki budjetit", "rallySeeAllBills": "Näytä kaikki laskut", "craneFormDate": "Valitse päivämäärä", "craneFormOrigin": "Valitse lähtöpaikka", "craneFly2": "Khumbun laakso, Nepal", "craneFly3": "Machu Picchu, Peru", "craneFly4": "Malé, Malediivit", "craneFly5": "Vitznau, Sveitsi", "craneFly6": "Mexico City, Meksiko", "craneFly7": "Mount Rushmore, Yhdysvallat", "settingsTextDirectionLocaleBased": "Perustuu kieli- ja maa-asetukseen", "craneFly9": "Havanna, Kuuba", "craneFly10": "Kairo, Egypti", "craneFly11": "Lissabon, Portugali", "craneFly12": "Napa, Yhdysvallat", "craneFly13": "Bali, Indonesia", "craneSleep0": "Malé, Malediivit", "craneSleep1": "Aspen, Yhdysvallat", "craneSleep2": "Machu Picchu, Peru", "demoCupertinoSegmentedControlTitle": "Segmenttihallinta", "craneSleep4": "Vitznau, Sveitsi", "craneSleep5": "Big Sur, Yhdysvallat", "craneSleep6": "Napa, Yhdysvallat", "craneSleep7": "Porto, Portugali", "craneSleep8": "Tulum, Meksiko", "craneEat5": "Soul, Etelä-Korea", "demoChipTitle": "Elementit", "demoChipSubtitle": "Syötettä, määritettä tai toimintoa vastaavat tiiviit elementit", "demoActionChipTitle": "Toimintoelementti", "demoActionChipDescription": "Toimintoelementit ovat vaihtoehtoja, jotka käynnistävät pääsisältöön liittyvän toiminnon. Toimintoelementtien pitäisi tulla näkyviin käyttöliittymissä dynaamisesti ja sopivassa asiayhteydessä.", "demoChoiceChipTitle": "Valintaelementti", "demoChoiceChipDescription": "Valintaelementit ovat joukkoon kuuluvia yksittäisiä vaihtoehtoja. Valintaelementit sisältävät aiheeseen liittyviä luokkia tai kuvailevaa tekstiä.", "demoFilterChipTitle": "Suodatinelementti", "demoFilterChipDescription": "Suodatinelementeissä käytetään tageja tai kuvailevia sanoja sisällön suodattamiseen.", "demoInputChipTitle": "Syöte-elementti", "demoInputChipDescription": "Syöte-elementit ovat monimutkaisia tietoja, kuten yksikkö (henkilö, paikka tai asia) tai keskustelun teksti, tiiviissä muodossa.", "craneSleep9": "Lissabon, Portugali", "craneEat10": "Lissabon, Portugali", "demoCupertinoSegmentedControlDescription": "Tällä valitaan yksi toisensa poissulkevista vaihtoehdoista. Kun yksi segmenttihallituista vaihtoehdoista valitaan, valinta poistuu sen muista vaihtoehdoista.", "chipTurnOnLights": "Laita valot päälle", "chipSmall": "Pieni", "chipMedium": "Keskikoko", "chipLarge": "Suuri", "chipElevator": "Hissi", "chipWasher": "Pesukone", "chipFireplace": "Takka", "chipBiking": "Pyöräily", "craneFormDiners": "Ruokaravintolat", "rallyAlertsMessageUnassignedTransactions": "{count,plural,=1{Lisää mahdollisten verovähennystesi määrää! Anna 1 tuntemattomalle tapahtumalle luokka.}other{Lisää mahdollisten verovähennystesi määrää! Anna {count} tuntemattomalle tapahtumalle luokat.}}", "craneFormTime": "Valitse aika", "craneFormLocation": "Valitse sijainti", "craneFormTravelers": "Matkustajat", "craneEat8": "Atlanta, Yhdysvallat", "craneFormDestination": "Valitse määränpää", "craneFormDates": "Valitse päivämäärät", "craneFly": "LENTÄMINEN", "craneSleep": "NUKKUMINEN", "craneEat": "SYÖMINEN", "craneFlySubhead": "Lennot määränpään mukaan", "craneSleepSubhead": "Majoituspaikat määränpään mukaan", "craneEatSubhead": "Ravintolat määränpään mukaan", "craneFlyStops": "{numberOfStops,plural,=0{Suorat lennot}=1{1 välilasku}other{{numberOfStops} välilaskua}}", "craneSleepProperties": "{totalProperties,plural,=0{Ei majoituspaikkoja saatavilla}=1{1 majoituspaikka saatavilla}other{{totalProperties} majoituspaikkaa saatavilla}}", "craneEatRestaurants": "{totalRestaurants,plural,=0{Ei ravintoloita}=1{1 ravintola}other{{totalRestaurants} ravintolaa}}", "craneFly0": "Aspen, Yhdysvallat", "demoCupertinoSegmentedControlSubtitle": "iOS-tyylinen segmenttihallinta", "craneSleep10": "Kairo, Egypti", "craneEat9": "Madrid, Espanja", "craneFly1": "Big Sur, Yhdysvallat", "craneEat7": "Nashville, Yhdysvallat", "craneEat6": "Seattle, Yhdysvallat", "craneFly8": "Singapore", "craneEat4": "Pariisi, Ranska", "craneEat3": "Portland, Yhdysvallat", "craneEat2": "Córdoba, Argentiina", "craneEat1": "Dallas, Yhdysvallat", "craneEat0": "Napoli, Italia", "craneSleep11": "Taipei, Taiwan", "craneSleep3": "Havanna, Kuuba", "shrineLogoutButtonCaption": "KIRJAUDU ULOS", "rallyTitleBills": "LASKUT", "rallyTitleAccounts": "TILIT", "shrineProductVagabondSack": "Vagabond-laukku", "rallyAccountDetailDataInterestYtd": "Korko YTD", "shrineProductWhitneyBelt": "Whitney-vyö", "shrineProductGardenStrand": "Garden-moniketju", "shrineProductStrutEarrings": "Näyttävät korvakorut", "shrineProductVarsitySocks": "Tennissukat", "shrineProductWeaveKeyring": "Punottu avaimenperä", "shrineProductGatsbyHat": "Gatsby-hattu", "shrineProductShrugBag": "Olkalaukku", "shrineProductGiltDeskTrio": "Kullattu kolmoispöytä", "shrineProductCopperWireRack": "Kuparilankahylly", "shrineProductSootheCeramicSet": "Soothe-keramiikka-astiasto", "shrineProductHurrahsTeaSet": "Hurrahs-teeastiasto", "shrineProductBlueStoneMug": "Sininen keraaminen muki", "shrineProductRainwaterTray": "Sadeveden keräin", "shrineProductChambrayNapkins": "Chambray-lautasliinat", "shrineProductSucculentPlanters": "Mehikasvien ruukut", "shrineProductQuartetTable": "Neliosainen pöytäsarja", "shrineProductKitchenQuattro": "Quattro (keittiö)", "shrineProductClaySweater": "Maanvärinen college-paita", "shrineProductSeaTunic": "Merenvärinen tunika", "shrineProductPlasterTunic": "Luonnonvalkoinen tunika", "rallyBudgetCategoryRestaurants": "Ravintolat", "shrineProductChambrayShirt": "Chambray-paita", "shrineProductSeabreezeSweater": "Merituuli-college", "shrineProductGentryJacket": "Gentry-takki", "shrineProductNavyTrousers": "Laivastonsiniset housut", "shrineProductWalterHenleyWhite": "Walter Henley (valkoinen)", "shrineProductSurfAndPerfShirt": "Surffipaita", "shrineProductGingerScarf": "Punertava huivi", "shrineProductRamonaCrossover": "Ramona crossover", "shrineProductClassicWhiteCollar": "Klassinen valkokaulus", "shrineProductSunshirtDress": "UV-paitamekko", "rallyAccountDetailDataInterestRate": "Korkoprosentti", "rallyAccountDetailDataAnnualPercentageYield": "Vuosituotto prosentteina", "rallyAccountDataVacation": "Loma", "shrineProductFineLinesTee": "T-paita, ohuet viivat", "rallyAccountDataHomeSavings": "Kodin säästötili", "rallyAccountDataChecking": "Tarkistetaan", "rallyAccountDetailDataInterestPaidLastYear": "Viime vuonna maksetut korot", "rallyAccountDetailDataNextStatement": "Seuraava ote", "rallyAccountDetailDataAccountOwner": "Tilin omistaja", "rallyBudgetCategoryCoffeeShops": "Kahvilat", "rallyBudgetCategoryGroceries": "Ruokaostokset", "shrineProductCeriseScallopTee": "Kirsikanpunainen scallop-teepaita", "rallyBudgetCategoryClothing": "Vaatteet", "rallySettingsManageAccounts": "Hallitse tilejä", "rallyAccountDataCarSavings": "Autosäästötili", "rallySettingsTaxDocuments": "Veroasiakirjat", "rallySettingsPasscodeAndTouchId": "Tunnuskoodi ja Touch ID", "rallySettingsNotifications": "Ilmoitukset", "rallySettingsPersonalInformation": "Henkilötiedot", "rallySettingsPaperlessSettings": "Paperittomuuden asetukset", "rallySettingsFindAtms": "Etsi pankkiautomaatteja", "rallySettingsHelp": "Ohje", "rallySettingsSignOut": "Kirjaudu ulos", "rallyAccountTotal": "Yhteensä", "rallyBillsDue": "Maksettavaa", "rallyBudgetLeft": "Vasen", "rallyAccounts": "Tilit", "rallyBills": "Laskut", "rallyBudgets": "Budjetit", "rallyAlerts": "Ilmoitukset", "rallySeeAll": "NÄYTÄ KAIKKI", "rallyFinanceLeft": "VASEN", "rallyTitleOverview": "ESITTELY", "shrineProductShoulderRollsTee": "T-paita, käärittävät hihat", "shrineNextButtonCaption": "SEURAAVA", "rallyTitleBudgets": "BUDJETIT", "rallyTitleSettings": "ASETUKSET", "rallyLoginLoginToRally": "Kirjaudu sisään Rallyyn", "rallyLoginNoAccount": "Eikö sinulla ole tiliä?", "rallyLoginSignUp": "REKISTERÖIDY", "rallyLoginUsername": "Käyttäjänimi", "rallyLoginPassword": "Salasana", "rallyLoginLabelLogin": "Kirjaudu sisään", "rallyLoginRememberMe": "Muista kirjautumiseni", "rallyLoginButtonLogin": "KIRJAUDU SISÄÄN", "rallyAlertsMessageHeadsUpShopping": "Hei, olet käyttänyt tämän kuun ostosbudjetista {percent}.", "rallyAlertsMessageSpentOnRestaurants": "Tässä kuussa olet käyttänyt {amount} ravintoloihin.", "rallyAlertsMessageATMFees": "Tässä kuussa olet käyttänyt {amount} pankkiautomaattien maksuihin", "rallyAlertsMessageCheckingAccount": "Hienoa – käyttötilisi saldo on {percent} viime kuuta korkeampi.", "shrineMenuCaption": "VALIKKO", "shrineCategoryNameAll": "KAIKKI", "shrineCategoryNameAccessories": "ASUSTEET", "shrineCategoryNameClothing": "VAATTEET", "shrineCategoryNameHome": "KOTI", "shrineLoginUsernameLabel": "Käyttäjänimi", "shrineLoginPasswordLabel": "Salasana", "shrineCancelButtonCaption": "PERUUTA", "shrineCartTaxCaption": "Verot:", "shrineCartPageCaption": "OSTOSKORI", "shrineProductQuantity": "Määrä: {quantity}", "shrineProductPrice": "x {price}", "shrineCartItemCount": "{quantity,plural,=0{EI TUOTTEITA}=1{1 TUOTE}other{{quantity} TUOTETTA}}", "shrineCartClearButtonCaption": "TYHJENNÄ OSTOSKORI", "shrineCartTotalCaption": "YHTEENSÄ", "shrineCartSubtotalCaption": "Välisumma:", "shrineCartShippingCaption": "Toimituskulut:", "shrineProductGreySlouchTank": "Hihaton harmaa löysä paita", "shrineProductStellaSunglasses": "Stella-aurinkolasit", "shrineProductWhitePinstripeShirt": "Valkoinen liituraitapaita", "demoTextFieldWhereCanWeReachYou": "Mistä sinut saa kiinni?", "settingsTextDirectionLTR": "V-O", "settingsTextScalingLarge": "Suuri", "demoBottomSheetHeader": "Ylätunniste", "demoBottomSheetItem": "Tuote {value}", "demoBottomTextFieldsTitle": "Tekstikentät", "demoTextFieldTitle": "Tekstikentät", "demoTextFieldSubtitle": "Yksi rivi muokattavaa tekstiä ja numeroita", "demoTextFieldDescription": "Tekstikentässä käyttäjä voi lisätä käyttöliittymään tekstiä. Niitä on yleensä lomakkeissa ja valintaikkunoissa.", "demoTextFieldShowPasswordLabel": "Näytä salasana", "demoTextFieldHidePasswordLabel": "Piilota salasana", "demoTextFieldFormErrors": "Korjaa punaisena näkyvät virheet ennen lähettämistä.", "demoTextFieldNameRequired": "Nimi on pakollinen.", "demoTextFieldOnlyAlphabeticalChars": "Käytä vain aakkosia.", "demoTextFieldEnterUSPhoneNumber": "(###) ###-#### – Lisää yhdysvaltalainen puhelinnumero.", "demoTextFieldEnterPassword": "Lisää salasana.", "demoTextFieldPasswordsDoNotMatch": "Salasanat eivät ole samat", "demoTextFieldWhatDoPeopleCallYou": "Millä nimellä sinua kutsutaan?", "demoTextFieldNameField": "Nimi*", "demoBottomSheetButtonText": "NÄYTÄ ALAOSA", "demoTextFieldPhoneNumber": "Puhelinnumero*", "demoBottomSheetTitle": "Alaosa", "demoTextFieldEmail": "Sähköposti", "demoTextFieldTellUsAboutYourself": "Kerro itsestäsi (esim. mitä teet työksesi, mitä harrastat)", "demoTextFieldKeepItShort": "Älä kirjoita liikaa, tämä on pelkkä demo.", "starterAppGenericButton": "PAINIKE", "demoTextFieldLifeStory": "Elämäntarina", "demoTextFieldSalary": "Palkka", "demoTextFieldUSD": "USD", "demoTextFieldNoMoreThan": "Enintään 8 merkkiä", "demoTextFieldPassword": "Salasana*", "demoTextFieldRetypePassword": "Lisää salasana uudelleen*", "demoTextFieldSubmit": "LÄHETÄ", "demoBottomNavigationSubtitle": "Alanavigointi, näkymien ristiinhäivytys", "demoBottomSheetAddLabel": "Lisää", "demoBottomSheetModalDescription": "Modaalinen alaosa on valikon tai valintaikkunan vaihtoehto, joka estää käyttäjää toimimasta muualla sovelluksessa.", "demoBottomSheetModalTitle": "Modaalinen alaosa", "demoBottomSheetPersistentDescription": "Näkyvissä pysyvä alaosa näyttää sovelluksen pääsisältöä täydentäviä tietoja. Tällainen alaosa on näkyvissä, vaikka käyttäjä tekee jotain sovelluksen muissa osissa.", "demoBottomSheetPersistentTitle": "Näkyvissä pysyvä alaosa", "demoBottomSheetSubtitle": "Näkyvissä pysyvä tai modaalinen alaosa", "demoTextFieldNameHasPhoneNumber": "Puhelinnumero ({name}) on {phoneNumber}", "buttonText": "PAINIKE", "demoTypographyDescription": "Material Designin erilaisten typografisten tyylien määritelmät.", "demoTypographySubtitle": "Kaikki ennalta määrätyt tekstityylit", "demoTypographyTitle": "Typografia", "demoFullscreenDialogDescription": "The fullscreenDialog property specifies whether the incoming page is a fullscreen modal dialog", "demoFlatButtonDescription": "Litteä painike värjää tekstin painettaessa, mutta ei nosta painiketta. Use flat buttons on toolbars, in dialogs and inline with padding", "demoBottomNavigationDescription": "Alareunan siirtymispalkissa näytetään kolmesta viiteen kohdetta näytön alalaidassa. Joka kohteella on kuvake ja mahdollisesti myös tekstikenttä. Kun käyttäjä napauttaa alaosan navigointikuvaketta, hän siirtyy siihen liittyvään navigointisijaintiin.", "demoBottomNavigationSelectedLabel": "Valittu tunniste", "demoBottomNavigationPersistentLabels": "Näkyvissä pysyvä tunnisteet", "starterAppDrawerItem": "Tuote {value}", "demoTextFieldRequiredField": "* pakollinen kenttä", "demoBottomNavigationTitle": "Alanavigointi", "settingsLightTheme": "Vaalea", "settingsTheme": "Teema", "settingsPlatformIOS": "iOS", "settingsPlatformAndroid": "Android", "settingsTextDirectionRTL": "O-V", "settingsTextScalingHuge": "Hyvin suuri", "cupertinoButton": "Painike", "settingsTextScalingNormal": "Normaali", "settingsTextScalingSmall": "Pieni", "settingsSystemDefault": "Järjestelmä", "settingsTitle": "Asetukset", "rallyDescription": "Sovellus oman talouden hoitoon", "aboutDialogDescription": "Jos haluat nähdä tämän sovelluksen lähdekoodin, avaa {repoLink}.", "bottomNavigationCommentsTab": "Kommentit", "starterAppGenericBody": "Leipäteksti", "starterAppGenericHeadline": "Otsake", "starterAppGenericSubtitle": "Alaotsikko", "starterAppGenericTitle": "Otsikko", "starterAppTooltipSearch": "Haku", "starterAppTooltipShare": "Jaa", "starterAppTooltipFavorite": "Suosikki", "starterAppTooltipAdd": "Lisää", "bottomNavigationCalendarTab": "Kalenteri", "starterAppDescription": "Responsiivinen aloitusasettelu", "starterAppTitle": "Aloitussovellus", "aboutFlutterSamplesRepo": "Flutter-näytteiden GitHub-kirjasto", "bottomNavigationContentPlaceholder": "Paikkamerkki {title}-välilehdelle", "bottomNavigationCameraTab": "Kamera", "bottomNavigationAlarmTab": "Herätys", "bottomNavigationAccountTab": "Tili", "demoTextFieldYourEmailAddress": "Sähköpostiosoite", "demoToggleButtonDescription": "Päälle/pois-painikkeiden avulla voidaan ryhmitellä vaihtoehtoja yhteen. To emphasize groups of related toggle buttons, a group should share a common container", "colorsGrey": "HARMAA", "colorsBrown": "RUSKEA", "colorsDeepOrange": "SYVÄ ORANSSI", "colorsOrange": "ORANSSI", "colorsAmber": "KULLANRUSKEA", "colorsYellow": "KELTAINEN", "colorsLime": "LIMETINVIHREÄ", "colorsLightGreen": "VAALEANVIHREÄ", "colorsGreen": "VIHREÄ", "homeHeaderGallery": "Galleria", "homeHeaderCategories": "Luokat", "shrineDescription": "Muodin kauppapaikkasovellus", "craneDescription": "Personoitu matkasovellus", "homeCategoryReference": "TYYLIT JA MUUT", "demoInvalidURL": "URL-osoitetta ei voitu näyttää:", "demoOptionsTooltip": "Vaihtoehdot", "demoInfoTooltip": "Tietoja", "demoCodeTooltip": "Demokoodi", "demoDocumentationTooltip": "Sovellusliittymien dokumentaatio", "demoFullscreenTooltip": "Koko näyttö", "settingsTextScaling": "Tekstin skaalaus", "settingsTextDirection": "Tekstin suunta", "settingsLocale": "Kieli- ja maa-asetus", "settingsPlatformMechanics": "Alustan mekaniikka", "settingsDarkTheme": "Tumma", "settingsSlowMotion": "Hidastus", "settingsAbout": "Tietoja Flutter Gallerysta", "settingsFeedback": "Lähetä palautetta", "settingsAttribution": "Suunnittelija: TOASTER, Lontoo", "demoButtonTitle": "Painikkeet", "demoButtonSubtitle": "Teksti, koho, ääriviivallinen ja muita", "demoFlatButtonTitle": "Litteä painike", "demoRaisedButtonDescription": "Kohopainikkeet lisäävät ulottuvuutta enimmäkseen litteisiin asetteluihin. Ne korostavat toimintoja täysissä tai laajoissa tiloissa.", "demoRaisedButtonTitle": "Kohopainike", "demoOutlineButtonTitle": "Ääriviivallinen painike", "demoOutlineButtonDescription": "Ääriviivalliset painikkeet muuttuvat läpinäkyviksi ja nousevat painettaessa. They are often paired with raised buttons to indicate an alternative, secondary action.", "demoToggleButtonTitle": "Päälle/pois-painikkeet", "colorsTeal": "TURKOOSI", "demoFloatingButtonTitle": "Kelluva toimintopainike", "demoFloatingButtonDescription": "A floating action button is a circular icon button that hovers over content to promote a primary action in the application.", "demoDialogTitle": "Valintaikkunat", "demoDialogSubtitle": "Yksinkertainen, ilmoitus ja koko näyttö", "demoAlertDialogTitle": "Ilmoitus", "demoAlertDialogDescription": "Ilmoitusikkuna kertoo käyttäjälle tilanteista, jotka vaativat toimia. Ilmoitusikkunassa on valinnainen otsikko ja valinnainen toimintoluettelo.", "demoAlertTitleDialogTitle": "Otsikollinen ilmoitus", "demoSimpleDialogTitle": "Yksinkertainen", "demoSimpleDialogDescription": "Yksinkertainen valintaikkuna tarjoaa käyttäjälle mahdollisuuden valita useista vaihtoehdoista. Yksinkertaisessa valintaikkunassa on valinnainen otsikko, joka näkyy vaihtoehtojen yläpuolella.", "demoFullscreenDialogTitle": "Koko näyttö", "demoCupertinoButtonsTitle": "Painikkeet", "demoCupertinoButtonsSubtitle": "iOS-tyyliset painikkeet", "demoCupertinoButtonsDescription": "iOS-tyylinen painike. It takes in text and/or an icon that fades out and in on touch. Voi sisältää taustan.", "demoCupertinoAlertsTitle": "Ilmoitukset", "demoCupertinoAlertsSubtitle": "iOS-tyyliset ilmoitusikkunat", "demoCupertinoAlertTitle": "Ilmoitus", "demoCupertinoAlertDescription": "Ilmoitusikkuna kertoo käyttäjälle tilanteista, jotka vaativat toimia. Ilmoitusikkunassa on valinnainen otsikko, valinnainen sisältö ja valinnainen toimintoluettelo. Otsikko näkyy sisällön yläpuolella ja toiminnot sisällön alapuolella.", "demoCupertinoAlertWithTitleTitle": "Otsikollinen ilmoitus", "demoCupertinoAlertButtonsTitle": "Painikkeellinen ilmoitus", "demoCupertinoAlertButtonsOnlyTitle": "Vain ilmoituspainikkeet", "demoCupertinoActionSheetTitle": "Toimintotaulukko", "demoCupertinoActionSheetDescription": "Toimintotaulukko on tietyntyylinen ilmoitus, joka näyttää käyttäjälle vähintään kaksi vaihtoehtoa liittyen senhetkiseen kontekstiin. Toimintotaulukoissa voi olla otsikko, lisäviesti ja toimintoluettelo.", "demoColorsTitle": "Värit", "demoColorsSubtitle": "Kaikki ennalta määritetyt värit", "demoColorsDescription": "Material designin väripaletin värien ja värijoukkojen arvot.", "buttonTextEnabled": "ENABLED", "buttonTextDisabled": "DISABLED", "buttonTextCreate": "Luo", "dialogSelectedOption": "Valitsit: \"{value}\"", "dialogDiscardTitle": "Hylätäänkö luonnos?", "dialogLocationTitle": "Käytetäänkö Googlen sijaintipalvelua?", "dialogLocationDescription": "Anna Googlen auttaa sovelluksia sijainnin määrittämisessä. Googlelle lähetetään anonyymejä sijaintitietoja – myös kun sovelluksia ei ole käytössä.", "dialogCancel": "PERUUTA", "dialogDiscard": "HYLKÄÄ", "dialogDisagree": "EN HYVÄKSY", "dialogAgree": "HYVÄKSY", "dialogSetBackup": "Luo varmuuskopiointitili", "colorsBlueGrey": "SINIHARMAA", "dialogShow": "NÄYTÄ VALINTAIKKUNA", "dialogFullscreenTitle": "Koko näytön valintaikkuna", "dialogFullscreenSave": "TALLENNA", "dialogFullscreenDescription": "Koko näytön valintaikkunan esittely", "cupertinoButtonEnabled": "Enabled", "cupertinoButtonDisabled": "Disabled", "cupertinoButtonWithBackground": "Sisältää taustan", "cupertinoAlertCancel": "Peru", "cupertinoAlertDiscard": "Hylkää", "cupertinoAlertLocationTitle": "Saako Maps käyttää sijaintiasi, kun käytät sovellusta?", "cupertinoAlertLocationDescription": "Nykyinen sijaintisi näytetään kartalla ja sitä käytetään reittiohjeiden, lähistön hakutulosten ja arvioitujen matka-aikojen näyttämiseen.", "cupertinoAlertAllow": "Salli", "cupertinoAlertDontAllow": "Älä salli", "cupertinoAlertFavoriteDessert": "Valitse lempijälkiruokasi", "cupertinoAlertDessertDescription": "Valitse mieluisin jälkiruokatyyppi alla olevasta luettelosta. Valintasi avulla sinulle personoidaan suosituslista alueesi ruokapaikoista.", "cupertinoAlertCheesecake": "Juustokakku", "cupertinoAlertTiramisu": "Tiramisu", "cupertinoAlertApplePie": "Omenapiirakka", "cupertinoAlertChocolateBrownie": "Suklaabrownie", "cupertinoShowAlert": "Näytä ilmoitus", "colorsRed": "PUNAINEN", "colorsPink": "VAALEANPUNAINEN", "colorsPurple": "VIOLETTI", "colorsDeepPurple": "TUMMANVIOLETTI", "colorsIndigo": "INDIGO", "colorsBlue": "SININEN", "colorsLightBlue": "VAALEANSININEN", "colorsCyan": "SYAANI", "dialogAddAccount": "Lisää tili", "Gallery": "Galleria", "Categories": "Luokat", "SHRINE": "SHRINE", "Basic shopping app": "Shoppailun perussovellus", "RALLY": "RALLY", "CRANE": "CRANE", "Travel app": "Matkailusovellus", "MATERIAL": "MATERIAALI", "CUPERTINO": "CUPERTINO", "REFERENCE STYLES & MEDIA": "VIITETYYLIT JA ‑MEDIA" }
gallery/lib/l10n/intl_fi.arb/0
{ "file_path": "gallery/lib/l10n/intl_fi.arb", "repo_id": "gallery", "token_count": 21090 }
810
{ "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": "マテリアル デザインの期間選択ツールを含むダイアログが表示されます。", "demoDateRangePickerTitle": "期間選択ツール", "demoNavigationDrawerUserName": "ユーザー名", "demoNavigationDrawerUserEmail": "[email protected]", "demoNavigationDrawerText": "ドロワーを表示するには、画面の端からスワイプするか、左上のアイコンをタップします", "demoNavigationRailTitle": "ナビゲーション レール", "demoNavigationRailSubtitle": "アプリ内にナビゲーション レールを表示する", "demoNavigationRailDescription": "少数(通常は 3~5 個)のビュー間を移動するためにアプリの左または右に表示することを目的としたマテリアル ウィジェット。", "demoNavigationRailFirst": "1 つ目", "demoNavigationDrawerTitle": "ナビゲーション ドロワー", "demoNavigationRailThird": "3 つ目", "replyStarredLabel": "スター付き", "demoTextButtonDescription": "テキストボタンを押すと、インク スプラッシュが表示されますが、このボタンは浮き上がりません。ツールバー、ダイアログのほか、パディング入りインラインで使用されます", "demoElevatedButtonTitle": "浮き上がりボタン", "demoElevatedButtonDescription": "浮き上がりボタンを使うと、ほぼ平面のレイアウトに立体感が出ます。スペースに余裕がある場所でもない場所でも、機能が強調されます。", "demoOutlinedButtonTitle": "アウトライン ボタン", "demoOutlinedButtonDescription": "アウトライン ボタンは、押すと不透明になり、浮き上がります。通常は、浮き出しボタンと組み合わせて、代替のサブアクションを提示します。", "demoContainerTransformDemoInstructions": "カード、リスト、フローティング操作ボタン(FAB)", "demoNavigationDrawerSubtitle": "アプリバー内にドロワーを表示する", "replyDescription": "フォーカスが当てられる、効率性に優れたメールアプリ", "demoNavigationDrawerDescription": "画面の端から横方向にスライドしてアプリのナビゲーション リンクを表示するマテリアル デザイン パネル。", "replyDraftsLabel": "下書き", "demoNavigationDrawerToPageOne": "項目 1", "replyInboxLabel": "受信トレイ", "demoSharedXAxisDemoInstructions": "次へボタン、戻るボタン", "replySpamLabel": "迷惑メール", "replyTrashLabel": "ゴミ箱", "replySentLabel": "送信済み", "demoNavigationRailSecond": "2 つ目", "demoNavigationDrawerToPageTwo": "項目 2", "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": "フェード パターンは、画面の中央でフェードするダイアログなど、画面の境界内で出入りする UI 要素に使用します。", "demoFadeScaleTitle": "フェード", "demoFadeThroughTextPlaceholder": "123 枚の写真", "demoFadeThroughSearchDestination": "検索", "demoFadeThroughPhotosDestination": "写真", "demoSharedXAxisCoursePageSubtitle": "カテゴリがまとめられて、フィードにグループとして表示されます。この設定は後からいつでも変更できます。", "demoFadeThroughDescription": "フェードスルー パターンは、相互に強力な関係がない UI 要素間の移行に使用します。", "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": "コンテナ変換パターンは、コンテナを含む UI 要素間の移行に使用することを目的としています。このパターンでは、2 つの UI 要素間に表示可能な接続が作成されます。", "demoContainerTransformModalBottomSheetTitle": "フェードモード", "demoContainerTransformTypeFade": "フェード", "demoSharedYAxisAlbumTileDurationUnit": "分", "demoMotionPlaceholderTitle": "タイトル", "demoSharedXAxisForgotEmailButtonText": "メールアドレスをお忘れの場合", "demoMotionSmallPlaceholderSubtitle": "サブ", "demoMotionDetailsPageTitle": "詳細ページ", "demoMotionListTileTitle": "リストアイテム", "demoSharedAxisDescription": "軸共有パターンは、空間関係またはナビゲーション関係がある UI 要素間の変換に使用します。このパターンは、x 軸、y 軸、z 軸で共有変換を使用して要素間の関係を強化します。", "demoSharedXAxisTitle": "x 軸共有", "demoSharedXAxisBackButtonText": "戻る", "demoSharedXAxisNextButtonText": "次へ", "demoSharedXAxisCulinaryCourseTitle": "料理", "githubRepo": "{repoName} GitHub リポジトリ", "fortnightlyMenuUS": "US", "fortnightlyMenuBusiness": "ビジネス", "fortnightlyMenuScience": "科学", "fortnightlyMenuSports": "スポーツ", "fortnightlyMenuTravel": "旅行", "fortnightlyMenuCulture": "カルチャー", "fortnightlyTrendingTechDesign": "TechDesign", "rallyBudgetDetailAmountLeft": "残額", "fortnightlyHeadlineArmy": "Green Army の内部改革", "fortnightlyDescription": "コンテンツ中心のニュースアプリ", "rallyBillDetailAmountDue": "未払い額", "rallyBudgetDetailTotalCap": "合計金額", "rallyBudgetDetailAmountUsed": "使用量", "fortnightlyTrendingHealthcareRevolution": "HealthcareRevolution", "fortnightlyMenuFrontPage": "トップページ", "fortnightlyMenuWorld": "世界", "rallyBillDetailAmountPaid": "支払い額", "fortnightlyMenuPolitics": "政治", "fortnightlyHeadlineBees": "農場のハチが不足", "fortnightlyHeadlineGasoline": "ガソリンの未来", "fortnightlyTrendingGreenArmy": "GreenArmy", "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": "ナトリウム(mg)", "demoTimePickerTitle": "時刻選択ツール", "demo2dTransformationsResetTooltip": "変換をリセット", "dataTableColumnFat": "脂肪(g)", "dataTableColumnCalories": "カロリー", "dataTableColumnDessert": "デザート(1 人分)", "cardsDemoTravelDestinationLocation1": "タンジャーヴール、タミルナードゥ州", "demoTimePickerDescription": "マテリアル デザインの時刻選択ツールを含むダイアログが表示されます。", "demoPickersShowPicker": "選択ツールを表示", "demoTabsScrollingTitle": "スクロール可", "demoTabsNonScrollingTitle": "スクロール不可", "craneHours": "{hours,plural,=1{1h}other{{hours}h}}", "craneMinutes": "{minutes,plural,=1{1m}other{{minutes}m}}", "craneFlightDuration": "{hoursShortForm}{minutesShortForm}", "dataTableHeader": "栄養", "demoDatePickerTitle": "日付選択ツール", "demoPickersSubtitle": "日付と時刻の選択", "demoPickersTitle": "選択ツール", "demo2dTransformationsEditTooltip": "タイルを編集", "demoDataTableDescription": "データテーブルには、行と列のグリッドのような形式で情報が表示されます。スキャンしやすいように情報が編成されているため、ユーザーはパターンやインサイトを探すことができます。", "demo2dTransformationsDescription": "タイルを編集するにはタップし、シーンを移動するにはジェスチャーを使用します。パン、ピンチ操作、ズーム、回転するには、2 本の指でドラッグします。最初の向きに戻すには、リセットボタンを押します。", "demo2dTransformationsSubtitle": "パン、ズーム、回転", "demo2dTransformationsTitle": "2D 変換", "demoCupertinoTextFieldPIN": "PIN", "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": "タンパク質(g)", "cardsDemoTravelDestinationTitle2": "南インドのアーティスト", "cardsDemoTravelDestinationDescription2": "絹糸紡績", "bannerDemoText": "お使いの他のデバイスでパスワードが更新されました。もう一度ログインしてください。", "cardsDemoTravelDestinationLocation2": "シヴァガンガイ、タミルナードゥ州", "cardsDemoTravelDestinationTitle3": "ブリハディーシュヴァラ寺院", "cardsDemoTravelDestinationDescription3": "寺院", "demoBannerTitle": "バナー", "demoBannerSubtitle": "リスト内にバナーを表示します", "demoBannerDescription": "バナーでは、重要なメッセージを簡潔に表示し、ユーザーが対応する(またはバナーを閉じる)アクションを提供します。バナーを閉じるには、ユーザーのアクションが必要です。", "demoCardTitle": "カード", "demoCardSubtitle": "角に丸みがある基本カード", "demoCardDescription": "カードは、アルバム、地理的位置、食事、連絡先の詳細など、いくつかの関連する情報を表す場合に使用するマテリアルのシートです。", "demoDataTableTitle": "データテーブル", "demoDataTableSubtitle": "情報の行と列", "dataTableColumnCarbs": "炭水化物(g)", "placeTanjore": "タンジョール", "demoGridListsTitle": "グリッドリスト", "placeFlowerMarket": "フラワー マーケット", "placeBronzeWorks": "ブロンズ作品", "placeMarket": "マーケット", "placeThanjavurTemple": "タンジャーヴール寺院", "placeSaltFarm": "塩田", "placeScooters": "スクーター", "placeSilkMaker": "絹織物の製作", "placeLunchPrep": "ランチの準備", "placeBeach": "ビーチ", "placeFisherman": "漁師", "demoMenuSelected": "選択: {value}", "demoMenuRemove": "削除", "demoMenuGetLink": "リンクを取得", "demoMenuShare": "共有", "demoBottomAppBarSubtitle": "下部にナビゲーションとアクションが表示されます", "demoMenuAnItemWithASectionedMenu": "セクション分割メニュー付きの項目", "demoMenuADisabledMenuItem": "無効なメニュー項目", "demoLinearProgressIndicatorTitle": "線形進行状況インジケーター", "demoMenuContextMenuItemOne": "コンテキスト メニュー項目 1", "demoMenuAnItemWithASimpleMenu": "シンプル メニュー付きの項目", "demoCustomSlidersTitle": "カスタム スライダー", "demoMenuAnItemWithAChecklistMenu": "チェックリスト メニュー付きの項目", "demoCupertinoActivityIndicatorTitle": "アクティビティ インジケーター", "demoCupertinoActivityIndicatorSubtitle": "iOS スタイルのアクティビティ インジケーター", "demoCupertinoActivityIndicatorDescription": "時計回りにくるくる回る iOS スタイルのアクティビティ インジケーター。", "demoCupertinoNavigationBarTitle": "ナビゲーション バー", "demoCupertinoNavigationBarSubtitle": "iOS スタイルのナビゲーション バー", "demoCupertinoNavigationBarDescription": "iOS スタイルのナビゲーション バーです。ナビゲーション バーは、ページタイトルを最小限含むツールバーです(ページタイトルはツールバーの中央に表示されます)。", "demoCupertinoPullToRefreshTitle": "下方向にスワイプして更新", "demoCupertinoPullToRefreshSubtitle": "iOS スタイルの「下にスワイプして更新」コントロール", "demoCupertinoPullToRefreshDescription": "iOS スタイルの「下にスワイプしてコンテンツを更新」コントロールを実装するウィジェットです。", "demoProgressIndicatorTitle": "進行状況インジケーター", "demoProgressIndicatorSubtitle": "線形、円形、不確定", "demoCircularProgressIndicatorTitle": "円形進行状況インジケーター", "demoCircularProgressIndicatorDescription": "くるくる回ることでアプリがビジー状態であることを示す、マテリアル デザインの円形進行状況インジケーター。", "demoMenuFour": "4", "demoLinearProgressIndicatorDescription": "マテリアル デザインの線形進行状況インジケーター。進行状況バーとも呼ばれます。", "demoTooltipTitle": "ツールチップ", "demoTooltipSubtitle": "長押しするかカーソルを合わせると表示される短いメッセージ", "demoTooltipDescription": "ツールチップでは、ボタンやその他のユーザー インターフェース アクションの機能を紹介するテキストラベルが提供されます。ユーザーが要素にカーソルを合わせたり、フォーカスを置いたり、要素を長押ししたりすると、ツールチップに情報メッセージが表示されます。", "demoTooltipInstructions": "長押しするかカーソルを合わせると、ツールチップが表示されます。", "placeChennai": "チェンナイ", "demoMenuChecked": "オン: {value}", "placeChettinad": "チェティナード", "demoMenuPreview": "プレビュー", "demoBottomAppBarTitle": "ボトム アプリバー", "demoBottomAppBarDescription": "ボトム アプリバーでは、ボトム ナビゲーション ドロワーと、フローティング アクション ボタンなど最大 4 つのアクションにアクセスできます。", "bottomAppBarNotch": "ノッチ", "bottomAppBarPosition": "フローティング アクション ボタンの位置", "bottomAppBarPositionDockedEnd": "固定 - 端", "bottomAppBarPositionDockedCenter": "固定 - 中央", "bottomAppBarPositionFloatingEnd": "フローティング - 端", "bottomAppBarPositionFloatingCenter": "フローティング - 中央", "demoSlidersEditableNumericalValue": "編集可能な数値", "demoGridListsSubtitle": "行と列のレイアウト", "demoGridListsDescription": "グリッドリストは、同種のデータ(一般的には画像)を表す場合に最適です。グリッドリスト内の各項目をタイルと言います。", "demoGridListsImageOnlyTitle": "画像のみ", "demoGridListsHeaderTitle": "ヘッダーあり", "demoGridListsFooterTitle": "フッターあり", "demoSlidersTitle": "スライダー", "demoSlidersSubtitle": "スワイプで値を選択するためのウィジェット", "demoSlidersDescription": "スライダーはバー上の値の範囲を表すもので、ユーザーはスライダーから 1 つの値を選択できます。音量、明るさなどの設定を調整したり、画像フィルタを適用したりするのに最適です。", "demoRangeSlidersTitle": "範囲スライダー", "demoRangeSlidersDescription": "スライダーはバー上の値の範囲を表すものです。スライダーには、バーの両端に値の範囲を表すアイコンを付けることができます。音量、明るさなどの設定を調整したり、画像フィルタを適用したりするのに最適です。", "demoMenuAnItemWithAContextMenuButton": "コンテキスト メニュー付きの項目", "demoCustomSlidersDescription": "スライダーはバー上の値の範囲を表すもので、ユーザーはスライダーから 1 つの値または値の範囲を選択できます。テーマを設定したりカスタマイズしたりできます。", "demoSlidersContinuousWithEditableNumericalValue": "編集可能な数値の連続", "demoSlidersDiscrete": "非連続", "demoSlidersDiscreteSliderWithCustomTheme": "カスタムテーマが設定された非連続スライダー", "demoSlidersContinuousRangeSliderWithCustomTheme": "カスタムテーマが設定された連続範囲スライダー", "demoSlidersContinuous": "連続", "placePondicherry": "ポンディシェリ", "demoMenuTitle": "メニュー", "demoContextMenuTitle": "コンテキスト メニュー", "demoSectionedMenuTitle": "セクション分割メニュー", "demoSimpleMenuTitle": "シンプル メニュー", "demoChecklistMenuTitle": "チェックリスト メニュー", "demoMenuSubtitle": "メニューボタンとシンプル メニュー", "demoMenuDescription": "メニューでは、一時的なサーフェス上に選択肢の一覧が表示されます。ユーザーがボタン、アクション、その他のコントロールを操作すると表示されます。", "demoMenuItemValueOne": "メニュー項目 1", "demoMenuItemValueTwo": "メニュー項目 2", "demoMenuItemValueThree": "メニュー項目 3", "demoMenuOne": "1", "demoMenuTwo": "2", "demoMenuThree": "3", "demoMenuContextMenuItemThree": "コンテキスト メニュー項目 3", "demoCupertinoSwitchSubtitle": "iOS スタイルのスイッチ", "demoSnackbarsText": "これがスナックバーです。", "demoCupertinoSliderSubtitle": "iOS スタイルのスライダー", "demoCupertinoSliderDescription": "スライダーでは、連続する値の集合または不連続な値の集合から値を選択できます。", "demoCupertinoSliderContinuous": "連続: {value}", "demoCupertinoSliderDiscrete": "不連続: {value}", "demoSnackbarsAction": "スナックバーのアクションを押しました。", "backToGallery": "ギャラリーに戻る", "demoCupertinoTabBarTitle": "タブバー", "demoCupertinoSwitchDescription": "スイッチでは、1 つの設定のオン / オフ状態を切り替えることができます。", "demoSnackbarsActionButtonLabel": "アクション", "cupertinoTabBarProfileTab": "プロフィール", "demoSnackbarsButtonLabel": "スナックバーを表示", "demoSnackbarsDescription": "スナックバーを使用して、アプリが実行したまたはこれから実行するプロセスをユーザーに伝えます。スナックバーは画面の下部に一時的に表示されるため、ユーザーの操作性を妨げることがありません。また、削除するためのユーザーの入力操作も必要ありません。", "demoSnackbarsSubtitle": "スナックバーでは、画面の下部にメッセージが表示されます", "demoSnackbarsTitle": "スナックバー", "demoCupertinoSliderTitle": "スライダー", "cupertinoTabBarChatTab": "チャット", "cupertinoTabBarHomeTab": "ホーム", "demoCupertinoTabBarDescription": "iOS スタイルのボトム ナビゲーション タブバーには複数のタブが表示され、そのうちの 1 つのタブ(デフォルトでは最初のタブ)がアクティブになります。", "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": "チェックボックスでは、ユーザーが選択肢のセットから複数の項目を選択できます。通常のチェックボックスの値は True または False で、3 状態のチェックボックスの値は Null になることもあります。", "settingsButtonLabel": "設定", "demoListsTitle": "リスト", "demoListsSubtitle": "リスト レイアウトのスクロール", "demoListsDescription": "通常、高さが固定された 1 行には、テキストとその前後のアイコンが含まれます。", "demoOneLineListsTitle": "1 行", "demoTwoLineListsTitle": "2 行", "demoListsSecondary": "サブテキスト", "demoSelectionControlsTitle": "選択コントロール", "craneFly7SemanticLabel": "ラシュモア山", "demoSelectionControlsCheckboxTitle": "チェックボックス", "craneSleep3SemanticLabel": "青いクラシック カーに寄りかかる男性", "demoSelectionControlsRadioTitle": "ラジオ", "demoSelectionControlsRadioDescription": "ラジオボタンでは、ユーザーが選択肢のセットから 1 つ選択できます。すべての選択肢を並べて、その中からユーザーが 1 つだけ選べるようにする場合は、ラジオボタンを使用します。", "demoSelectionControlsSwitchTitle": "スイッチ", "demoSelectionControlsSwitchDescription": "オンとオフのスイッチでは、1 つの設定の状態を切り替えることができます。スイッチでコントロールする設定とその状態は、対応するインライン ラベルと明確に区別する必要があります。", "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": "アクション チップは、メイン コンテンツに関連するアクションをトリガーするオプションの集合です。アクション チップは UI にコンテキストに基づいて動的に表示されます。", "demoChoiceChipTitle": "選択チップ", "demoChoiceChipDescription": "選択チップは、集合からの 1 つの選択肢を表すものです。選択チップには、関連する説明テキストまたはカテゴリが含まれます。", "demoFilterChipTitle": "フィルタチップ", "demoFilterChipDescription": "フィルタチップは、コンテンツをフィルタする方法としてタグやキーワードを使用します。", "demoInputChipTitle": "入力チップ", "demoInputChipDescription": "入力チップは、エンティティ(人、場所、アイテムなど)や会話テキストなどの複雑な情報をコンパクトな形式で表すものです。", "craneSleep9": "リスボン(ポルトガル)", "craneEat10": "リスボン(ポルトガル)", "demoCupertinoSegmentedControlDescription": "相互に排他的な複数のオプションから選択する場合に使用します。セグメンテッド コントロール内の 1 つのオプションが選択されると、そのセグメンテッド コントロール内の他のオプションは選択されなくなります。", "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": "バガボンド サック", "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": "T シャツ(ファイン ラインズ)", "rallyAccountDataHomeSavings": "マイホーム貯金", "rallyAccountDataChecking": "当座預金", "rallyAccountDetailDataInterestPaidLastYear": "昨年の利息", "rallyAccountDetailDataNextStatement": "次回の取引明細書発行日", "rallyAccountDetailDataAccountOwner": "口座所有者", "rallyBudgetCategoryCoffeeShops": "カフェ", "rallyBudgetCategoryGroceries": "食料品", "shrineProductCeriseScallopTee": "T シャツ(セリーズ スカロップ)", "rallyBudgetCategoryClothing": "衣料品", "rallySettingsManageAccounts": "口座を管理", "rallyAccountDataCarSavings": "マイカー貯金", "rallySettingsTaxDocuments": "税務書類", "rallySettingsPasscodeAndTouchId": "パスコードと Touch ID", "rallySettingsNotifications": "通知", "rallySettingsPersonalInformation": "個人情報", "rallySettingsPaperlessSettings": "ペーパーレスの設定", "rallySettingsFindAtms": "ATM を探す", "rallySettingsHelp": "ヘルプ", "rallySettingsSignOut": "ログアウト", "rallyAccountTotal": "合計", "rallyBillsDue": "期限", "rallyBudgetLeft": "残", "rallyAccounts": "口座", "rallyBills": "請求", "rallyBudgets": "予算", "rallyAlerts": "アラート", "rallySeeAll": "すべて表示", "rallyFinanceLeft": "残", "rallyTitleOverview": "概要", "shrineProductShoulderRollsTee": "T シャツ(ショルダー ロール)", "shrineNextButtonCaption": "次へ", "rallyTitleBudgets": "予算", "rallyTitleSettings": "設定", "rallyLoginLoginToRally": "Rally にログイン", "rallyLoginNoAccount": "口座を開設する", "rallyLoginSignUp": "登録", "rallyLoginUsername": "ユーザー名", "rallyLoginPassword": "パスワード", "rallyLoginLabelLogin": "ログイン", "rallyLoginRememberMe": "次回から入力を省略する", "rallyLoginButtonLogin": "ログイン", "rallyAlertsMessageHeadsUpShopping": "今月のショッピング予算の {percent} を使いました。", "rallyAlertsMessageSpentOnRestaurants": "今週はレストランに {amount}使いました。", "rallyAlertsMessageATMFees": "今月は ATM 手数料に {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": "LTR", "settingsTextScalingLarge": "大", "demoBottomSheetHeader": "ヘッダー", "demoBottomSheetItem": "項目 {value}", "demoBottomTextFieldsTitle": "テキスト欄", "demoTextFieldTitle": "テキスト欄", "demoTextFieldSubtitle": "1 行(編集可能な文字と数字)", "demoTextFieldDescription": "テキスト欄では、ユーザーが UI にテキストを入力できます。一般にフォームやダイアログで表示されます。", "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": "マテリアル デザインにあるさまざまな字体の定義です。", "demoTypographySubtitle": "定義済みテキスト スタイルすべて", "demoTypographyTitle": "タイポグラフィ", "demoFullscreenDialogDescription": "fullscreenDialog プロパティで、着信ページが全画面モード ダイアログかどうかを指定します", "demoFlatButtonDescription": "フラットボタンを押すと、インク スプラッシュが表示されますが、このボタンは浮き上がりません。ツールバー、ダイアログのほか、パディング入りインラインで使用されます", "demoBottomNavigationDescription": "画面の下部には、ボトム ナビゲーション バーに 3~5 件の移動先が表示されます。各移動先はアイコンとテキストラベル(省略可)で表されます。ボトム ナビゲーション アイコンをタップすると、そのアイコンに関連付けられた移動先のトップレベルに移動します。", "demoBottomNavigationSelectedLabel": "選択済みのラベル", "demoBottomNavigationPersistentLabels": "永続ラベル", "starterAppDrawerItem": "項目 {value}", "demoTextFieldRequiredField": "* は必須項目です", "demoBottomNavigationTitle": "ボトム ナビゲーション", "settingsLightTheme": "ライト", "settingsTheme": "テーマ", "settingsPlatformIOS": "iOS", "settingsPlatformAndroid": "Android", "settingsTextDirectionRTL": "RTL", "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": "切り替えボタンでは、関連するオプションを 1 つのグループにまとめることができます。関連する切り替えボタンのグループを強調するには、グループが共通コンテナを共有する必要があります", "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 ギャラリーについて", "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": "アクション シートは、現在のコンテキストに関連する 2 つ以上の選択肢の集合をユーザーに提示する特定のスタイルのアラートです。タイトル、追加メッセージ、アクション リストを設定できます。", "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": "クパチーノ", "REFERENCE STYLES & MEDIA": "リファレンス スタイルとメディア" }
gallery/lib/l10n/intl_ja.arb/0
{ "file_path": "gallery/lib/l10n/intl_ja.arb", "repo_id": "gallery", "token_count": 24528 }
811