common.dart 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:math';
  4. import 'package:back_button_interceptor/back_button_interceptor.dart';
  5. import 'package:desktop_multi_window/desktop_multi_window.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:flutter/gestures.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:flutter/services.dart';
  10. import 'package:flutter_hbb/common/formatter/id_formatter.dart';
  11. import 'package:flutter_hbb/desktop/widgets/refresh_wrapper.dart';
  12. import 'package:flutter_hbb/desktop/widgets/tabbar_widget.dart';
  13. import 'package:flutter_hbb/main.dart';
  14. import 'package:flutter_hbb/models/peer_model.dart';
  15. import 'package:flutter_hbb/models/state_model.dart';
  16. import 'package:flutter_hbb/utils/multi_window_manager.dart';
  17. import 'package:flutter_hbb/utils/platform_channel.dart';
  18. import 'package:flutter_svg/flutter_svg.dart';
  19. import 'package:get/get.dart';
  20. import 'package:provider/provider.dart';
  21. import 'package:uni_links/uni_links.dart';
  22. import 'package:url_launcher/url_launcher.dart';
  23. import 'package:uuid/uuid.dart';
  24. import 'package:window_manager/window_manager.dart';
  25. import 'package:window_size/window_size.dart' as window_size;
  26. import '../consts.dart';
  27. import 'common/widgets/overlay.dart';
  28. import 'mobile/pages/file_manager_page.dart';
  29. import 'mobile/pages/remote_page.dart';
  30. import 'desktop/pages/remote_page.dart' as desktop_remote;
  31. import 'desktop/pages/file_manager_page.dart' as desktop_file_manager;
  32. import 'package:flutter_hbb/desktop/widgets/remote_toolbar.dart';
  33. import 'models/model.dart';
  34. import 'models/platform_model.dart';
  35. import 'package:flutter_hbb/native/win32.dart'
  36. if (dart.library.html) 'package:flutter_hbb/web/win32.dart';
  37. import 'package:flutter_hbb/native/common.dart'
  38. if (dart.library.html) 'package:flutter_hbb/web/common.dart';
  39. final globalKey = GlobalKey<NavigatorState>();
  40. final navigationBarKey = GlobalKey();
  41. final isAndroid = isAndroid_;
  42. final isIOS = isIOS_;
  43. final isWindows = isWindows_;
  44. final isMacOS = isMacOS_;
  45. final isLinux = isLinux_;
  46. final isDesktop = isDesktop_;
  47. final isWeb = isWeb_;
  48. final isWebDesktop = isWebDesktop_;
  49. final isWebOnWindows = isWebOnWindows_;
  50. final isWebOnLinux = isWebOnLinux_;
  51. final isWebOnMacOs = isWebOnMacOS_;
  52. var isMobile = isAndroid || isIOS;
  53. var version = '';
  54. int androidVersion = 0;
  55. // Only used on Linux.
  56. // `windowManager.setResizable(false)` will reset the window size to the default size on Linux.
  57. // https://stackoverflow.com/questions/8193613/gtk-window-resize-disable-without-going-back-to-default
  58. // So we need to use this flag to enable/disable resizable.
  59. bool _linuxWindowResizable = true;
  60. /// only available for Windows target
  61. int windowsBuildNumber = 0;
  62. DesktopType? desktopType;
  63. bool get isMainDesktopWindow =>
  64. desktopType == DesktopType.main || desktopType == DesktopType.cm;
  65. String get screenInfo => screenInfo_;
  66. /// Check if the app is running with single view mode.
  67. bool isSingleViewApp() {
  68. return desktopType == DesktopType.cm;
  69. }
  70. /// * debug or test only, DO NOT enable in release build
  71. bool isTest = false;
  72. typedef F = String Function(String);
  73. typedef FMethod = String Function(String, dynamic);
  74. typedef StreamEventHandler = Future<void> Function(Map<String, dynamic>);
  75. typedef SessionID = UuidValue;
  76. final iconHardDrive = MemoryImage(Uint8List.fromList(base64Decode(
  77. 'iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAmVBMVEUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAjHWqVAAAAMnRSTlMAv0BmzLJNXlhiUu2fxXDgu7WuSUUe29LJvpqUjX53VTstD7ilNujCqTEk5IYH+vEoFjKvAagAAAPpSURBVHja7d0JbhpBEIXhB3jYzb5vBgzYgO04df/DJXGUKMwU9ECmZ6pQfSfw028LCXW3YYwxxhhjjDHGGGOM0eZ9VV1MckdKWLM1bRQ/35GW/WxHHu1me6ShuyHvNl34VhlTKsYVeDWj1EzgUZ1S1DrAk/UDparZgxd9Sl0BHnxSBhpI3jfKQG2FpLUpE69I2ILikv1nsvygjBwPSNKYMlNHggqUoSKS80AZCnwHqQ1zCRvW+CRegwRFeFAMKKrtM8gTPJlzSfwFgT9dJom3IDN4VGaSeAryAK8m0SSeghTg1ZYiql6CjBDhO8mzlyAVhKhIwgXxrh5NojGIhyRckEdwpCdhgpSQgiWTRGMQNonGIGySp0SDvMDBX5KWxiB8Eo1BgE00SYJBykhNnkmSWJAcLpGaJNMgfJKyxiDAK4WNEwryhMtkJsk8CJtEYxA+icYgQIfCcgkEqcJNXhIRQdgkGoPwSTQG+e8khdu/7JOVREwQIKCwF41B2CQljUH4JLcH6SI+OUlEBQHa0SQag/BJNAbhkjxqDMIn0RgEeI4muSlID9eSkERgEKAVTaIxCJ9EYxA2ydVB8hCASVLRGAQYR5NoDMIn0RgEyFHYSGMQPonGII4kziCNvBgNJonEk4u3GAk8Sprk6eYaqbMDY0oKvUm5jfC/viGiSypV7+M3i2iDsAGpNEDYjlTa3W8RdR/r544g50ilnA0RxoZIE2NIXqQbhkAkGyKNDZHGhkhjQ6SxIdLYEGlsiDQ2JGTVeD0264U9zipPh7XOooffpA6pfNCXjxl4/c3pUzlChwzor53zwYYVfpI5pOV6LWFF/2jiJ5FDSs5jdY/0rwUAkUMeXWdBqnSqD0DikBqdqCHsjTvELm9In0IOri/0pwAEDtlSyNaRjAIAAoesKWTtuusxByBwCJp0oomwBXcYUuCQgE50ENajE4OvZAKHLB1/68Br5NqiyCGYOY8YRd77kTkEb64n7lZN+mOIX4QOwb5FX0ZVx3uOxwW+SB0CbBubemWP8/rlaaeRX+M3uUOuZENsiA25zIbYkPsZElBIHwL13U/PTjJ/cyOOEoVM3I+hziDQlELm7pPxw3eI8/7gPh1fpLA6xGnEeDDgO0UcIAzzM35HxLPIq5SXe9BLzOsj9eUaQqyXzxS1QFSfWM2cCANiHcAISJ0AnCKpUwTuIkkA3EeSInAXSQKcs1V18e24wlllUmQp9v9zXKeHi+akRAMOPVKhAqdPBZeUmnnEsO6QcJ0+4qmOSbBxFfGVRiTUqITrdKcCbyYO3/K4wX4+aQ+FfNjXhu3JfAVjjDHGGGOMMcYYY4xIPwCgfqT6TbhCLAAAAABJRU5ErkJggg==')));
  78. enum DesktopType {
  79. main,
  80. remote,
  81. fileTransfer,
  82. cm,
  83. portForward,
  84. }
  85. class IconFont {
  86. static const _family1 = 'Tabbar';
  87. static const _family2 = 'PeerSearchbar';
  88. IconFont._();
  89. static const IconData max = IconData(0xe606, fontFamily: _family1);
  90. static const IconData restore = IconData(0xe607, fontFamily: _family1);
  91. static const IconData close = IconData(0xe668, fontFamily: _family1);
  92. static const IconData min = IconData(0xe609, fontFamily: _family1);
  93. static const IconData add = IconData(0xe664, fontFamily: _family1);
  94. static const IconData menu = IconData(0xe628, fontFamily: _family1);
  95. static const IconData search = IconData(0xe6a4, fontFamily: _family2);
  96. static const IconData roundClose = IconData(0xe6ed, fontFamily: _family2);
  97. static const IconData addressBook =
  98. IconData(0xe602, fontFamily: "AddressBook");
  99. }
  100. class ColorThemeExtension extends ThemeExtension<ColorThemeExtension> {
  101. const ColorThemeExtension({
  102. required this.border,
  103. required this.border2,
  104. required this.border3,
  105. required this.highlight,
  106. required this.drag_indicator,
  107. required this.shadow,
  108. required this.errorBannerBg,
  109. required this.me,
  110. required this.toastBg,
  111. required this.toastText,
  112. required this.divider,
  113. });
  114. final Color? border;
  115. final Color? border2;
  116. final Color? border3;
  117. final Color? highlight;
  118. final Color? drag_indicator;
  119. final Color? shadow;
  120. final Color? errorBannerBg;
  121. final Color? me;
  122. final Color? toastBg;
  123. final Color? toastText;
  124. final Color? divider;
  125. static final light = ColorThemeExtension(
  126. border: Color(0xFFCCCCCC),
  127. border2: Color(0xFFBBBBBB),
  128. border3: Colors.black26,
  129. highlight: Color(0xFFE5E5E5),
  130. drag_indicator: Colors.grey[800],
  131. shadow: Colors.black,
  132. errorBannerBg: Color(0xFFFDEEEB),
  133. me: Colors.green,
  134. toastBg: Colors.black.withOpacity(0.6),
  135. toastText: Colors.white,
  136. divider: Colors.black38,
  137. );
  138. static final dark = ColorThemeExtension(
  139. border: Color(0xFF555555),
  140. border2: Color(0xFFE5E5E5),
  141. border3: Colors.white24,
  142. highlight: Color(0xFF3F3F3F),
  143. drag_indicator: Colors.grey,
  144. shadow: Colors.grey,
  145. errorBannerBg: Color(0xFF470F2D),
  146. me: Colors.greenAccent,
  147. toastBg: Colors.white.withOpacity(0.6),
  148. toastText: Colors.black,
  149. divider: Colors.white38,
  150. );
  151. @override
  152. ThemeExtension<ColorThemeExtension> copyWith({
  153. Color? border,
  154. Color? border2,
  155. Color? border3,
  156. Color? highlight,
  157. Color? drag_indicator,
  158. Color? shadow,
  159. Color? errorBannerBg,
  160. Color? me,
  161. Color? toastBg,
  162. Color? toastText,
  163. Color? divider,
  164. }) {
  165. return ColorThemeExtension(
  166. border: border ?? this.border,
  167. border2: border2 ?? this.border2,
  168. border3: border3 ?? this.border3,
  169. highlight: highlight ?? this.highlight,
  170. drag_indicator: drag_indicator ?? this.drag_indicator,
  171. shadow: shadow ?? this.shadow,
  172. errorBannerBg: errorBannerBg ?? this.errorBannerBg,
  173. me: me ?? this.me,
  174. toastBg: toastBg ?? this.toastBg,
  175. toastText: toastText ?? this.toastText,
  176. divider: divider ?? this.divider,
  177. );
  178. }
  179. @override
  180. ThemeExtension<ColorThemeExtension> lerp(
  181. ThemeExtension<ColorThemeExtension>? other, double t) {
  182. if (other is! ColorThemeExtension) {
  183. return this;
  184. }
  185. return ColorThemeExtension(
  186. border: Color.lerp(border, other.border, t),
  187. border2: Color.lerp(border2, other.border2, t),
  188. border3: Color.lerp(border3, other.border3, t),
  189. highlight: Color.lerp(highlight, other.highlight, t),
  190. drag_indicator: Color.lerp(drag_indicator, other.drag_indicator, t),
  191. shadow: Color.lerp(shadow, other.shadow, t),
  192. errorBannerBg: Color.lerp(shadow, other.errorBannerBg, t),
  193. me: Color.lerp(shadow, other.me, t),
  194. toastBg: Color.lerp(shadow, other.toastBg, t),
  195. toastText: Color.lerp(shadow, other.toastText, t),
  196. divider: Color.lerp(shadow, other.divider, t),
  197. );
  198. }
  199. }
  200. class MyTheme {
  201. MyTheme._();
  202. static const Color grayBg = Color(0xFFEFEFF2);
  203. static const Color accent = Color(0xFF0071FF);
  204. static const Color accent50 = Color(0x770071FF);
  205. static const Color accent80 = Color(0xAA0071FF);
  206. static const Color canvasColor = Color(0xFF212121);
  207. static const Color border = Color(0xFFCCCCCC);
  208. static const Color idColor = Color(0xFF00B6F0);
  209. static const Color darkGray = Color.fromARGB(255, 148, 148, 148);
  210. static const Color cmIdColor = Color(0xFF21790B);
  211. static const Color dark = Colors.black87;
  212. static const Color button = Color(0xFF2C8CFF);
  213. static const Color hoverBorder = Color(0xFF999999);
  214. // ListTile
  215. static const ListTileThemeData listTileTheme = ListTileThemeData(
  216. shape: RoundedRectangleBorder(
  217. borderRadius: BorderRadius.all(
  218. Radius.circular(5),
  219. ),
  220. ),
  221. );
  222. static SwitchThemeData switchTheme() {
  223. return SwitchThemeData(
  224. splashRadius: (isDesktop || isWebDesktop) ? 0 : kRadialReactionRadius);
  225. }
  226. static RadioThemeData radioTheme() {
  227. return RadioThemeData(
  228. splashRadius: (isDesktop || isWebDesktop) ? 0 : kRadialReactionRadius);
  229. }
  230. // Checkbox
  231. static const CheckboxThemeData checkboxTheme = CheckboxThemeData(
  232. splashRadius: 0,
  233. shape: RoundedRectangleBorder(
  234. borderRadius: BorderRadius.all(
  235. Radius.circular(5),
  236. ),
  237. ),
  238. );
  239. // TextButton
  240. // Value is used to calculate "dialog.actionsPadding"
  241. static const double mobileTextButtonPaddingLR = 20;
  242. // TextButton on mobile needs a fixed padding, otherwise small buttons
  243. // like "OK" has a larger left/right padding.
  244. static TextButtonThemeData mobileTextButtonTheme = TextButtonThemeData(
  245. style: TextButton.styleFrom(
  246. padding: EdgeInsets.symmetric(horizontal: mobileTextButtonPaddingLR),
  247. shape: RoundedRectangleBorder(
  248. borderRadius: BorderRadius.circular(8.0),
  249. ),
  250. ),
  251. );
  252. //tooltip
  253. static TooltipThemeData tooltipTheme() {
  254. return TooltipThemeData(
  255. waitDuration: Duration(seconds: 1, milliseconds: 500),
  256. );
  257. }
  258. // Dialogs
  259. static const double dialogPadding = 24;
  260. // padding bottom depends on content (some dialogs has no content)
  261. static EdgeInsets dialogTitlePadding({bool content = true}) {
  262. final double p = dialogPadding;
  263. return EdgeInsets.fromLTRB(p, p, p, content ? 0 : p);
  264. }
  265. // padding bottom depends on actions (mobile has dialogs without actions)
  266. static EdgeInsets dialogContentPadding({bool actions = true}) {
  267. final double p = dialogPadding;
  268. return (isDesktop || isWebDesktop)
  269. ? EdgeInsets.fromLTRB(p, p, p, actions ? (p - 4) : p)
  270. : EdgeInsets.fromLTRB(p, p, p, actions ? (p / 2) : p);
  271. }
  272. static EdgeInsets dialogActionsPadding() {
  273. final double p = dialogPadding;
  274. return (isDesktop || isWebDesktop)
  275. ? EdgeInsets.fromLTRB(p, 0, p, (p - 4))
  276. : EdgeInsets.fromLTRB(p, 0, (p - mobileTextButtonPaddingLR), (p / 2));
  277. }
  278. static EdgeInsets dialogButtonPadding = (isDesktop || isWebDesktop)
  279. ? EdgeInsets.only(left: dialogPadding)
  280. : EdgeInsets.only(left: dialogPadding / 3);
  281. static ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(
  282. thickness: MaterialStateProperty.all(6),
  283. thumbColor: MaterialStateProperty.resolveWith<Color?>((states) {
  284. if (states.contains(MaterialState.dragged)) {
  285. return Colors.grey[900];
  286. } else if (states.contains(MaterialState.hovered)) {
  287. return Colors.grey[700];
  288. } else {
  289. return Colors.grey[500];
  290. }
  291. }),
  292. crossAxisMargin: 4,
  293. );
  294. static ScrollbarThemeData scrollbarThemeDark = scrollbarTheme.copyWith(
  295. thumbColor: MaterialStateProperty.resolveWith<Color?>((states) {
  296. if (states.contains(MaterialState.dragged)) {
  297. return Colors.grey[100];
  298. } else if (states.contains(MaterialState.hovered)) {
  299. return Colors.grey[300];
  300. } else {
  301. return Colors.grey[500];
  302. }
  303. }),
  304. );
  305. static ThemeData lightTheme = ThemeData(
  306. // https://stackoverflow.com/questions/77537315/after-upgrading-to-flutter-3-16-the-app-bar-background-color-button-size-and
  307. useMaterial3: false,
  308. brightness: Brightness.light,
  309. hoverColor: Color.fromARGB(255, 224, 224, 224),
  310. scaffoldBackgroundColor: Colors.white,
  311. dialogBackgroundColor: Colors.white,
  312. appBarTheme: AppBarTheme(
  313. shadowColor: Colors.transparent,
  314. ),
  315. dialogTheme: DialogTheme(
  316. elevation: 15,
  317. shape: RoundedRectangleBorder(
  318. borderRadius: BorderRadius.circular(18.0),
  319. side: BorderSide(
  320. width: 1,
  321. color: grayBg,
  322. ),
  323. ),
  324. ),
  325. scrollbarTheme: scrollbarTheme,
  326. inputDecorationTheme: isDesktop
  327. ? InputDecorationTheme(
  328. fillColor: grayBg,
  329. filled: true,
  330. isDense: true,
  331. border: OutlineInputBorder(
  332. borderRadius: BorderRadius.circular(8),
  333. ),
  334. )
  335. : null,
  336. textTheme: const TextTheme(
  337. titleLarge: TextStyle(fontSize: 19, color: Colors.black87),
  338. titleSmall: TextStyle(fontSize: 14, color: Colors.black87),
  339. bodySmall: TextStyle(fontSize: 12, color: Colors.black87, height: 1.25),
  340. bodyMedium:
  341. TextStyle(fontSize: 14, color: Colors.black87, height: 1.25),
  342. labelLarge: TextStyle(fontSize: 16.0, color: MyTheme.accent80)),
  343. cardColor: grayBg,
  344. hintColor: Color(0xFFAAAAAA),
  345. visualDensity: VisualDensity.adaptivePlatformDensity,
  346. tabBarTheme: const TabBarTheme(
  347. labelColor: Colors.black87,
  348. ),
  349. tooltipTheme: tooltipTheme(),
  350. splashColor: (isDesktop || isWebDesktop) ? Colors.transparent : null,
  351. highlightColor: (isDesktop || isWebDesktop) ? Colors.transparent : null,
  352. splashFactory: (isDesktop || isWebDesktop) ? NoSplash.splashFactory : null,
  353. textButtonTheme: (isDesktop || isWebDesktop)
  354. ? TextButtonThemeData(
  355. style: TextButton.styleFrom(
  356. splashFactory: NoSplash.splashFactory,
  357. shape: RoundedRectangleBorder(
  358. borderRadius: BorderRadius.circular(18.0),
  359. ),
  360. ),
  361. )
  362. : mobileTextButtonTheme,
  363. elevatedButtonTheme: ElevatedButtonThemeData(
  364. style: ElevatedButton.styleFrom(
  365. backgroundColor: MyTheme.accent,
  366. shape: RoundedRectangleBorder(
  367. borderRadius: BorderRadius.circular(8.0),
  368. ),
  369. ),
  370. ),
  371. outlinedButtonTheme: OutlinedButtonThemeData(
  372. style: OutlinedButton.styleFrom(
  373. backgroundColor: grayBg,
  374. foregroundColor: Colors.black87,
  375. shape: RoundedRectangleBorder(
  376. borderRadius: BorderRadius.circular(8.0),
  377. ),
  378. ),
  379. ),
  380. switchTheme: switchTheme(),
  381. radioTheme: radioTheme(),
  382. checkboxTheme: checkboxTheme,
  383. listTileTheme: listTileTheme,
  384. menuBarTheme: MenuBarThemeData(
  385. style:
  386. MenuStyle(backgroundColor: MaterialStatePropertyAll(Colors.white))),
  387. colorScheme: ColorScheme.light(
  388. primary: Colors.blue, secondary: accent, background: grayBg),
  389. popupMenuTheme: PopupMenuThemeData(
  390. color: Colors.white,
  391. shape: RoundedRectangleBorder(
  392. side: BorderSide(
  393. color: (isDesktop || isWebDesktop)
  394. ? Color(0xFFECECEC)
  395. : Colors.transparent),
  396. borderRadius: BorderRadius.all(Radius.circular(8.0)),
  397. )),
  398. ).copyWith(
  399. extensions: <ThemeExtension<dynamic>>[
  400. ColorThemeExtension.light,
  401. TabbarTheme.light,
  402. ],
  403. );
  404. static ThemeData darkTheme = ThemeData(
  405. useMaterial3: false,
  406. brightness: Brightness.dark,
  407. hoverColor: Color.fromARGB(255, 45, 46, 53),
  408. scaffoldBackgroundColor: Color(0xFF18191E),
  409. dialogBackgroundColor: Color(0xFF18191E),
  410. appBarTheme: AppBarTheme(
  411. shadowColor: Colors.transparent,
  412. ),
  413. dialogTheme: DialogTheme(
  414. elevation: 15,
  415. shape: RoundedRectangleBorder(
  416. borderRadius: BorderRadius.circular(18.0),
  417. side: BorderSide(
  418. width: 1,
  419. color: Color(0xFF24252B),
  420. ),
  421. ),
  422. ),
  423. scrollbarTheme: scrollbarThemeDark,
  424. inputDecorationTheme: (isDesktop || isWebDesktop)
  425. ? InputDecorationTheme(
  426. fillColor: Color(0xFF24252B),
  427. filled: true,
  428. isDense: true,
  429. border: OutlineInputBorder(
  430. borderRadius: BorderRadius.circular(8),
  431. ),
  432. )
  433. : null,
  434. textTheme: const TextTheme(
  435. titleLarge: TextStyle(fontSize: 19),
  436. titleSmall: TextStyle(fontSize: 14),
  437. bodySmall: TextStyle(fontSize: 12, height: 1.25),
  438. bodyMedium: TextStyle(fontSize: 14, height: 1.25),
  439. labelLarge: TextStyle(
  440. fontSize: 16.0,
  441. fontWeight: FontWeight.bold,
  442. color: accent80,
  443. ),
  444. ),
  445. cardColor: Color(0xFF24252B),
  446. visualDensity: VisualDensity.adaptivePlatformDensity,
  447. tabBarTheme: const TabBarTheme(
  448. labelColor: Colors.white70,
  449. ),
  450. tooltipTheme: tooltipTheme(),
  451. splashColor: (isDesktop || isWebDesktop) ? Colors.transparent : null,
  452. highlightColor: (isDesktop || isWebDesktop) ? Colors.transparent : null,
  453. splashFactory: (isDesktop || isWebDesktop) ? NoSplash.splashFactory : null,
  454. textButtonTheme: (isDesktop || isWebDesktop)
  455. ? TextButtonThemeData(
  456. style: TextButton.styleFrom(
  457. splashFactory: NoSplash.splashFactory,
  458. disabledForegroundColor: Colors.white70,
  459. foregroundColor: Colors.white70,
  460. shape: RoundedRectangleBorder(
  461. borderRadius: BorderRadius.circular(18.0),
  462. ),
  463. ),
  464. )
  465. : mobileTextButtonTheme,
  466. elevatedButtonTheme: ElevatedButtonThemeData(
  467. style: ElevatedButton.styleFrom(
  468. backgroundColor: MyTheme.accent,
  469. foregroundColor: Colors.white,
  470. disabledForegroundColor: Colors.white70,
  471. disabledBackgroundColor: Colors.white10,
  472. shape: RoundedRectangleBorder(
  473. borderRadius: BorderRadius.circular(8.0),
  474. ),
  475. ),
  476. ),
  477. outlinedButtonTheme: OutlinedButtonThemeData(
  478. style: OutlinedButton.styleFrom(
  479. backgroundColor: Color(0xFF24252B),
  480. side: BorderSide(color: Colors.white12, width: 0.5),
  481. disabledForegroundColor: Colors.white70,
  482. foregroundColor: Colors.white70,
  483. shape: RoundedRectangleBorder(
  484. borderRadius: BorderRadius.circular(8.0),
  485. ),
  486. ),
  487. ),
  488. switchTheme: switchTheme(),
  489. radioTheme: radioTheme(),
  490. checkboxTheme: checkboxTheme,
  491. listTileTheme: listTileTheme,
  492. menuBarTheme: MenuBarThemeData(
  493. style: MenuStyle(
  494. backgroundColor: MaterialStatePropertyAll(Color(0xFF121212)))),
  495. colorScheme: ColorScheme.dark(
  496. primary: Colors.blue,
  497. secondary: accent,
  498. background: Color(0xFF24252B),
  499. ),
  500. popupMenuTheme: PopupMenuThemeData(
  501. shape: RoundedRectangleBorder(
  502. side: BorderSide(color: Colors.white24),
  503. borderRadius: BorderRadius.all(Radius.circular(8.0)),
  504. )),
  505. ).copyWith(
  506. extensions: <ThemeExtension<dynamic>>[
  507. ColorThemeExtension.dark,
  508. TabbarTheme.dark,
  509. ],
  510. );
  511. static ThemeMode getThemeModePreference() {
  512. return themeModeFromString(bind.mainGetLocalOption(key: kCommConfKeyTheme));
  513. }
  514. static Future<void> changeDarkMode(ThemeMode mode) async {
  515. Get.changeThemeMode(mode);
  516. if (desktopType == DesktopType.main || isAndroid || isIOS || isWeb) {
  517. if (mode == ThemeMode.system) {
  518. await bind.mainSetLocalOption(
  519. key: kCommConfKeyTheme, value: defaultOptionTheme);
  520. } else {
  521. await bind.mainSetLocalOption(
  522. key: kCommConfKeyTheme, value: mode.toShortString());
  523. }
  524. if (!isWeb) await bind.mainChangeTheme(dark: mode.toShortString());
  525. // Synchronize the window theme of the system.
  526. updateSystemWindowTheme();
  527. }
  528. }
  529. static ThemeMode currentThemeMode() {
  530. final preference = getThemeModePreference();
  531. if (preference == ThemeMode.system) {
  532. if (WidgetsBinding.instance.platformDispatcher.platformBrightness ==
  533. Brightness.light) {
  534. return ThemeMode.light;
  535. } else {
  536. return ThemeMode.dark;
  537. }
  538. } else {
  539. return preference;
  540. }
  541. }
  542. static ColorThemeExtension color(BuildContext context) {
  543. return Theme.of(context).extension<ColorThemeExtension>()!;
  544. }
  545. static TabbarTheme tabbar(BuildContext context) {
  546. return Theme.of(context).extension<TabbarTheme>()!;
  547. }
  548. static ThemeMode themeModeFromString(String v) {
  549. switch (v) {
  550. case "light":
  551. return ThemeMode.light;
  552. case "dark":
  553. return ThemeMode.dark;
  554. default:
  555. return ThemeMode.system;
  556. }
  557. }
  558. }
  559. extension ParseToString on ThemeMode {
  560. String toShortString() {
  561. return toString().split('.').last;
  562. }
  563. }
  564. final ButtonStyle flatButtonStyle = TextButton.styleFrom(
  565. minimumSize: Size(0, 36),
  566. padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
  567. shape: const RoundedRectangleBorder(
  568. borderRadius: BorderRadius.all(Radius.circular(2.0)),
  569. ),
  570. );
  571. List<Locale> supportedLocales = const [
  572. Locale('en', 'US'),
  573. Locale('zh', 'CN'),
  574. Locale('zh', 'TW'),
  575. Locale('zh', 'SG'),
  576. Locale('fr'),
  577. Locale('de'),
  578. Locale('it'),
  579. Locale('ja'),
  580. Locale('cs'),
  581. Locale('pl'),
  582. Locale('ko'),
  583. Locale('hu'),
  584. Locale('pt'),
  585. Locale('ru'),
  586. Locale('sk'),
  587. Locale('id'),
  588. Locale('da'),
  589. Locale('eo'),
  590. Locale('tr'),
  591. Locale('kz'),
  592. Locale('es'),
  593. Locale('nl'),
  594. Locale('nb'),
  595. Locale('et'),
  596. Locale('eu'),
  597. Locale('bg'),
  598. Locale('be'),
  599. Locale('vn'),
  600. Locale('uk'),
  601. Locale('fa'),
  602. Locale('ca'),
  603. Locale('el'),
  604. Locale('sv'),
  605. Locale('sq'),
  606. Locale('sr'),
  607. Locale('th'),
  608. Locale('sl'),
  609. Locale('ro'),
  610. Locale('lt'),
  611. Locale('lv'),
  612. Locale('ar'),
  613. Locale('he'),
  614. Locale('hr'),
  615. ];
  616. String formatDurationToTime(Duration duration) {
  617. var totalTime = duration.inSeconds;
  618. final secs = totalTime % 60;
  619. totalTime = (totalTime - secs) ~/ 60;
  620. final mins = totalTime % 60;
  621. totalTime = (totalTime - mins) ~/ 60;
  622. return "${totalTime.toString().padLeft(2, "0")}:${mins.toString().padLeft(2, "0")}:${secs.toString().padLeft(2, "0")}";
  623. }
  624. closeConnection({String? id}) {
  625. if (isAndroid || isIOS) {
  626. () async {
  627. await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
  628. overlays: SystemUiOverlay.values);
  629. gFFI.chatModel.hideChatOverlay();
  630. Navigator.popUntil(globalKey.currentContext!, ModalRoute.withName("/"));
  631. stateGlobal.isInMainPage = true;
  632. }();
  633. } else {
  634. if (isWeb) {
  635. Navigator.popUntil(globalKey.currentContext!, ModalRoute.withName("/"));
  636. stateGlobal.isInMainPage = true;
  637. } else {
  638. final controller = Get.find<DesktopTabController>();
  639. controller.closeBy(id);
  640. }
  641. }
  642. }
  643. Future<void> windowOnTop(int? id) async {
  644. if (!isDesktop) {
  645. return;
  646. }
  647. print("Bring window '$id' on top");
  648. if (id == null) {
  649. // main window
  650. if (stateGlobal.isMinimized) {
  651. await windowManager.restore();
  652. }
  653. await windowManager.show();
  654. await windowManager.focus();
  655. await rustDeskWinManager.registerActiveWindow(kWindowMainId);
  656. } else {
  657. WindowController.fromWindowId(id)
  658. ..focus()
  659. ..show();
  660. rustDeskWinManager.call(WindowType.Main, kWindowEventShow, {"id": id});
  661. }
  662. }
  663. typedef DialogBuilder = CustomAlertDialog Function(
  664. StateSetter setState, void Function([dynamic]) close, BuildContext context);
  665. class Dialog<T> {
  666. OverlayEntry? entry;
  667. Completer<T?> completer = Completer<T?>();
  668. Dialog();
  669. void complete(T? res) {
  670. try {
  671. if (!completer.isCompleted) {
  672. completer.complete(res);
  673. }
  674. } catch (e) {
  675. debugPrint("Dialog complete catch error: $e");
  676. } finally {
  677. entry?.remove();
  678. }
  679. }
  680. }
  681. class OverlayKeyState {
  682. final _overlayKey = GlobalKey<OverlayState>();
  683. /// use global overlay by default
  684. OverlayState? get state =>
  685. _overlayKey.currentState ?? globalKey.currentState?.overlay;
  686. GlobalKey<OverlayState>? get key => _overlayKey;
  687. }
  688. class OverlayDialogManager {
  689. final Map<String, Dialog> _dialogs = {};
  690. var _overlayKeyState = OverlayKeyState();
  691. int _tagCount = 0;
  692. OverlayEntry? _mobileActionsOverlayEntry;
  693. RxBool mobileActionsOverlayVisible = true.obs;
  694. setMobileActionsOverlayVisible(bool v, {store = true}) {
  695. if (store) {
  696. bind.setLocalFlutterOption(k: kOptionShowMobileAction, v: v ? 'Y' : 'N');
  697. }
  698. // No need to read the value from local storage after setting it.
  699. // It better to toggle the value directly.
  700. mobileActionsOverlayVisible.value = v;
  701. }
  702. loadMobileActionsOverlayVisible() {
  703. mobileActionsOverlayVisible.value =
  704. bind.getLocalFlutterOption(k: kOptionShowMobileAction) != 'N';
  705. }
  706. void setOverlayState(OverlayKeyState overlayKeyState) {
  707. _overlayKeyState = overlayKeyState;
  708. }
  709. void dismissAll() {
  710. _dialogs.forEach((key, value) {
  711. value.complete(null);
  712. BackButtonInterceptor.removeByName(key);
  713. });
  714. _dialogs.clear();
  715. }
  716. void dismissByTag(String tag) {
  717. _dialogs[tag]?.complete(null);
  718. _dialogs.remove(tag);
  719. BackButtonInterceptor.removeByName(tag);
  720. }
  721. Future<T?> show<T>(DialogBuilder builder,
  722. {bool clickMaskDismiss = false,
  723. bool backDismiss = false,
  724. String? tag,
  725. bool useAnimation = true,
  726. bool forceGlobal = false}) {
  727. final overlayState =
  728. forceGlobal ? globalKey.currentState?.overlay : _overlayKeyState.state;
  729. if (overlayState == null) {
  730. return Future.error(
  731. "[OverlayDialogManager] Failed to show dialog, _overlayState is null, call [setOverlayState] first");
  732. }
  733. final String dialogTag;
  734. if (tag != null) {
  735. dialogTag = tag;
  736. } else {
  737. dialogTag = _tagCount.toString();
  738. _tagCount++;
  739. }
  740. final dialog = Dialog<T>();
  741. _dialogs[dialogTag] = dialog;
  742. close([res]) {
  743. _dialogs.remove(dialogTag);
  744. dialog.complete(res);
  745. BackButtonInterceptor.removeByName(dialogTag);
  746. }
  747. dialog.entry = OverlayEntry(builder: (context) {
  748. bool innerClicked = false;
  749. return Listener(
  750. onPointerUp: (_) {
  751. if (!innerClicked && clickMaskDismiss) {
  752. close();
  753. }
  754. innerClicked = false;
  755. },
  756. child: Container(
  757. color: Theme.of(context).brightness == Brightness.light
  758. ? Colors.black12
  759. : Colors.black45,
  760. child: StatefulBuilder(builder: (context, setState) {
  761. return Listener(
  762. onPointerUp: (_) => innerClicked = true,
  763. child: builder(setState, close, overlayState.context),
  764. );
  765. })));
  766. });
  767. overlayState.insert(dialog.entry!);
  768. BackButtonInterceptor.add((stopDefaultButtonEvent, routeInfo) {
  769. if (backDismiss) {
  770. close();
  771. }
  772. return true;
  773. }, name: dialogTag);
  774. return dialog.completer.future;
  775. }
  776. String showLoading(String text,
  777. {bool clickMaskDismiss = false,
  778. bool showCancel = true,
  779. VoidCallback? onCancel,
  780. String? tag}) {
  781. if (tag == null) {
  782. tag = _tagCount.toString();
  783. _tagCount++;
  784. }
  785. show((setState, close, context) {
  786. cancel() {
  787. dismissAll();
  788. if (onCancel != null) {
  789. onCancel();
  790. }
  791. }
  792. return CustomAlertDialog(
  793. content: Container(
  794. constraints: const BoxConstraints(maxWidth: 240),
  795. child: Column(
  796. mainAxisSize: MainAxisSize.min,
  797. crossAxisAlignment: CrossAxisAlignment.start,
  798. children: [
  799. const SizedBox(height: 30),
  800. const Center(child: CircularProgressIndicator()),
  801. const SizedBox(height: 20),
  802. Center(
  803. child: Text(translate(text),
  804. style: const TextStyle(fontSize: 15))),
  805. const SizedBox(height: 20),
  806. Offstage(
  807. offstage: !showCancel,
  808. child: Center(
  809. child: (isDesktop || isWebDesktop)
  810. ? dialogButton('Cancel', onPressed: cancel)
  811. : TextButton(
  812. style: flatButtonStyle,
  813. onPressed: cancel,
  814. child: Text(translate('Cancel'),
  815. style: const TextStyle(
  816. color: MyTheme.accent)))))
  817. ])),
  818. onCancel: showCancel ? cancel : null,
  819. );
  820. }, tag: tag);
  821. return tag;
  822. }
  823. void resetMobileActionsOverlay({FFI? ffi}) {
  824. if (_mobileActionsOverlayEntry == null) return;
  825. hideMobileActionsOverlay();
  826. showMobileActionsOverlay(ffi: ffi);
  827. }
  828. void showMobileActionsOverlay({FFI? ffi}) {
  829. if (_mobileActionsOverlayEntry != null) return;
  830. final overlayState = _overlayKeyState.state;
  831. if (overlayState == null) return;
  832. final overlay = makeMobileActionsOverlayEntry(
  833. () => hideMobileActionsOverlay(),
  834. ffi: ffi,
  835. );
  836. overlayState.insert(overlay);
  837. _mobileActionsOverlayEntry = overlay;
  838. setMobileActionsOverlayVisible(true);
  839. }
  840. void hideMobileActionsOverlay({store = true}) {
  841. if (_mobileActionsOverlayEntry != null) {
  842. _mobileActionsOverlayEntry!.remove();
  843. _mobileActionsOverlayEntry = null;
  844. setMobileActionsOverlayVisible(false, store: store);
  845. return;
  846. }
  847. }
  848. void toggleMobileActionsOverlay({FFI? ffi}) {
  849. if (_mobileActionsOverlayEntry == null) {
  850. showMobileActionsOverlay(ffi: ffi);
  851. } else {
  852. hideMobileActionsOverlay();
  853. }
  854. }
  855. bool existing(String tag) {
  856. return _dialogs.keys.contains(tag);
  857. }
  858. }
  859. makeMobileActionsOverlayEntry(VoidCallback? onHide, {FFI? ffi}) {
  860. makeMobileActions(BuildContext context, double s) {
  861. final scale = s < 0.85 ? 0.85 : s;
  862. final session = ffi ?? gFFI;
  863. const double overlayW = 200;
  864. const double overlayH = 45;
  865. computeOverlayPosition() {
  866. final screenW = MediaQuery.of(context).size.width;
  867. final screenH = MediaQuery.of(context).size.height;
  868. final left = (screenW - overlayW * scale) / 2;
  869. final top = screenH - (overlayH + 80) * scale;
  870. return Offset(left, top);
  871. }
  872. if (draggablePositions.mobileActions.isInvalid()) {
  873. draggablePositions.mobileActions.update(computeOverlayPosition());
  874. } else {
  875. draggablePositions.mobileActions.tryAdjust(overlayW, overlayH, scale);
  876. }
  877. return DraggableMobileActions(
  878. scale: scale,
  879. position: draggablePositions.mobileActions,
  880. width: overlayW,
  881. height: overlayH,
  882. onBackPressed: session.inputModel.onMobileBack,
  883. onHomePressed: session.inputModel.onMobileHome,
  884. onRecentPressed: session.inputModel.onMobileApps,
  885. onHidePressed: onHide,
  886. );
  887. }
  888. return OverlayEntry(builder: (context) {
  889. if (isDesktop) {
  890. final c = Provider.of<CanvasModel>(context);
  891. return makeMobileActions(context, c.scale * 2.0);
  892. } else {
  893. return makeMobileActions(globalKey.currentContext!, 1.0);
  894. }
  895. });
  896. }
  897. void showToast(String text, {Duration timeout = const Duration(seconds: 3)}) {
  898. final overlayState = globalKey.currentState?.overlay;
  899. if (overlayState == null) return;
  900. final entry = OverlayEntry(builder: (context) {
  901. return IgnorePointer(
  902. child: Align(
  903. alignment: const Alignment(0.0, 0.8),
  904. child: Container(
  905. decoration: BoxDecoration(
  906. color: MyTheme.color(context).toastBg,
  907. borderRadius: const BorderRadius.all(
  908. Radius.circular(20),
  909. ),
  910. ),
  911. padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5),
  912. child: Text(
  913. text,
  914. textAlign: TextAlign.center,
  915. style: TextStyle(
  916. decoration: TextDecoration.none,
  917. fontWeight: FontWeight.w300,
  918. fontSize: 18,
  919. color: MyTheme.color(context).toastText),
  920. ),
  921. )));
  922. });
  923. overlayState.insert(entry);
  924. Future.delayed(timeout, () {
  925. entry.remove();
  926. });
  927. }
  928. // TODO
  929. // - Remove argument "contentPadding", no need for it, all should look the same.
  930. // - Remove "required" for argument "content". See simple confirm dialog "delete peer", only title and actions are used. No need to "content: SizedBox.shrink()".
  931. // - Make dead code alive, transform arguments "onSubmit" and "onCancel" into correspondenting buttons "ConfirmOkButton", "CancelButton".
  932. class CustomAlertDialog extends StatelessWidget {
  933. const CustomAlertDialog(
  934. {Key? key,
  935. this.title,
  936. this.titlePadding,
  937. required this.content,
  938. this.actions,
  939. this.contentPadding,
  940. this.contentBoxConstraints = const BoxConstraints(maxWidth: 500),
  941. this.onSubmit,
  942. this.onCancel})
  943. : super(key: key);
  944. final Widget? title;
  945. final EdgeInsetsGeometry? titlePadding;
  946. final Widget content;
  947. final List<Widget>? actions;
  948. final double? contentPadding;
  949. final BoxConstraints contentBoxConstraints;
  950. final Function()? onSubmit;
  951. final Function()? onCancel;
  952. @override
  953. Widget build(BuildContext context) {
  954. // request focus
  955. FocusScopeNode scopeNode = FocusScopeNode();
  956. Future.delayed(Duration.zero, () {
  957. if (!scopeNode.hasFocus) scopeNode.requestFocus();
  958. });
  959. bool tabTapped = false;
  960. if (isAndroid) gFFI.invokeMethod("enable_soft_keyboard", true);
  961. return FocusScope(
  962. node: scopeNode,
  963. autofocus: true,
  964. onKey: (node, key) {
  965. if (key.logicalKey == LogicalKeyboardKey.escape) {
  966. if (key is RawKeyDownEvent) {
  967. onCancel?.call();
  968. }
  969. return KeyEventResult.handled; // avoid TextField exception on escape
  970. } else if (!tabTapped &&
  971. onSubmit != null &&
  972. (key.logicalKey == LogicalKeyboardKey.enter ||
  973. key.logicalKey == LogicalKeyboardKey.numpadEnter)) {
  974. if (key is RawKeyDownEvent) onSubmit?.call();
  975. return KeyEventResult.handled;
  976. } else if (key.logicalKey == LogicalKeyboardKey.tab) {
  977. if (key is RawKeyDownEvent) {
  978. scopeNode.nextFocus();
  979. tabTapped = true;
  980. }
  981. return KeyEventResult.handled;
  982. }
  983. return KeyEventResult.ignored;
  984. },
  985. child: AlertDialog(
  986. scrollable: true,
  987. title: title,
  988. content: ConstrainedBox(
  989. constraints: contentBoxConstraints,
  990. child: content,
  991. ),
  992. actions: actions,
  993. titlePadding: titlePadding ?? MyTheme.dialogTitlePadding(),
  994. contentPadding:
  995. MyTheme.dialogContentPadding(actions: actions is List),
  996. actionsPadding: MyTheme.dialogActionsPadding(),
  997. buttonPadding: MyTheme.dialogButtonPadding),
  998. );
  999. }
  1000. }
  1001. Widget createDialogContent(String text) {
  1002. final RegExp linkRegExp = RegExp(r'(https?://[^\s]+)');
  1003. final List<TextSpan> spans = [];
  1004. int start = 0;
  1005. bool hasLink = false;
  1006. linkRegExp.allMatches(text).forEach((match) {
  1007. hasLink = true;
  1008. if (match.start > start) {
  1009. spans.add(TextSpan(text: text.substring(start, match.start)));
  1010. }
  1011. spans.add(TextSpan(
  1012. text: match.group(0) ?? '',
  1013. style: TextStyle(
  1014. color: Colors.blue,
  1015. decoration: TextDecoration.underline,
  1016. ),
  1017. recognizer: TapGestureRecognizer()
  1018. ..onTap = () {
  1019. String linkText = match.group(0) ?? '';
  1020. linkText = linkText.replaceAll(RegExp(r'[.,;!?]+$'), '');
  1021. launchUrl(Uri.parse(linkText));
  1022. },
  1023. ));
  1024. start = match.end;
  1025. });
  1026. if (start < text.length) {
  1027. spans.add(TextSpan(text: text.substring(start)));
  1028. }
  1029. if (!hasLink) {
  1030. return SelectableText(text, style: const TextStyle(fontSize: 15));
  1031. }
  1032. return SelectableText.rich(
  1033. TextSpan(
  1034. style: TextStyle(color: Colors.black, fontSize: 15),
  1035. children: spans,
  1036. ),
  1037. );
  1038. }
  1039. void msgBox(SessionID sessionId, String type, String title, String text,
  1040. String link, OverlayDialogManager dialogManager,
  1041. {bool? hasCancel, ReconnectHandle? reconnect, int? reconnectTimeout}) {
  1042. dialogManager.dismissAll();
  1043. List<Widget> buttons = [];
  1044. bool hasOk = false;
  1045. submit() {
  1046. dialogManager.dismissAll();
  1047. // https://github.com/rustdesk/rustdesk/blob/5e9a31340b899822090a3731769ae79c6bf5f3e5/src/ui/common.tis#L263
  1048. if (!type.contains("custom") && desktopType != DesktopType.portForward) {
  1049. closeConnection();
  1050. }
  1051. }
  1052. cancel() {
  1053. dialogManager.dismissAll();
  1054. }
  1055. jumplink() {
  1056. if (link.startsWith('http')) {
  1057. launchUrl(Uri.parse(link));
  1058. }
  1059. }
  1060. if (type != "connecting" && type != "success" && !type.contains("nook")) {
  1061. hasOk = true;
  1062. buttons.insert(0, dialogButton('OK', onPressed: submit));
  1063. }
  1064. hasCancel ??= !type.contains("error") &&
  1065. !type.contains("nocancel") &&
  1066. type != "restarting";
  1067. if (hasCancel) {
  1068. buttons.insert(
  1069. 0, dialogButton('Cancel', onPressed: cancel, isOutline: true));
  1070. }
  1071. if (type.contains("hasclose")) {
  1072. buttons.insert(
  1073. 0,
  1074. dialogButton('Close', onPressed: () {
  1075. dialogManager.dismissAll();
  1076. }));
  1077. }
  1078. if (reconnect != null && title == "Connection Error") {
  1079. // `enabled` is used to disable the dialog button once the button is clicked.
  1080. final enabled = true.obs;
  1081. final button = reconnectTimeout != null
  1082. ? Obx(() => _ReconnectCountDownButton(
  1083. second: reconnectTimeout,
  1084. onPressed: enabled.isTrue
  1085. ? () {
  1086. // Disable the button
  1087. enabled.value = false;
  1088. reconnect(dialogManager, sessionId, false);
  1089. }
  1090. : null,
  1091. ))
  1092. : Obx(
  1093. () => dialogButton(
  1094. 'Reconnect',
  1095. isOutline: true,
  1096. onPressed: enabled.isTrue
  1097. ? () {
  1098. // Disable the button
  1099. enabled.value = false;
  1100. reconnect(dialogManager, sessionId, false);
  1101. }
  1102. : null,
  1103. ),
  1104. );
  1105. buttons.insert(0, button);
  1106. }
  1107. if (link.isNotEmpty) {
  1108. buttons.insert(0, dialogButton('JumpLink', onPressed: jumplink));
  1109. }
  1110. dialogManager.show(
  1111. (setState, close, context) => CustomAlertDialog(
  1112. title: null,
  1113. content: SelectionArea(child: msgboxContent(type, title, text)),
  1114. actions: buttons,
  1115. onSubmit: hasOk ? submit : null,
  1116. onCancel: hasCancel == true ? cancel : null,
  1117. ),
  1118. tag: '$sessionId-$type-$title-$text-$link',
  1119. );
  1120. }
  1121. Color? _msgboxColor(String type) {
  1122. if (type == "input-password" || type == "custom-os-password") {
  1123. return Color(0xFFAD448E);
  1124. }
  1125. if (type.contains("success")) {
  1126. return Color(0xFF32bea6);
  1127. }
  1128. if (type.contains("error") || type == "re-input-password") {
  1129. return Color(0xFFE04F5F);
  1130. }
  1131. return Color(0xFF2C8CFF);
  1132. }
  1133. Widget msgboxIcon(String type) {
  1134. IconData? iconData;
  1135. if (type.contains("error") || type == "re-input-password") {
  1136. iconData = Icons.cancel;
  1137. }
  1138. if (type.contains("success")) {
  1139. iconData = Icons.check_circle;
  1140. }
  1141. if (type == "wait-uac" || type == "wait-remote-accept-nook") {
  1142. iconData = Icons.hourglass_top;
  1143. }
  1144. if (type == 'on-uac' || type == 'on-foreground-elevated') {
  1145. iconData = Icons.admin_panel_settings;
  1146. }
  1147. if (type.contains('info')) {
  1148. iconData = Icons.info;
  1149. }
  1150. if (iconData != null) {
  1151. return Icon(iconData, size: 50, color: _msgboxColor(type))
  1152. .marginOnly(right: 16);
  1153. }
  1154. return Offstage();
  1155. }
  1156. // title should be null
  1157. Widget msgboxContent(String type, String title, String text) {
  1158. String translateText(String text) {
  1159. if (text.indexOf('Failed') == 0 && text.indexOf(': ') > 0) {
  1160. List<String> words = text.split(': ');
  1161. for (var i = 0; i < words.length; ++i) {
  1162. words[i] = translate(words[i]);
  1163. }
  1164. text = words.join(': ');
  1165. } else {
  1166. List<String> words = text.split(' ');
  1167. if (words.length > 1 && words[0].endsWith('_tip')) {
  1168. words[0] = translate(words[0]);
  1169. final rest = text.substring(words[0].length + 1);
  1170. text = '${words[0]} ${translate(rest)}';
  1171. } else {
  1172. text = translate(text);
  1173. }
  1174. }
  1175. return text;
  1176. }
  1177. return Row(
  1178. children: [
  1179. msgboxIcon(type),
  1180. Expanded(
  1181. child: Column(
  1182. crossAxisAlignment: CrossAxisAlignment.start,
  1183. children: [
  1184. Text(
  1185. translate(title),
  1186. style: TextStyle(fontSize: 21),
  1187. ).marginOnly(bottom: 10),
  1188. createDialogContent(translateText(text)),
  1189. ],
  1190. ),
  1191. ),
  1192. ],
  1193. ).marginOnly(bottom: 12);
  1194. }
  1195. void msgBoxCommon(OverlayDialogManager dialogManager, String title,
  1196. Widget content, List<Widget> buttons,
  1197. {bool hasCancel = true}) {
  1198. dialogManager.show((setState, close, context) => CustomAlertDialog(
  1199. title: Text(
  1200. translate(title),
  1201. style: TextStyle(fontSize: 21),
  1202. ),
  1203. content: content,
  1204. actions: buttons,
  1205. onCancel: hasCancel ? close : null,
  1206. ));
  1207. }
  1208. Color str2color(String str, [alpha = 0xFF]) {
  1209. var hash = 160 << 16 + 114 << 8 + 91;
  1210. for (var i = 0; i < str.length; i += 1) {
  1211. hash = str.codeUnitAt(i) + ((hash << 5) - hash);
  1212. }
  1213. hash = hash % 16777216;
  1214. return Color((hash & 0xFF7FFF) | (alpha << 24));
  1215. }
  1216. Color str2color2(String str, {List<int> existing = const []}) {
  1217. Map<String, Color> colorMap = {
  1218. "red": Colors.red,
  1219. "green": Colors.green,
  1220. "blue": Colors.blue,
  1221. "orange": Colors.orange,
  1222. "purple": Colors.purple,
  1223. "grey": Colors.grey,
  1224. "cyan": Colors.cyan,
  1225. "lime": Colors.lime,
  1226. "teal": Colors.teal,
  1227. "pink": Colors.pink[200]!,
  1228. "indigo": Colors.indigo,
  1229. "brown": Colors.brown,
  1230. };
  1231. final color = colorMap[str.toLowerCase()];
  1232. if (color != null) {
  1233. return color.withAlpha(0xFF);
  1234. }
  1235. if (str.toLowerCase() == 'yellow') {
  1236. return Colors.yellow.withAlpha(0xFF);
  1237. }
  1238. var hash = 0;
  1239. for (var i = 0; i < str.length; i++) {
  1240. hash += str.codeUnitAt(i);
  1241. }
  1242. List<Color> colorList = colorMap.values.toList();
  1243. hash = hash % colorList.length;
  1244. var result = colorList[hash].withAlpha(0xFF);
  1245. if (existing.contains(result.value)) {
  1246. Color? notUsed =
  1247. colorList.firstWhereOrNull((e) => !existing.contains(e.value));
  1248. if (notUsed != null) {
  1249. result = notUsed;
  1250. }
  1251. }
  1252. return result;
  1253. }
  1254. const K = 1024;
  1255. const M = K * K;
  1256. const G = M * K;
  1257. String readableFileSize(double size) {
  1258. if (size < K) {
  1259. return "${size.toStringAsFixed(2)} B";
  1260. } else if (size < M) {
  1261. return "${(size / K).toStringAsFixed(2)} KB";
  1262. } else if (size < G) {
  1263. return "${(size / M).toStringAsFixed(2)} MB";
  1264. } else {
  1265. return "${(size / G).toStringAsFixed(2)} GB";
  1266. }
  1267. }
  1268. /// Flutter can't not catch PointerMoveEvent when size is 1
  1269. /// This will happen in Android AccessibilityService Input
  1270. /// android can't init dispatching size yet ,see: https://stackoverflow.com/questions/59960451/android-accessibility-dispatchgesture-is-it-possible-to-specify-pressure-for-a
  1271. /// use this temporary solution until flutter or android fixes the bug
  1272. class AccessibilityListener extends StatelessWidget {
  1273. final Widget? child;
  1274. static final offset = 100;
  1275. AccessibilityListener({this.child});
  1276. @override
  1277. Widget build(BuildContext context) {
  1278. return Listener(
  1279. onPointerDown: (evt) {
  1280. if (evt.size == 1) {
  1281. GestureBinding.instance.handlePointerEvent(PointerAddedEvent(
  1282. pointer: evt.pointer + offset, position: evt.position));
  1283. GestureBinding.instance.handlePointerEvent(PointerDownEvent(
  1284. pointer: evt.pointer + offset,
  1285. size: 0.1,
  1286. position: evt.position));
  1287. }
  1288. },
  1289. onPointerUp: (evt) {
  1290. if (evt.size == 1) {
  1291. GestureBinding.instance.handlePointerEvent(PointerUpEvent(
  1292. pointer: evt.pointer + offset,
  1293. size: 0.1,
  1294. position: evt.position));
  1295. GestureBinding.instance.handlePointerEvent(PointerRemovedEvent(
  1296. pointer: evt.pointer + offset, position: evt.position));
  1297. }
  1298. },
  1299. onPointerMove: (evt) {
  1300. if (evt.size == 1) {
  1301. GestureBinding.instance.handlePointerEvent(PointerMoveEvent(
  1302. pointer: evt.pointer + offset,
  1303. size: 0.1,
  1304. delta: evt.delta,
  1305. position: evt.position));
  1306. }
  1307. },
  1308. child: child);
  1309. }
  1310. }
  1311. class AndroidPermissionManager {
  1312. static Completer<bool>? _completer;
  1313. static Timer? _timer;
  1314. static var _current = "";
  1315. static bool isWaitingFile() {
  1316. if (_completer != null) {
  1317. return !_completer!.isCompleted && _current == kManageExternalStorage;
  1318. }
  1319. return false;
  1320. }
  1321. static Future<bool> check(String type) {
  1322. if (isDesktop || isWeb) {
  1323. return Future.value(true);
  1324. }
  1325. return gFFI.invokeMethod("check_permission", type);
  1326. }
  1327. // startActivity goto Android Setting's page to request permission manually by user
  1328. static void startAction(String action) {
  1329. gFFI.invokeMethod(AndroidChannel.kStartAction, action);
  1330. }
  1331. /// We use XXPermissions to request permissions,
  1332. /// for supported types, see https://github.com/getActivity/XXPermissions/blob/e46caea32a64ad7819df62d448fb1c825481cd28/library/src/main/java/com/hjq/permissions/Permission.java
  1333. static Future<bool> request(String type) {
  1334. if (isDesktop || isWeb) {
  1335. return Future.value(true);
  1336. }
  1337. gFFI.invokeMethod("request_permission", type);
  1338. // clear last task
  1339. if (_completer?.isCompleted == false) {
  1340. _completer?.complete(false);
  1341. }
  1342. _timer?.cancel();
  1343. _current = type;
  1344. _completer = Completer<bool>();
  1345. _timer = Timer(Duration(seconds: 120), () {
  1346. if (_completer == null) return;
  1347. if (!_completer!.isCompleted) {
  1348. _completer!.complete(false);
  1349. }
  1350. _completer = null;
  1351. _current = "";
  1352. });
  1353. return _completer!.future;
  1354. }
  1355. static complete(String type, bool res) {
  1356. if (type != _current) {
  1357. res = false;
  1358. }
  1359. _timer?.cancel();
  1360. _completer?.complete(res);
  1361. _current = "";
  1362. }
  1363. }
  1364. RadioListTile<T> getRadio<T>(
  1365. Widget title, T toValue, T curValue, ValueChanged<T?>? onChange,
  1366. {bool? dense}) {
  1367. return RadioListTile<T>(
  1368. visualDensity: VisualDensity.compact,
  1369. controlAffinity: ListTileControlAffinity.trailing,
  1370. title: title,
  1371. value: toValue,
  1372. groupValue: curValue,
  1373. onChanged: onChange,
  1374. dense: dense,
  1375. );
  1376. }
  1377. /// find ffi, tag is Remote ID
  1378. /// for session specific usage
  1379. FFI ffi(String? tag) {
  1380. return Get.find<FFI>(tag: tag);
  1381. }
  1382. /// Global FFI object
  1383. late FFI _globalFFI;
  1384. FFI get gFFI => _globalFFI;
  1385. Future<void> initGlobalFFI() async {
  1386. debugPrint("_globalFFI init");
  1387. _globalFFI = FFI(null);
  1388. debugPrint("_globalFFI init end");
  1389. // after `put`, can also be globally found by Get.find<FFI>();
  1390. Get.put<FFI>(_globalFFI, permanent: true);
  1391. }
  1392. String translate(String name) {
  1393. if (name.startsWith('Failed to') && name.contains(': ')) {
  1394. return name.split(': ').map((x) => translate(x)).join(': ');
  1395. }
  1396. return platformFFI.translate(name, localeName);
  1397. }
  1398. // This function must be kept the same as the one in rust and sciter code.
  1399. // rust: libs/hbb_common/src/config.rs -> option2bool()
  1400. // sciter: Does not have the function, but it should be kept the same.
  1401. bool option2bool(String option, String value) {
  1402. bool res;
  1403. if (option.startsWith("enable-")) {
  1404. res = value != "N";
  1405. } else if (option.startsWith("allow-") ||
  1406. option == kOptionStopService ||
  1407. option == kOptionDirectServer ||
  1408. option == kOptionForceAlwaysRelay) {
  1409. res = value == "Y";
  1410. } else {
  1411. assert(false);
  1412. res = value != "N";
  1413. }
  1414. return res;
  1415. }
  1416. String bool2option(String option, bool b) {
  1417. String res;
  1418. if (option.startsWith('enable-')) {
  1419. res = b ? defaultOptionYes : 'N';
  1420. } else if (option.startsWith('allow-') ||
  1421. option == kOptionStopService ||
  1422. option == kOptionDirectServer ||
  1423. option == kOptionForceAlwaysRelay) {
  1424. res = b ? 'Y' : defaultOptionNo;
  1425. } else {
  1426. assert(false);
  1427. res = b ? 'Y' : 'N';
  1428. }
  1429. return res;
  1430. }
  1431. mainSetBoolOption(String key, bool value) async {
  1432. String v = bool2option(key, value);
  1433. await bind.mainSetOption(key: key, value: v);
  1434. }
  1435. Future<bool> mainGetBoolOption(String key) async {
  1436. return option2bool(key, await bind.mainGetOption(key: key));
  1437. }
  1438. bool mainGetBoolOptionSync(String key) {
  1439. return option2bool(key, bind.mainGetOptionSync(key: key));
  1440. }
  1441. mainSetLocalBoolOption(String key, bool value) async {
  1442. String v = bool2option(key, value);
  1443. await bind.mainSetLocalOption(key: key, value: v);
  1444. }
  1445. bool mainGetLocalBoolOptionSync(String key) {
  1446. return option2bool(key, bind.mainGetLocalOption(key: key));
  1447. }
  1448. bool mainGetPeerBoolOptionSync(String id, String key) {
  1449. return option2bool(key, bind.mainGetPeerOptionSync(id: id, key: key));
  1450. }
  1451. // Don't use `option2bool()` and `bool2option()` to convert the session option.
  1452. // Use `sessionGetToggleOption()` and `sessionToggleOption()` instead.
  1453. // Because all session options use `Y` and `<Empty>` as values.
  1454. Future<bool> matchPeer(String searchText, Peer peer) async {
  1455. if (searchText.isEmpty) {
  1456. return true;
  1457. }
  1458. if (peer.id.toLowerCase().contains(searchText)) {
  1459. return true;
  1460. }
  1461. if (peer.hostname.toLowerCase().contains(searchText) ||
  1462. peer.username.toLowerCase().contains(searchText)) {
  1463. return true;
  1464. }
  1465. final alias = peer.alias;
  1466. if (alias.isEmpty) {
  1467. return false;
  1468. }
  1469. return alias.toLowerCase().contains(searchText);
  1470. }
  1471. /// Get the image for the current [platform].
  1472. Widget getPlatformImage(String platform, {double size = 50}) {
  1473. if (platform.isEmpty) {
  1474. return Container(width: size, height: size);
  1475. }
  1476. if (platform == kPeerPlatformMacOS) {
  1477. platform = 'mac';
  1478. } else if (platform != kPeerPlatformLinux &&
  1479. platform != kPeerPlatformAndroid) {
  1480. platform = 'win';
  1481. } else {
  1482. platform = platform.toLowerCase();
  1483. }
  1484. return SvgPicture.asset('assets/$platform.svg', height: size, width: size);
  1485. }
  1486. class OffsetDevicePixelRatio {
  1487. Offset offset;
  1488. final double devicePixelRatio;
  1489. OffsetDevicePixelRatio(this.offset, this.devicePixelRatio);
  1490. }
  1491. class LastWindowPosition {
  1492. double? width;
  1493. double? height;
  1494. double? offsetWidth;
  1495. double? offsetHeight;
  1496. bool? isMaximized;
  1497. bool? isFullscreen;
  1498. LastWindowPosition(this.width, this.height, this.offsetWidth,
  1499. this.offsetHeight, this.isMaximized, this.isFullscreen);
  1500. Map<String, dynamic> toJson() {
  1501. return <String, dynamic>{
  1502. "width": width,
  1503. "height": height,
  1504. "offsetWidth": offsetWidth,
  1505. "offsetHeight": offsetHeight,
  1506. "isMaximized": isMaximized,
  1507. "isFullscreen": isFullscreen,
  1508. };
  1509. }
  1510. @override
  1511. String toString() {
  1512. return jsonEncode(toJson());
  1513. }
  1514. static LastWindowPosition? loadFromString(String content) {
  1515. if (content.isEmpty) {
  1516. return null;
  1517. }
  1518. try {
  1519. final m = jsonDecode(content);
  1520. return LastWindowPosition(m["width"], m["height"], m["offsetWidth"],
  1521. m["offsetHeight"], m["isMaximized"], m["isFullscreen"]);
  1522. } catch (e) {
  1523. debugPrintStack(
  1524. label:
  1525. 'Failed to load LastWindowPosition "$content" ${e.toString()}');
  1526. return null;
  1527. }
  1528. }
  1529. }
  1530. String get windowFramePrefix =>
  1531. kWindowPrefix +
  1532. (bind.isIncomingOnly()
  1533. ? "incoming_"
  1534. : (bind.isOutgoingOnly() ? "outgoing_" : ""));
  1535. /// Save window position and size on exit
  1536. /// Note that windowId must be provided if it's subwindow
  1537. Future<void> saveWindowPosition(WindowType type, {int? windowId}) async {
  1538. if (type != WindowType.Main && windowId == null) {
  1539. debugPrint(
  1540. "Error: windowId cannot be null when saving positions for sub window");
  1541. }
  1542. late Offset position;
  1543. late Size sz;
  1544. late bool isMaximized;
  1545. bool isFullscreen = stateGlobal.fullscreen.isTrue;
  1546. setPreFrame() {
  1547. final pos = bind.getLocalFlutterOption(k: windowFramePrefix + type.name);
  1548. var lpos = LastWindowPosition.loadFromString(pos);
  1549. position = Offset(
  1550. lpos?.offsetWidth ?? position.dx, lpos?.offsetHeight ?? position.dy);
  1551. sz = Size(lpos?.width ?? sz.width, lpos?.height ?? sz.height);
  1552. }
  1553. switch (type) {
  1554. case WindowType.Main:
  1555. // Checking `bind.isIncomingOnly()` is a simple workaround for MacOS.
  1556. // `await windowManager.isMaximized()` will always return true
  1557. // if is not resizable. The reason is unknown.
  1558. //
  1559. // `setResizable(!bind.isIncomingOnly());` in main.dart
  1560. isMaximized =
  1561. bind.isIncomingOnly() ? false : await windowManager.isMaximized();
  1562. if (isFullscreen || isMaximized) {
  1563. setPreFrame();
  1564. } else {
  1565. position = await windowManager.getPosition();
  1566. sz = await windowManager.getSize();
  1567. }
  1568. break;
  1569. default:
  1570. final wc = WindowController.fromWindowId(windowId!);
  1571. isMaximized = await wc.isMaximized();
  1572. if (isFullscreen || isMaximized) {
  1573. setPreFrame();
  1574. } else {
  1575. final Rect frame;
  1576. try {
  1577. frame = await wc.getFrame();
  1578. } catch (e) {
  1579. debugPrint(
  1580. "Failed to get frame of window $windowId, it may be hidden");
  1581. return;
  1582. }
  1583. position = frame.topLeft;
  1584. sz = frame.size;
  1585. }
  1586. break;
  1587. }
  1588. if (isWindows) {
  1589. const kMinOffset = -10000;
  1590. const kMaxOffset = 10000;
  1591. if (position.dx < kMinOffset ||
  1592. position.dy < kMinOffset ||
  1593. position.dx > kMaxOffset ||
  1594. position.dy > kMaxOffset) {
  1595. debugPrint("Invalid position: $position, ignore saving position");
  1596. return;
  1597. }
  1598. }
  1599. final pos = LastWindowPosition(
  1600. sz.width, sz.height, position.dx, position.dy, isMaximized, isFullscreen);
  1601. debugPrint(
  1602. "Saving frame: $windowId: ${pos.width}/${pos.height}, offset:${pos.offsetWidth}/${pos.offsetHeight}, isMaximized:${pos.isMaximized}, isFullscreen:${pos.isFullscreen}");
  1603. await bind.setLocalFlutterOption(
  1604. k: windowFramePrefix + type.name, v: pos.toString());
  1605. if (type == WindowType.RemoteDesktop && windowId != null) {
  1606. await _saveSessionWindowPosition(
  1607. type, windowId, isMaximized, isFullscreen, pos);
  1608. }
  1609. }
  1610. Future _saveSessionWindowPosition(WindowType windowType, int windowId,
  1611. bool isMaximized, bool isFullscreen, LastWindowPosition pos) async {
  1612. final remoteList = await DesktopMultiWindow.invokeMethod(
  1613. windowId, kWindowEventGetRemoteList, null);
  1614. getPeerPos(String peerId) {
  1615. if (isMaximized || isFullscreen) {
  1616. final peerPos = bind.mainGetPeerFlutterOptionSync(
  1617. id: peerId, k: windowFramePrefix + windowType.name);
  1618. var lpos = LastWindowPosition.loadFromString(peerPos);
  1619. return LastWindowPosition(
  1620. lpos?.width ?? pos.offsetWidth,
  1621. lpos?.height ?? pos.offsetHeight,
  1622. lpos?.offsetWidth ?? pos.offsetWidth,
  1623. lpos?.offsetHeight ?? pos.offsetHeight,
  1624. isMaximized,
  1625. isFullscreen)
  1626. .toString();
  1627. } else {
  1628. return pos.toString();
  1629. }
  1630. }
  1631. if (remoteList != null) {
  1632. for (final peerId in remoteList.split(',')) {
  1633. bind.mainSetPeerFlutterOptionSync(
  1634. id: peerId,
  1635. k: windowFramePrefix + windowType.name,
  1636. v: getPeerPos(peerId));
  1637. }
  1638. }
  1639. }
  1640. Future<Size> _adjustRestoreMainWindowSize(double? width, double? height) async {
  1641. const double minWidth = 1;
  1642. const double minHeight = 1;
  1643. const double maxWidth = 6480;
  1644. const double maxHeight = 6480;
  1645. final defaultWidth =
  1646. ((isDesktop || isWebDesktop) ? 1280 : kMobileDefaultDisplayWidth)
  1647. .toDouble();
  1648. final defaultHeight =
  1649. ((isDesktop || isWebDesktop) ? 720 : kMobileDefaultDisplayHeight)
  1650. .toDouble();
  1651. double restoreWidth = width ?? defaultWidth;
  1652. double restoreHeight = height ?? defaultHeight;
  1653. if (restoreWidth < minWidth) {
  1654. restoreWidth = defaultWidth;
  1655. }
  1656. if (restoreHeight < minHeight) {
  1657. restoreHeight = defaultHeight;
  1658. }
  1659. if (restoreWidth > maxWidth) {
  1660. restoreWidth = defaultWidth;
  1661. }
  1662. if (restoreHeight > maxHeight) {
  1663. restoreHeight = defaultHeight;
  1664. }
  1665. return Size(restoreWidth, restoreHeight);
  1666. }
  1667. bool isPointInRect(Offset point, Rect rect) {
  1668. return point.dx >= rect.left &&
  1669. point.dx <= rect.right &&
  1670. point.dy >= rect.top &&
  1671. point.dy <= rect.bottom;
  1672. }
  1673. /// return null means center
  1674. Future<OffsetDevicePixelRatio?> _adjustRestoreMainWindowOffset(
  1675. double? left,
  1676. double? top,
  1677. double? width,
  1678. double? height,
  1679. ) async {
  1680. if (left == null || top == null || width == null || height == null) {
  1681. return null;
  1682. }
  1683. double? frameLeft;
  1684. double? frameTop;
  1685. double? frameRight;
  1686. double? frameBottom;
  1687. double devicePixelRatio = 1.0;
  1688. if (isDesktop || isWebDesktop) {
  1689. for (final screen in await window_size.getScreenList()) {
  1690. if (isPointInRect(Offset(left, top), screen.visibleFrame)) {
  1691. devicePixelRatio = screen.scaleFactor;
  1692. }
  1693. frameLeft = frameLeft == null
  1694. ? screen.visibleFrame.left
  1695. : min(screen.visibleFrame.left, frameLeft);
  1696. frameTop = frameTop == null
  1697. ? screen.visibleFrame.top
  1698. : min(screen.visibleFrame.top, frameTop);
  1699. frameRight = frameRight == null
  1700. ? screen.visibleFrame.right
  1701. : max(screen.visibleFrame.right, frameRight);
  1702. frameBottom = frameBottom == null
  1703. ? screen.visibleFrame.bottom
  1704. : max(screen.visibleFrame.bottom, frameBottom);
  1705. }
  1706. }
  1707. if (frameLeft == null) {
  1708. frameLeft = 0.0;
  1709. frameTop = 0.0;
  1710. frameRight = ((isDesktop || isWebDesktop)
  1711. ? kDesktopMaxDisplaySize
  1712. : kMobileMaxDisplaySize)
  1713. .toDouble();
  1714. frameBottom = ((isDesktop || isWebDesktop)
  1715. ? kDesktopMaxDisplaySize
  1716. : kMobileMaxDisplaySize)
  1717. .toDouble();
  1718. }
  1719. final minWidth = 10.0;
  1720. if ((left + minWidth) > frameRight! ||
  1721. (top + minWidth) > frameBottom! ||
  1722. (left + width - minWidth) < frameLeft ||
  1723. top < frameTop!) {
  1724. return null;
  1725. } else {
  1726. return OffsetDevicePixelRatio(Offset(left, top), devicePixelRatio);
  1727. }
  1728. }
  1729. /// Restore window position and size on start
  1730. /// Note that windowId must be provided if it's subwindow
  1731. //
  1732. // display is used to set the offset of the window in individual display mode.
  1733. Future<bool> restoreWindowPosition(WindowType type,
  1734. {int? windowId, String? peerId, int? display}) async {
  1735. if (bind
  1736. .mainGetEnv(key: "DISABLE_RUSTDESK_RESTORE_WINDOW_POSITION")
  1737. .isNotEmpty) {
  1738. return false;
  1739. }
  1740. if (type != WindowType.Main && windowId == null) {
  1741. debugPrint(
  1742. "Error: windowId cannot be null when saving positions for sub window");
  1743. return false;
  1744. }
  1745. bool isRemotePeerPos = false;
  1746. String? pos;
  1747. // No need to check mainGetLocalBoolOptionSync(kOptionOpenNewConnInTabs)
  1748. // Though "open in tabs" is true and the new window restore peer position, it's ok.
  1749. if (type == WindowType.RemoteDesktop && windowId != null && peerId != null) {
  1750. final peerPos = bind.mainGetPeerFlutterOptionSync(
  1751. id: peerId, k: windowFramePrefix + type.name);
  1752. if (peerPos.isNotEmpty) {
  1753. pos = peerPos;
  1754. }
  1755. isRemotePeerPos = pos != null;
  1756. }
  1757. pos ??= bind.getLocalFlutterOption(k: windowFramePrefix + type.name);
  1758. var lpos = LastWindowPosition.loadFromString(pos);
  1759. if (lpos == null) {
  1760. debugPrint("no window position saved, ignoring position restoration");
  1761. return false;
  1762. }
  1763. if (type == WindowType.RemoteDesktop) {
  1764. if (!isRemotePeerPos && windowId != null) {
  1765. if (lpos.offsetWidth != null) {
  1766. lpos.offsetWidth = lpos.offsetWidth! + windowId * kNewWindowOffset;
  1767. }
  1768. if (lpos.offsetHeight != null) {
  1769. lpos.offsetHeight = lpos.offsetHeight! + windowId * kNewWindowOffset;
  1770. }
  1771. }
  1772. if (display != null) {
  1773. if (lpos.offsetWidth != null) {
  1774. lpos.offsetWidth = lpos.offsetWidth! + display * kNewWindowOffset;
  1775. }
  1776. if (lpos.offsetHeight != null) {
  1777. lpos.offsetHeight = lpos.offsetHeight! + display * kNewWindowOffset;
  1778. }
  1779. }
  1780. }
  1781. final size = await _adjustRestoreMainWindowSize(lpos.width, lpos.height);
  1782. final offsetDevicePixelRatio = await _adjustRestoreMainWindowOffset(
  1783. lpos.offsetWidth,
  1784. lpos.offsetHeight,
  1785. size.width,
  1786. size.height,
  1787. );
  1788. debugPrint(
  1789. "restore lpos: ${size.width}/${size.height}, offset:${offsetDevicePixelRatio?.offset.dx}/${offsetDevicePixelRatio?.offset.dy}, devicePixelRatio:${offsetDevicePixelRatio?.devicePixelRatio}, isMaximized: ${lpos.isMaximized}, isFullscreen: ${lpos.isFullscreen}");
  1790. switch (type) {
  1791. case WindowType.Main:
  1792. // https://github.com/rustdesk/rustdesk/issues/8038
  1793. // `setBounds()` in `window_manager` will use the current devicePixelRatio.
  1794. // So we need to adjust the offset by the scale factor.
  1795. // https://github.com/rustdesk-org/window_manager/blob/f19acdb008645366339444a359a45c3257c8b32e/windows/window_manager.cpp#L701
  1796. if (isWindows) {
  1797. double? curDevicePixelRatio;
  1798. Offset curPos = await windowManager.getPosition();
  1799. for (final screen in await window_size.getScreenList()) {
  1800. if (isPointInRect(curPos, screen.visibleFrame)) {
  1801. curDevicePixelRatio = screen.scaleFactor;
  1802. }
  1803. }
  1804. if (curDevicePixelRatio != null &&
  1805. curDevicePixelRatio != 0 &&
  1806. offsetDevicePixelRatio != null) {
  1807. if (offsetDevicePixelRatio.devicePixelRatio != 0) {
  1808. final scale =
  1809. offsetDevicePixelRatio.devicePixelRatio / curDevicePixelRatio;
  1810. offsetDevicePixelRatio.offset =
  1811. offsetDevicePixelRatio.offset.scale(scale, scale);
  1812. debugPrint(
  1813. "restore new offset: ${offsetDevicePixelRatio.offset.dx}/${offsetDevicePixelRatio.offset.dy}, scale:$scale");
  1814. }
  1815. }
  1816. }
  1817. restorePos() async {
  1818. if (offsetDevicePixelRatio == null) {
  1819. await windowManager.center();
  1820. } else {
  1821. await windowManager.setPosition(offsetDevicePixelRatio.offset);
  1822. }
  1823. }
  1824. if (lpos.isMaximized == true) {
  1825. await restorePos();
  1826. if (!(bind.isIncomingOnly() || bind.isOutgoingOnly())) {
  1827. await windowManager.maximize();
  1828. }
  1829. } else {
  1830. if (!bind.isIncomingOnly() || bind.isOutgoingOnly()) {
  1831. await windowManager.setSize(size);
  1832. }
  1833. await restorePos();
  1834. }
  1835. return true;
  1836. default:
  1837. final wc = WindowController.fromWindowId(windowId!);
  1838. restoreFrame() async {
  1839. if (offsetDevicePixelRatio == null) {
  1840. await wc.center();
  1841. } else {
  1842. final frame = Rect.fromLTWH(offsetDevicePixelRatio.offset.dx,
  1843. offsetDevicePixelRatio.offset.dy, size.width, size.height);
  1844. await wc.setFrame(frame);
  1845. }
  1846. }
  1847. if (lpos.isFullscreen == true) {
  1848. if (!isMacOS) {
  1849. await restoreFrame();
  1850. }
  1851. // An duration is needed to avoid the window being restored after fullscreen.
  1852. Future.delayed(Duration(milliseconds: 300), () async {
  1853. if (kWindowId == windowId) {
  1854. stateGlobal.setFullscreen(true);
  1855. } else {
  1856. // If is not current window, we need to send a fullscreen message to `windowId`
  1857. DesktopMultiWindow.invokeMethod(
  1858. windowId, kWindowEventSetFullscreen, 'true');
  1859. }
  1860. });
  1861. } else if (lpos.isMaximized == true) {
  1862. await restoreFrame();
  1863. // An duration is needed to avoid the window being restored after maximized.
  1864. Future.delayed(Duration(milliseconds: 300), () async {
  1865. await wc.maximize();
  1866. });
  1867. } else {
  1868. await restoreFrame();
  1869. }
  1870. break;
  1871. }
  1872. return false;
  1873. }
  1874. var webInitialLink = "";
  1875. /// Initialize uni links for macos/windows
  1876. ///
  1877. /// [Availability]
  1878. /// initUniLinks should only be used on macos/windows.
  1879. /// we use dbus for linux currently.
  1880. Future<bool> initUniLinks() async {
  1881. if (isLinux) {
  1882. return false;
  1883. }
  1884. // check cold boot
  1885. try {
  1886. final initialLink = await getInitialLink();
  1887. print("initialLink: $initialLink");
  1888. if (initialLink == null || initialLink.isEmpty) {
  1889. return false;
  1890. }
  1891. if (isWeb) {
  1892. webInitialLink = initialLink;
  1893. return false;
  1894. } else {
  1895. return handleUriLink(uriString: initialLink);
  1896. }
  1897. } catch (err) {
  1898. debugPrintStack(label: "$err");
  1899. return false;
  1900. }
  1901. }
  1902. /// Listen for uni links.
  1903. ///
  1904. /// * handleByFlutter: Should uni links be handled by Flutter.
  1905. ///
  1906. /// Returns a [StreamSubscription] which can listen the uni links.
  1907. StreamSubscription? listenUniLinks({handleByFlutter = true}) {
  1908. if (isLinux || isWeb) {
  1909. return null;
  1910. }
  1911. final sub = uriLinkStream.listen((Uri? uri) {
  1912. debugPrint("A uri was received: $uri. handleByFlutter $handleByFlutter");
  1913. if (uri != null) {
  1914. if (handleByFlutter) {
  1915. handleUriLink(uri: uri);
  1916. } else {
  1917. bind.sendUrlScheme(url: uri.toString());
  1918. }
  1919. } else {
  1920. print("uni listen error: uri is empty.");
  1921. }
  1922. }, onError: (err) {
  1923. print("uni links error: $err");
  1924. });
  1925. return sub;
  1926. }
  1927. enum UriLinkType {
  1928. remoteDesktop,
  1929. fileTransfer,
  1930. portForward,
  1931. rdp,
  1932. }
  1933. // uri link handler
  1934. bool handleUriLink({List<String>? cmdArgs, Uri? uri, String? uriString}) {
  1935. List<String>? args;
  1936. if (cmdArgs != null && cmdArgs.isNotEmpty) {
  1937. args = cmdArgs;
  1938. // rustdesk <uri link>
  1939. if (args[0].startsWith(bind.mainUriPrefixSync())) {
  1940. final uri = Uri.tryParse(args[0]);
  1941. if (uri != null) {
  1942. args = urlLinkToCmdArgs(uri);
  1943. }
  1944. }
  1945. } else if (uri != null) {
  1946. args = urlLinkToCmdArgs(uri);
  1947. } else if (uriString != null) {
  1948. final uri = Uri.tryParse(uriString);
  1949. if (uri != null) {
  1950. args = urlLinkToCmdArgs(uri);
  1951. }
  1952. }
  1953. if (args == null) {
  1954. return false;
  1955. }
  1956. if (args.isEmpty) {
  1957. windowOnTop(null);
  1958. return true;
  1959. }
  1960. UriLinkType? type;
  1961. String? id;
  1962. String? password;
  1963. String? switchUuid;
  1964. bool? forceRelay;
  1965. for (int i = 0; i < args.length; i++) {
  1966. switch (args[i]) {
  1967. case '--connect':
  1968. case '--play':
  1969. type = UriLinkType.remoteDesktop;
  1970. id = args[i + 1];
  1971. i++;
  1972. break;
  1973. case '--file-transfer':
  1974. type = UriLinkType.fileTransfer;
  1975. id = args[i + 1];
  1976. i++;
  1977. break;
  1978. case '--port-forward':
  1979. type = UriLinkType.portForward;
  1980. id = args[i + 1];
  1981. i++;
  1982. break;
  1983. case '--rdp':
  1984. type = UriLinkType.rdp;
  1985. id = args[i + 1];
  1986. i++;
  1987. break;
  1988. case '--password':
  1989. password = args[i + 1];
  1990. i++;
  1991. break;
  1992. case '--switch_uuid':
  1993. switchUuid = args[i + 1];
  1994. i++;
  1995. break;
  1996. case '--relay':
  1997. forceRelay = true;
  1998. break;
  1999. default:
  2000. break;
  2001. }
  2002. }
  2003. if (type != null && id != null) {
  2004. switch (type) {
  2005. case UriLinkType.remoteDesktop:
  2006. Future.delayed(Duration.zero, () {
  2007. rustDeskWinManager.newRemoteDesktop(id!,
  2008. password: password,
  2009. switchUuid: switchUuid,
  2010. forceRelay: forceRelay);
  2011. });
  2012. break;
  2013. case UriLinkType.fileTransfer:
  2014. Future.delayed(Duration.zero, () {
  2015. rustDeskWinManager.newFileTransfer(id!,
  2016. password: password, forceRelay: forceRelay);
  2017. });
  2018. break;
  2019. case UriLinkType.portForward:
  2020. Future.delayed(Duration.zero, () {
  2021. rustDeskWinManager.newPortForward(id!, false,
  2022. password: password, forceRelay: forceRelay);
  2023. });
  2024. break;
  2025. case UriLinkType.rdp:
  2026. Future.delayed(Duration.zero, () {
  2027. rustDeskWinManager.newPortForward(id!, true,
  2028. password: password, forceRelay: forceRelay);
  2029. });
  2030. break;
  2031. }
  2032. return true;
  2033. }
  2034. return false;
  2035. }
  2036. List<String>? urlLinkToCmdArgs(Uri uri) {
  2037. String? command;
  2038. String? id;
  2039. final options = ["connect", "play", "file-transfer", "port-forward", "rdp"];
  2040. if (uri.authority.isEmpty &&
  2041. uri.path.split('').every((char) => char == '/')) {
  2042. return [];
  2043. } else if (uri.authority == "connection" && uri.path.startsWith("/new/")) {
  2044. // For compatibility
  2045. command = '--connect';
  2046. id = uri.path.substring("/new/".length);
  2047. } else if (uri.authority == "config") {
  2048. if (isAndroid || isIOS) {
  2049. final config = uri.path.substring("/".length);
  2050. // add a timer to make showToast work
  2051. Timer(Duration(seconds: 1), () {
  2052. importConfig(null, null, config);
  2053. });
  2054. }
  2055. return null;
  2056. } else if (uri.authority == "password") {
  2057. if (isAndroid || isIOS) {
  2058. final password = uri.path.substring("/".length);
  2059. if (password.isNotEmpty) {
  2060. Timer(Duration(seconds: 1), () async {
  2061. await bind.mainSetPermanentPassword(password: password);
  2062. showToast(translate('Successful'));
  2063. });
  2064. }
  2065. }
  2066. } else if (options.contains(uri.authority)) {
  2067. final optionIndex = options.indexOf(uri.authority);
  2068. command = '--${uri.authority}';
  2069. if (uri.path.length > 1) {
  2070. id = uri.path.substring(1);
  2071. }
  2072. if (isMobile && id != null) {
  2073. if (optionIndex == 0 || optionIndex == 1) {
  2074. connect(Get.context!, id);
  2075. } else if (optionIndex == 2) {
  2076. connect(Get.context!, id, isFileTransfer: true);
  2077. }
  2078. return null;
  2079. }
  2080. } else if (uri.authority.length > 2 &&
  2081. (uri.path.length <= 1 ||
  2082. (uri.path == '/r' || uri.path.startsWith('/r@')))) {
  2083. // rustdesk://<connect-id>
  2084. // rustdesk://<connect-id>/r
  2085. // rustdesk://<connect-id>/r@<server>
  2086. command = '--connect';
  2087. id = uri.authority;
  2088. if (uri.path.length > 1) {
  2089. id = id + uri.path;
  2090. }
  2091. }
  2092. var key = uri.queryParameters["key"];
  2093. if (id != null) {
  2094. if (key != null) {
  2095. id = "$id?key=$key";
  2096. }
  2097. }
  2098. if (isMobile) {
  2099. if (id != null) {
  2100. final forceRelay = uri.queryParameters["relay"] != null;
  2101. connect(Get.context!, id, forceRelay: forceRelay);
  2102. return null;
  2103. }
  2104. }
  2105. List<String> args = List.empty(growable: true);
  2106. if (command != null && id != null) {
  2107. args.add(command);
  2108. args.add(id);
  2109. var param = uri.queryParameters;
  2110. String? password = param["password"];
  2111. if (password != null) args.addAll(['--password', password]);
  2112. String? switch_uuid = param["switch_uuid"];
  2113. if (switch_uuid != null) args.addAll(['--switch_uuid', switch_uuid]);
  2114. if (param["relay"] != null) args.add("--relay");
  2115. return args;
  2116. }
  2117. return null;
  2118. }
  2119. connectMainDesktop(String id,
  2120. {required bool isFileTransfer,
  2121. required bool isTcpTunneling,
  2122. required bool isRDP,
  2123. bool? forceRelay,
  2124. String? password,
  2125. bool? isSharedPassword}) async {
  2126. if (isFileTransfer) {
  2127. await rustDeskWinManager.newFileTransfer(id,
  2128. password: password,
  2129. isSharedPassword: isSharedPassword,
  2130. forceRelay: forceRelay);
  2131. } else if (isTcpTunneling || isRDP) {
  2132. await rustDeskWinManager.newPortForward(id, isRDP,
  2133. password: password,
  2134. isSharedPassword: isSharedPassword,
  2135. forceRelay: forceRelay);
  2136. } else {
  2137. await rustDeskWinManager.newRemoteDesktop(id,
  2138. password: password,
  2139. isSharedPassword: isSharedPassword,
  2140. forceRelay: forceRelay);
  2141. }
  2142. }
  2143. /// Connect to a peer with [id].
  2144. /// If [isFileTransfer], starts a session only for file transfer.
  2145. /// If [isTcpTunneling], starts a session only for tcp tunneling.
  2146. /// If [isRDP], starts a session only for rdp.
  2147. connect(BuildContext context, String id,
  2148. {bool isFileTransfer = false,
  2149. bool isTcpTunneling = false,
  2150. bool isRDP = false,
  2151. bool forceRelay = false,
  2152. String? password,
  2153. bool? isSharedPassword}) async {
  2154. if (id == '') return;
  2155. if (!isDesktop || desktopType == DesktopType.main) {
  2156. try {
  2157. if (Get.isRegistered<IDTextEditingController>()) {
  2158. final idController = Get.find<IDTextEditingController>();
  2159. idController.text = formatID(id);
  2160. }
  2161. if (Get.isRegistered<TextEditingController>()) {
  2162. final fieldTextEditingController = Get.find<TextEditingController>();
  2163. fieldTextEditingController.text = formatID(id);
  2164. }
  2165. } catch (_) {}
  2166. }
  2167. id = id.replaceAll(' ', '');
  2168. final oldId = id;
  2169. id = await bind.mainHandleRelayId(id: id);
  2170. final forceRelay2 = id != oldId || forceRelay;
  2171. assert(!(isFileTransfer && isTcpTunneling && isRDP),
  2172. "more than one connect type");
  2173. if (isDesktop) {
  2174. if (desktopType == DesktopType.main) {
  2175. await connectMainDesktop(
  2176. id,
  2177. isFileTransfer: isFileTransfer,
  2178. isTcpTunneling: isTcpTunneling,
  2179. isRDP: isRDP,
  2180. password: password,
  2181. isSharedPassword: isSharedPassword,
  2182. forceRelay: forceRelay2,
  2183. );
  2184. } else {
  2185. await rustDeskWinManager.call(WindowType.Main, kWindowConnect, {
  2186. 'id': id,
  2187. 'isFileTransfer': isFileTransfer,
  2188. 'isTcpTunneling': isTcpTunneling,
  2189. 'isRDP': isRDP,
  2190. 'password': password,
  2191. 'isSharedPassword': isSharedPassword,
  2192. 'forceRelay': forceRelay,
  2193. });
  2194. }
  2195. } else {
  2196. if (isFileTransfer) {
  2197. if (isAndroid) {
  2198. if (!await AndroidPermissionManager.check(kManageExternalStorage)) {
  2199. if (!await AndroidPermissionManager.request(kManageExternalStorage)) {
  2200. return;
  2201. }
  2202. }
  2203. }
  2204. if (isWeb) {
  2205. Navigator.push(
  2206. context,
  2207. MaterialPageRoute(
  2208. builder: (BuildContext context) =>
  2209. desktop_file_manager.FileManagerPage(
  2210. id: id,
  2211. password: password,
  2212. isSharedPassword: isSharedPassword),
  2213. ),
  2214. );
  2215. } else {
  2216. Navigator.push(
  2217. context,
  2218. MaterialPageRoute(
  2219. builder: (BuildContext context) => FileManagerPage(
  2220. id: id, password: password, isSharedPassword: isSharedPassword),
  2221. ),
  2222. );
  2223. }
  2224. } else {
  2225. if (isWeb) {
  2226. Navigator.push(
  2227. context,
  2228. MaterialPageRoute(
  2229. builder: (BuildContext context) => desktop_remote.RemotePage(
  2230. key: ValueKey(id),
  2231. id: id,
  2232. toolbarState: ToolbarState(),
  2233. password: password,
  2234. forceRelay: forceRelay,
  2235. isSharedPassword: isSharedPassword,
  2236. ),
  2237. ),
  2238. );
  2239. } else {
  2240. Navigator.push(
  2241. context,
  2242. MaterialPageRoute(
  2243. builder: (BuildContext context) => RemotePage(
  2244. id: id, password: password, isSharedPassword: isSharedPassword),
  2245. ),
  2246. );
  2247. }
  2248. }
  2249. stateGlobal.isInMainPage = false;
  2250. }
  2251. FocusScopeNode currentFocus = FocusScope.of(context);
  2252. if (!currentFocus.hasPrimaryFocus) {
  2253. currentFocus.unfocus();
  2254. }
  2255. }
  2256. Map<String, String> getHttpHeaders() {
  2257. return {
  2258. 'Authorization': 'Bearer ${bind.mainGetLocalOption(key: 'access_token')}'
  2259. };
  2260. }
  2261. // Simple wrapper of built-in types for reference use.
  2262. class SimpleWrapper<T> {
  2263. T value;
  2264. SimpleWrapper(this.value);
  2265. }
  2266. /// call this to reload current window.
  2267. ///
  2268. /// [Note]
  2269. /// Must have [RefreshWrapper] on the top of widget tree.
  2270. void reloadCurrentWindow() {
  2271. if (Get.context != null) {
  2272. // reload self window
  2273. RefreshWrapper.of(Get.context!)?.rebuild();
  2274. } else {
  2275. debugPrint(
  2276. "reload current window failed, global BuildContext does not exist");
  2277. }
  2278. }
  2279. /// call this to reload all windows, including main + all sub windows.
  2280. Future<void> reloadAllWindows() async {
  2281. reloadCurrentWindow();
  2282. try {
  2283. final ids = await DesktopMultiWindow.getAllSubWindowIds();
  2284. for (final id in ids) {
  2285. DesktopMultiWindow.invokeMethod(id, kWindowActionRebuild);
  2286. }
  2287. } on AssertionError {
  2288. // ignore
  2289. }
  2290. }
  2291. /// Indicate the flutter app is running in portable mode.
  2292. ///
  2293. /// [Note]
  2294. /// Portable build is only available on Windows.
  2295. bool isRunningInPortableMode() {
  2296. if (!isWindows) {
  2297. return false;
  2298. }
  2299. return bool.hasEnvironment(kEnvPortableExecutable);
  2300. }
  2301. /// Window status callback
  2302. Future<void> onActiveWindowChanged() async {
  2303. print(
  2304. "[MultiWindowHandler] active window changed: ${rustDeskWinManager.getActiveWindows()}");
  2305. if (rustDeskWinManager.getActiveWindows().isEmpty) {
  2306. // close all sub windows
  2307. try {
  2308. if (isLinux) {
  2309. await Future.wait([
  2310. saveWindowPosition(WindowType.Main),
  2311. rustDeskWinManager.closeAllSubWindows()
  2312. ]);
  2313. } else {
  2314. await rustDeskWinManager.closeAllSubWindows();
  2315. }
  2316. } catch (err) {
  2317. debugPrintStack(label: "$err");
  2318. } finally {
  2319. debugPrint("Start closing RustDesk...");
  2320. await windowManager.setPreventClose(false);
  2321. await windowManager.close();
  2322. if (isMacOS) {
  2323. // If we call without delay, `flutter/macos/Runner/MainFlutterWindow.swift` can handle the "terminate" event.
  2324. // But the app will not close.
  2325. //
  2326. // No idea why we need to delay here, `terminate()` itself is also an async function.
  2327. Future.delayed(Duration.zero, () {
  2328. RdPlatformChannel.instance.terminate();
  2329. });
  2330. }
  2331. }
  2332. }
  2333. }
  2334. Timer periodic_immediate(Duration duration, Future<void> Function() callback) {
  2335. Future.delayed(Duration.zero, callback);
  2336. return Timer.periodic(duration, (timer) async {
  2337. await callback();
  2338. });
  2339. }
  2340. /// return a human readable windows version
  2341. WindowsTarget getWindowsTarget(int buildNumber) {
  2342. if (!isWindows) {
  2343. return WindowsTarget.naw;
  2344. }
  2345. if (buildNumber >= 22000) {
  2346. return WindowsTarget.w11;
  2347. } else if (buildNumber >= 10240) {
  2348. return WindowsTarget.w10;
  2349. } else if (buildNumber >= 9600) {
  2350. return WindowsTarget.w8_1;
  2351. } else if (buildNumber >= 9200) {
  2352. return WindowsTarget.w8;
  2353. } else if (buildNumber >= 7601) {
  2354. return WindowsTarget.w7;
  2355. } else if (buildNumber >= 6002) {
  2356. return WindowsTarget.vista;
  2357. } else {
  2358. // minimum support
  2359. return WindowsTarget.xp;
  2360. }
  2361. }
  2362. /// Get windows target build number.
  2363. ///
  2364. /// [Note]
  2365. /// Please use this function wrapped with `Platform.isWindows`.
  2366. int getWindowsTargetBuildNumber() {
  2367. return getWindowsTargetBuildNumber_();
  2368. }
  2369. /// Indicating we need to use compatible ui mode.
  2370. ///
  2371. /// [Conditions]
  2372. /// - Windows 7, window will overflow when we use frameless ui.
  2373. bool get kUseCompatibleUiMode =>
  2374. isWindows &&
  2375. const [WindowsTarget.w7].contains(windowsBuildNumber.windowsVersion);
  2376. class ServerConfig {
  2377. late String idServer;
  2378. late String relayServer;
  2379. late String apiServer;
  2380. late String key;
  2381. ServerConfig(
  2382. {String? idServer, String? relayServer, String? apiServer, String? key}) {
  2383. this.idServer = idServer?.trim() ?? '';
  2384. this.relayServer = relayServer?.trim() ?? '';
  2385. this.apiServer = apiServer?.trim() ?? '';
  2386. this.key = key?.trim() ?? '';
  2387. }
  2388. /// decode from shared string (from user shared or rustdesk-server generated)
  2389. /// also see [encode]
  2390. /// throw when decoding failure
  2391. ServerConfig.decode(String msg) {
  2392. var json = {};
  2393. try {
  2394. // back compatible
  2395. json = jsonDecode(msg);
  2396. } catch (err) {
  2397. final input = msg.split('').reversed.join('');
  2398. final bytes = base64Decode(base64.normalize(input));
  2399. json = jsonDecode(utf8.decode(bytes));
  2400. }
  2401. idServer = json['host'] ?? '';
  2402. relayServer = json['relay'] ?? '';
  2403. apiServer = json['api'] ?? '';
  2404. key = json['key'] ?? '';
  2405. }
  2406. /// encode to shared string
  2407. /// also see [ServerConfig.decode]
  2408. String encode() {
  2409. Map<String, String> config = {};
  2410. config['host'] = idServer.trim();
  2411. config['relay'] = relayServer.trim();
  2412. config['api'] = apiServer.trim();
  2413. config['key'] = key.trim();
  2414. return base64Encode(Uint8List.fromList(jsonEncode(config).codeUnits))
  2415. .split('')
  2416. .reversed
  2417. .join();
  2418. }
  2419. /// from local options
  2420. ServerConfig.fromOptions(Map<String, dynamic> options)
  2421. : idServer = options['custom-rendezvous-server'] ?? "",
  2422. relayServer = options['relay-server'] ?? "",
  2423. apiServer = options['api-server'] ?? "",
  2424. key = options['key'] ?? "";
  2425. }
  2426. Widget dialogButton(String text,
  2427. {required VoidCallback? onPressed,
  2428. bool isOutline = false,
  2429. Widget? icon,
  2430. TextStyle? style,
  2431. ButtonStyle? buttonStyle}) {
  2432. if (isDesktop || isWebDesktop) {
  2433. if (isOutline) {
  2434. return icon == null
  2435. ? OutlinedButton(
  2436. onPressed: onPressed,
  2437. child: Text(translate(text), style: style),
  2438. )
  2439. : OutlinedButton.icon(
  2440. icon: icon,
  2441. onPressed: onPressed,
  2442. label: Text(translate(text), style: style),
  2443. );
  2444. } else {
  2445. return icon == null
  2446. ? ElevatedButton(
  2447. style: ElevatedButton.styleFrom(elevation: 0).merge(buttonStyle),
  2448. onPressed: onPressed,
  2449. child: Text(translate(text), style: style),
  2450. )
  2451. : ElevatedButton.icon(
  2452. icon: icon,
  2453. style: ElevatedButton.styleFrom(elevation: 0).merge(buttonStyle),
  2454. onPressed: onPressed,
  2455. label: Text(translate(text), style: style),
  2456. );
  2457. }
  2458. } else {
  2459. return TextButton(
  2460. onPressed: onPressed,
  2461. child: Text(
  2462. translate(text),
  2463. style: style,
  2464. ),
  2465. );
  2466. }
  2467. }
  2468. int versionCmp(String v1, String v2) {
  2469. return bind.versionToNumber(v: v1) - bind.versionToNumber(v: v2);
  2470. }
  2471. String getWindowName({WindowType? overrideType}) {
  2472. final name = bind.mainGetAppNameSync();
  2473. switch (overrideType ?? kWindowType) {
  2474. case WindowType.Main:
  2475. return name;
  2476. case WindowType.FileTransfer:
  2477. return "File Transfer - $name";
  2478. case WindowType.PortForward:
  2479. return "Port Forward - $name";
  2480. case WindowType.RemoteDesktop:
  2481. return "Remote Desktop - $name";
  2482. default:
  2483. break;
  2484. }
  2485. return name;
  2486. }
  2487. String getWindowNameWithId(String id, {WindowType? overrideType}) {
  2488. return "${DesktopTab.tablabelGetter(id).value} - ${getWindowName(overrideType: overrideType)}";
  2489. }
  2490. Future<void> updateSystemWindowTheme() async {
  2491. // Set system window theme for macOS.
  2492. final userPreference = MyTheme.getThemeModePreference();
  2493. if (userPreference != ThemeMode.system) {
  2494. if (isMacOS) {
  2495. await RdPlatformChannel.instance.changeSystemWindowTheme(
  2496. userPreference == ThemeMode.light
  2497. ? SystemWindowTheme.light
  2498. : SystemWindowTheme.dark);
  2499. }
  2500. }
  2501. }
  2502. /// macOS only
  2503. ///
  2504. /// Note: not found a general solution for rust based AVFoundation bingding.
  2505. /// [AVFoundation] crate has compile error.
  2506. const kMacOSPermChannel = MethodChannel("org.rustdesk.rustdesk/macos");
  2507. enum PermissionAuthorizeType {
  2508. undetermined,
  2509. authorized,
  2510. denied, // and restricted
  2511. }
  2512. Future<PermissionAuthorizeType> osxCanRecordAudio() async {
  2513. int res = await kMacOSPermChannel.invokeMethod("canRecordAudio");
  2514. print(res);
  2515. if (res > 0) {
  2516. return PermissionAuthorizeType.authorized;
  2517. } else if (res == 0) {
  2518. return PermissionAuthorizeType.undetermined;
  2519. } else {
  2520. return PermissionAuthorizeType.denied;
  2521. }
  2522. }
  2523. Future<bool> osxRequestAudio() async {
  2524. return await kMacOSPermChannel.invokeMethod("requestRecordAudio");
  2525. }
  2526. class DraggableNeverScrollableScrollPhysics extends ScrollPhysics {
  2527. /// Creates scroll physics that does not let the user scroll.
  2528. const DraggableNeverScrollableScrollPhysics({super.parent});
  2529. @override
  2530. DraggableNeverScrollableScrollPhysics applyTo(ScrollPhysics? ancestor) {
  2531. return DraggableNeverScrollableScrollPhysics(parent: buildParent(ancestor));
  2532. }
  2533. @override
  2534. bool shouldAcceptUserOffset(ScrollMetrics position) {
  2535. // TODO: find a better solution to check if the offset change is caused by the scrollbar.
  2536. // Workaround: when dragging with the scrollbar, it always triggers an [IdleScrollActivity].
  2537. if (position is ScrollPositionWithSingleContext) {
  2538. // ignore: invalid_use_of_protected_member, invalid_use_of_visible_for_testing_member
  2539. return position.activity is IdleScrollActivity;
  2540. }
  2541. return false;
  2542. }
  2543. @override
  2544. bool get allowImplicitScrolling => false;
  2545. }
  2546. Widget futureBuilder(
  2547. {required Future? future, required Widget Function(dynamic data) hasData}) {
  2548. return FutureBuilder(
  2549. future: future,
  2550. builder: (BuildContext context, AsyncSnapshot snapshot) {
  2551. if (snapshot.hasData) {
  2552. return hasData(snapshot.data!);
  2553. } else {
  2554. if (snapshot.hasError) {
  2555. debugPrint(snapshot.error.toString());
  2556. }
  2557. return Container();
  2558. }
  2559. });
  2560. }
  2561. void onCopyFingerprint(String value) {
  2562. if (value.isNotEmpty) {
  2563. Clipboard.setData(ClipboardData(text: value));
  2564. showToast('$value\n${translate("Copied")}');
  2565. } else {
  2566. showToast(translate("no fingerprints"));
  2567. }
  2568. }
  2569. Future<bool> callMainCheckSuperUserPermission() async {
  2570. bool checked = await bind.mainCheckSuperUserPermission();
  2571. if (isMacOS) {
  2572. await windowManager.show();
  2573. }
  2574. return checked;
  2575. }
  2576. Future<void> start_service(bool is_start) async {
  2577. bool checked = !bind.mainIsInstalled() ||
  2578. !isMacOS ||
  2579. await callMainCheckSuperUserPermission();
  2580. if (checked) {
  2581. mainSetBoolOption(kOptionStopService, !is_start);
  2582. }
  2583. }
  2584. Future<bool> canBeBlocked() async {
  2585. var access_mode = await bind.mainGetOption(key: kOptionAccessMode);
  2586. var option = option2bool(kOptionAllowRemoteConfigModification,
  2587. await bind.mainGetOption(key: kOptionAllowRemoteConfigModification));
  2588. return access_mode == 'view' || (access_mode.isEmpty && !option);
  2589. }
  2590. Future<void> shouldBeBlocked(RxBool block, WhetherUseRemoteBlock? use) async {
  2591. if (use != null && !await use()) {
  2592. block.value = false;
  2593. return;
  2594. }
  2595. var time0 = DateTime.now().millisecondsSinceEpoch;
  2596. await bind.mainCheckMouseTime();
  2597. Timer(const Duration(milliseconds: 120), () async {
  2598. var d = time0 - await bind.mainGetMouseTime();
  2599. if (d < 120) {
  2600. block.value = true;
  2601. } else {
  2602. block.value = false;
  2603. }
  2604. });
  2605. }
  2606. typedef WhetherUseRemoteBlock = Future<bool> Function();
  2607. Widget buildRemoteBlock(
  2608. {required Widget child,
  2609. required RxBool block,
  2610. required bool mask,
  2611. WhetherUseRemoteBlock? use}) {
  2612. return Obx(() => MouseRegion(
  2613. onEnter: (_) async {
  2614. await shouldBeBlocked(block, use);
  2615. },
  2616. onExit: (event) => block.value = false,
  2617. child: Stack(children: [
  2618. // scope block tab
  2619. FocusScope(child: child, canRequestFocus: !block.value),
  2620. // mask block click, cm not block click and still use check_click_time to avoid block local click
  2621. if (mask)
  2622. Offstage(
  2623. offstage: !block.value,
  2624. child: Container(
  2625. color: Colors.black.withOpacity(0.5),
  2626. )),
  2627. ]),
  2628. ));
  2629. }
  2630. Widget unreadMessageCountBuilder(RxInt? count,
  2631. {double? size, double? fontSize}) {
  2632. return Obx(() => Offstage(
  2633. offstage: !((count?.value ?? 0) > 0),
  2634. child: Container(
  2635. width: size ?? 16,
  2636. height: size ?? 16,
  2637. decoration: BoxDecoration(
  2638. color: Colors.red,
  2639. shape: BoxShape.circle,
  2640. ),
  2641. child: Center(
  2642. child: Text("${count?.value ?? 0}",
  2643. maxLines: 1,
  2644. style: TextStyle(color: Colors.white, fontSize: fontSize ?? 10)),
  2645. ),
  2646. )));
  2647. }
  2648. Widget unreadTopRightBuilder(RxInt? count, {Widget? icon}) {
  2649. return Stack(
  2650. children: [
  2651. icon ?? Icon(Icons.chat),
  2652. Positioned(
  2653. top: 0,
  2654. right: 0,
  2655. child: unreadMessageCountBuilder(count, size: 12, fontSize: 8))
  2656. ],
  2657. );
  2658. }
  2659. String toCapitalized(String s) {
  2660. if (s.isEmpty) {
  2661. return s;
  2662. }
  2663. return s.substring(0, 1).toUpperCase() + s.substring(1);
  2664. }
  2665. Widget buildErrorBanner(BuildContext context,
  2666. {required RxBool loading,
  2667. required RxString err,
  2668. required Function? retry,
  2669. required Function close}) {
  2670. return Obx(() => Offstage(
  2671. offstage: !(!loading.value && err.value.isNotEmpty),
  2672. child: Center(
  2673. child: Container(
  2674. color: MyTheme.color(context).errorBannerBg,
  2675. child: Row(
  2676. mainAxisAlignment: MainAxisAlignment.center,
  2677. crossAxisAlignment: CrossAxisAlignment.center,
  2678. children: [
  2679. FittedBox(
  2680. child: Icon(
  2681. Icons.info,
  2682. color: Color.fromARGB(255, 249, 81, 81),
  2683. ),
  2684. ).marginAll(4),
  2685. Flexible(
  2686. child: Align(
  2687. alignment: Alignment.centerLeft,
  2688. child: Tooltip(
  2689. message: translate(err.value),
  2690. child: SelectableText(
  2691. translate(err.value),
  2692. ),
  2693. )).marginSymmetric(vertical: 2),
  2694. ),
  2695. if (retry != null)
  2696. InkWell(
  2697. onTap: () {
  2698. retry.call();
  2699. },
  2700. child: Text(
  2701. translate("Retry"),
  2702. style: TextStyle(color: MyTheme.accent),
  2703. )).marginSymmetric(horizontal: 5),
  2704. FittedBox(
  2705. child: InkWell(
  2706. onTap: () {
  2707. close.call();
  2708. },
  2709. child: Icon(Icons.close).marginSymmetric(horizontal: 5),
  2710. ),
  2711. ).marginAll(4)
  2712. ],
  2713. ),
  2714. )).marginOnly(bottom: 14),
  2715. ));
  2716. }
  2717. String getDesktopTabLabel(String peerId, String alias) {
  2718. String label = alias.isEmpty ? peerId : alias;
  2719. try {
  2720. String peer = bind.mainGetPeerSync(id: peerId);
  2721. Map<String, dynamic> config = jsonDecode(peer);
  2722. if (config['info']['hostname'] is String) {
  2723. String hostname = config['info']['hostname'];
  2724. if (hostname.isNotEmpty &&
  2725. !label.toLowerCase().contains(hostname.toLowerCase())) {
  2726. label += "@$hostname";
  2727. }
  2728. }
  2729. } catch (e) {
  2730. debugPrint("Failed to get hostname:$e");
  2731. }
  2732. return label;
  2733. }
  2734. sessionRefreshVideo(SessionID sessionId, PeerInfo pi) async {
  2735. if (pi.currentDisplay == kAllDisplayValue) {
  2736. for (int i = 0; i < pi.displays.length; i++) {
  2737. await bind.sessionRefresh(sessionId: sessionId, display: i);
  2738. }
  2739. } else {
  2740. await bind.sessionRefresh(sessionId: sessionId, display: pi.currentDisplay);
  2741. }
  2742. }
  2743. Future<List<Rect>> getScreenListWayland() async {
  2744. final screenRectList = <Rect>[];
  2745. if (isMainDesktopWindow) {
  2746. for (var screen in await window_size.getScreenList()) {
  2747. final scale = kIgnoreDpi ? 1.0 : screen.scaleFactor;
  2748. double l = screen.frame.left;
  2749. double t = screen.frame.top;
  2750. double r = screen.frame.right;
  2751. double b = screen.frame.bottom;
  2752. final rect = Rect.fromLTRB(l / scale, t / scale, r / scale, b / scale);
  2753. screenRectList.add(rect);
  2754. }
  2755. } else {
  2756. final screenList = await rustDeskWinManager.call(
  2757. WindowType.Main, kWindowGetScreenList, '');
  2758. try {
  2759. for (var screen in jsonDecode(screenList.result) as List<dynamic>) {
  2760. final scale = kIgnoreDpi ? 1.0 : screen['scaleFactor'];
  2761. double l = screen['frame']['l'];
  2762. double t = screen['frame']['t'];
  2763. double r = screen['frame']['r'];
  2764. double b = screen['frame']['b'];
  2765. final rect = Rect.fromLTRB(l / scale, t / scale, r / scale, b / scale);
  2766. screenRectList.add(rect);
  2767. }
  2768. } catch (e) {
  2769. debugPrint('Failed to parse screenList: $e');
  2770. }
  2771. }
  2772. return screenRectList;
  2773. }
  2774. Future<List<Rect>> getScreenListNotWayland() async {
  2775. final screenRectList = <Rect>[];
  2776. final displays = bind.mainGetDisplays();
  2777. if (displays.isEmpty) {
  2778. return screenRectList;
  2779. }
  2780. try {
  2781. for (var display in jsonDecode(displays) as List<dynamic>) {
  2782. // to-do: scale factor ?
  2783. // final scale = kIgnoreDpi ? 1.0 : screen.scaleFactor;
  2784. double l = display['x'].toDouble();
  2785. double t = display['y'].toDouble();
  2786. double r = (display['x'] + display['w']).toDouble();
  2787. double b = (display['y'] + display['h']).toDouble();
  2788. screenRectList.add(Rect.fromLTRB(l, t, r, b));
  2789. }
  2790. } catch (e) {
  2791. debugPrint('Failed to parse displays: $e');
  2792. }
  2793. return screenRectList;
  2794. }
  2795. Future<List<Rect>> getScreenRectList() async {
  2796. return bind.mainCurrentIsWayland()
  2797. ? await getScreenListWayland()
  2798. : await getScreenListNotWayland();
  2799. }
  2800. openMonitorInTheSameTab(int i, FFI ffi, PeerInfo pi,
  2801. {bool updateCursorPos = true}) {
  2802. final displays = i == kAllDisplayValue
  2803. ? List.generate(pi.displays.length, (index) => index)
  2804. : [i];
  2805. // Try clear image model before switching from all displays
  2806. // 1. The remote side has multiple displays.
  2807. // 2. Do not use texture render.
  2808. // 3. Connect to Display 1.
  2809. // 4. Switch to multi-displays `kAllDisplayValue`
  2810. // 5. Switch to Display 2.
  2811. // Then the remote page will display last picture of Display 1 at the beginning.
  2812. if (pi.forceTextureRender && i != kAllDisplayValue) {
  2813. ffi.imageModel.clearImage();
  2814. }
  2815. bind.sessionSwitchDisplay(
  2816. isDesktop: isDesktop,
  2817. sessionId: ffi.sessionId,
  2818. value: Int32List.fromList(displays),
  2819. );
  2820. ffi.ffiModel.switchToNewDisplay(i, ffi.sessionId, ffi.id,
  2821. updateCursorPos: updateCursorPos);
  2822. }
  2823. // Open new tab or window to show this monitor.
  2824. // For now just open new window.
  2825. //
  2826. // screenRect is used to move the new window to the specified screen and set fullscreen.
  2827. openMonitorInNewTabOrWindow(int i, String peerId, PeerInfo pi,
  2828. {Rect? screenRect}) {
  2829. final args = {
  2830. 'window_id': stateGlobal.windowId,
  2831. 'peer_id': peerId,
  2832. 'display': i,
  2833. 'display_count': pi.displays.length,
  2834. };
  2835. if (screenRect != null) {
  2836. args['screen_rect'] = {
  2837. 'l': screenRect.left,
  2838. 't': screenRect.top,
  2839. 'r': screenRect.right,
  2840. 'b': screenRect.bottom,
  2841. };
  2842. }
  2843. DesktopMultiWindow.invokeMethod(
  2844. kMainWindowId, kWindowEventOpenMonitorSession, jsonEncode(args));
  2845. }
  2846. setNewConnectWindowFrame(int windowId, String peerId, int preSessionCount,
  2847. int? display, Rect? screenRect) async {
  2848. if (screenRect == null) {
  2849. // Do not restore window position to new connection if there's a pre-session.
  2850. // https://github.com/rustdesk/rustdesk/discussions/8825
  2851. if (preSessionCount == 0) {
  2852. await restoreWindowPosition(WindowType.RemoteDesktop,
  2853. windowId: windowId, display: display, peerId: peerId);
  2854. }
  2855. } else {
  2856. await tryMoveToScreenAndSetFullscreen(screenRect);
  2857. }
  2858. }
  2859. tryMoveToScreenAndSetFullscreen(Rect? screenRect) async {
  2860. if (screenRect == null) {
  2861. return;
  2862. }
  2863. final wc = WindowController.fromWindowId(stateGlobal.windowId);
  2864. final curFrame = await wc.getFrame();
  2865. final frame =
  2866. Rect.fromLTWH(screenRect.left + 30, screenRect.top + 30, 600, 400);
  2867. if (stateGlobal.fullscreen.isTrue &&
  2868. curFrame.left <= frame.left &&
  2869. curFrame.top <= frame.top &&
  2870. curFrame.width >= frame.width &&
  2871. curFrame.height >= frame.height) {
  2872. return;
  2873. }
  2874. await wc.setFrame(frame);
  2875. // An duration is needed to avoid the window being restored after fullscreen.
  2876. Future.delayed(Duration(milliseconds: 300), () async {
  2877. stateGlobal.setFullscreen(true);
  2878. });
  2879. }
  2880. parseParamScreenRect(Map<String, dynamic> params) {
  2881. Rect? screenRect;
  2882. if (params['screen_rect'] != null) {
  2883. double l = params['screen_rect']['l'];
  2884. double t = params['screen_rect']['t'];
  2885. double r = params['screen_rect']['r'];
  2886. double b = params['screen_rect']['b'];
  2887. screenRect = Rect.fromLTRB(l, t, r, b);
  2888. }
  2889. return screenRect;
  2890. }
  2891. get isInputSourceFlutter => stateGlobal.getInputSource() == "Input source 2";
  2892. class _ReconnectCountDownButton extends StatefulWidget {
  2893. _ReconnectCountDownButton({
  2894. Key? key,
  2895. required this.second,
  2896. required this.onPressed,
  2897. }) : super(key: key);
  2898. final VoidCallback? onPressed;
  2899. final int second;
  2900. @override
  2901. State<_ReconnectCountDownButton> createState() =>
  2902. _ReconnectCountDownButtonState();
  2903. }
  2904. class _ReconnectCountDownButtonState extends State<_ReconnectCountDownButton> {
  2905. late int _countdownSeconds = widget.second;
  2906. Timer? _timer;
  2907. @override
  2908. void initState() {
  2909. super.initState();
  2910. _startCountdownTimer();
  2911. }
  2912. @override
  2913. void dispose() {
  2914. _timer?.cancel();
  2915. super.dispose();
  2916. }
  2917. void _startCountdownTimer() {
  2918. _timer = Timer.periodic(Duration(seconds: 1), (timer) {
  2919. if (_countdownSeconds <= 0) {
  2920. timer.cancel();
  2921. } else {
  2922. setState(() {
  2923. _countdownSeconds--;
  2924. });
  2925. }
  2926. });
  2927. }
  2928. @override
  2929. Widget build(BuildContext context) {
  2930. return dialogButton(
  2931. '${translate('Reconnect')} (${_countdownSeconds}s)',
  2932. onPressed: widget.onPressed,
  2933. isOutline: true,
  2934. );
  2935. }
  2936. }
  2937. importConfig(List<TextEditingController>? controllers, List<RxString>? errMsgs,
  2938. String? text) {
  2939. text = text?.trim();
  2940. if (text != null && text.isNotEmpty) {
  2941. try {
  2942. final sc = ServerConfig.decode(text);
  2943. if (isWeb || isIOS) {
  2944. sc.relayServer = '';
  2945. }
  2946. if (sc.idServer.isNotEmpty) {
  2947. Future<bool> success = setServerConfig(controllers, errMsgs, sc);
  2948. success.then((value) {
  2949. if (value) {
  2950. showToast(translate('Import server configuration successfully'));
  2951. } else {
  2952. showToast(translate('Invalid server configuration'));
  2953. }
  2954. });
  2955. } else {
  2956. showToast(translate('Invalid server configuration'));
  2957. }
  2958. return sc;
  2959. } catch (e) {
  2960. showToast(translate('Invalid server configuration'));
  2961. }
  2962. } else {
  2963. showToast(translate('Clipboard is empty'));
  2964. }
  2965. }
  2966. Future<bool> setServerConfig(
  2967. List<TextEditingController>? controllers,
  2968. List<RxString>? errMsgs,
  2969. ServerConfig config,
  2970. ) async {
  2971. String removeEndSlash(String input) {
  2972. if (input.endsWith('/')) {
  2973. return input.substring(0, input.length - 1);
  2974. }
  2975. return input;
  2976. }
  2977. config.idServer = removeEndSlash(config.idServer.trim());
  2978. config.relayServer = removeEndSlash(config.relayServer.trim());
  2979. config.apiServer = removeEndSlash(config.apiServer.trim());
  2980. config.key = config.key.trim();
  2981. if (controllers != null) {
  2982. controllers[0].text = config.idServer;
  2983. controllers[1].text = config.relayServer;
  2984. controllers[2].text = config.apiServer;
  2985. controllers[3].text = config.key;
  2986. }
  2987. // id
  2988. if (config.idServer.isNotEmpty && errMsgs != null) {
  2989. errMsgs[0].value = translate(await bind.mainTestIfValidServer(
  2990. server: config.idServer, testWithProxy: true));
  2991. if (errMsgs[0].isNotEmpty) {
  2992. return false;
  2993. }
  2994. }
  2995. // relay
  2996. if (config.relayServer.isNotEmpty && errMsgs != null) {
  2997. errMsgs[1].value = translate(await bind.mainTestIfValidServer(
  2998. server: config.relayServer, testWithProxy: true));
  2999. if (errMsgs[1].isNotEmpty) {
  3000. return false;
  3001. }
  3002. }
  3003. // api
  3004. if (config.apiServer.isNotEmpty && errMsgs != null) {
  3005. if (!config.apiServer.startsWith('http://') &&
  3006. !config.apiServer.startsWith('https://')) {
  3007. errMsgs[2].value =
  3008. '${translate("API Server")}: ${translate("invalid_http")}';
  3009. return false;
  3010. }
  3011. }
  3012. final oldApiServer = await bind.mainGetApiServer();
  3013. // should set one by one
  3014. await bind.mainSetOption(
  3015. key: 'custom-rendezvous-server', value: config.idServer);
  3016. await bind.mainSetOption(key: 'relay-server', value: config.relayServer);
  3017. await bind.mainSetOption(key: 'api-server', value: config.apiServer);
  3018. await bind.mainSetOption(key: 'key', value: config.key);
  3019. final newApiServer = await bind.mainGetApiServer();
  3020. if (oldApiServer.isNotEmpty &&
  3021. oldApiServer != newApiServer &&
  3022. gFFI.userModel.isLogin) {
  3023. gFFI.userModel.logOut(apiServer: oldApiServer);
  3024. }
  3025. return true;
  3026. }
  3027. ColorFilter? svgColor(Color? color) {
  3028. if (color == null) {
  3029. return null;
  3030. } else {
  3031. return ColorFilter.mode(color, BlendMode.srcIn);
  3032. }
  3033. }
  3034. // ignore: must_be_immutable
  3035. class ComboBox extends StatelessWidget {
  3036. late final List<String> keys;
  3037. late final List<String> values;
  3038. late final String initialKey;
  3039. late final Function(String key) onChanged;
  3040. late final bool enabled;
  3041. late String current;
  3042. ComboBox({
  3043. Key? key,
  3044. required this.keys,
  3045. required this.values,
  3046. required this.initialKey,
  3047. required this.onChanged,
  3048. this.enabled = true,
  3049. }) : super(key: key);
  3050. @override
  3051. Widget build(BuildContext context) {
  3052. var index = keys.indexOf(initialKey);
  3053. if (index < 0) {
  3054. index = 0;
  3055. }
  3056. var ref = values[index].obs;
  3057. current = keys[index];
  3058. return Container(
  3059. decoration: BoxDecoration(
  3060. border: Border.all(
  3061. color: enabled
  3062. ? MyTheme.color(context).border2 ?? MyTheme.border
  3063. : MyTheme.border,
  3064. ),
  3065. borderRadius:
  3066. BorderRadius.circular(8), //border raiuds of dropdown button
  3067. ),
  3068. height: 42, // should be the height of a TextField
  3069. child: Obx(() => DropdownButton<String>(
  3070. isExpanded: true,
  3071. value: ref.value,
  3072. elevation: 16,
  3073. underline: Container(),
  3074. style: TextStyle(
  3075. color: enabled
  3076. ? Theme.of(context).textTheme.titleMedium?.color
  3077. : disabledTextColor(context, enabled)),
  3078. icon: const Icon(
  3079. Icons.expand_more_sharp,
  3080. size: 20,
  3081. ).marginOnly(right: 15),
  3082. onChanged: enabled
  3083. ? (String? newValue) {
  3084. if (newValue != null && newValue != ref.value) {
  3085. ref.value = newValue;
  3086. current = newValue;
  3087. onChanged(keys[values.indexOf(newValue)]);
  3088. }
  3089. }
  3090. : null,
  3091. items: values.map<DropdownMenuItem<String>>((String value) {
  3092. return DropdownMenuItem<String>(
  3093. value: value,
  3094. child: Text(
  3095. value,
  3096. style: const TextStyle(fontSize: 15),
  3097. overflow: TextOverflow.ellipsis,
  3098. ).marginOnly(left: 15),
  3099. );
  3100. }).toList(),
  3101. )),
  3102. ).marginOnly(bottom: 5);
  3103. }
  3104. }
  3105. Color? disabledTextColor(BuildContext context, bool enabled) {
  3106. return enabled
  3107. ? null
  3108. : Theme.of(context).textTheme.titleLarge?.color?.withOpacity(0.6);
  3109. }
  3110. Widget loadPowered(BuildContext context) {
  3111. return MouseRegion(
  3112. cursor: SystemMouseCursors.click,
  3113. child: GestureDetector(
  3114. onTap: () {
  3115. launchUrl(Uri.parse('https://rustdesk.com'));
  3116. },
  3117. child: Opacity(
  3118. opacity: 0.5,
  3119. child: Text(
  3120. translate("powered_by_me"),
  3121. overflow: TextOverflow.clip,
  3122. style: Theme.of(context)
  3123. .textTheme
  3124. .bodySmall
  3125. ?.copyWith(fontSize: 9, decoration: TextDecoration.underline),
  3126. )),
  3127. ),
  3128. ).marginOnly(top: 6);
  3129. }
  3130. // max 300 x 60
  3131. Widget loadLogo() {
  3132. return FutureBuilder<ByteData>(
  3133. future: rootBundle.load('assets/logo.png'),
  3134. builder: (BuildContext context, AsyncSnapshot<ByteData> snapshot) {
  3135. if (snapshot.hasData) {
  3136. final image = Image.asset(
  3137. 'assets/logo.png',
  3138. fit: BoxFit.contain,
  3139. errorBuilder: (ctx, error, stackTrace) {
  3140. return Container();
  3141. },
  3142. );
  3143. return Container(
  3144. constraints: BoxConstraints(maxWidth: 300, maxHeight: 60),
  3145. child: image,
  3146. ).marginOnly(left: 12, right: 12, top: 12);
  3147. }
  3148. return const Offstage();
  3149. });
  3150. }
  3151. Widget loadIcon(double size) {
  3152. return Image.asset('assets/icon.png',
  3153. width: size,
  3154. height: size,
  3155. errorBuilder: (ctx, error, stackTrace) => SvgPicture.asset(
  3156. 'assets/icon.svg',
  3157. width: size,
  3158. height: size,
  3159. ));
  3160. }
  3161. var imcomingOnlyHomeSize = Size(280, 300);
  3162. Size getIncomingOnlyHomeSize() {
  3163. final magicWidth = isWindows ? 11.0 : 2.0;
  3164. final magicHeight = 10.0;
  3165. return imcomingOnlyHomeSize +
  3166. Offset(magicWidth, kDesktopRemoteTabBarHeight + magicHeight);
  3167. }
  3168. Size getIncomingOnlySettingsSize() {
  3169. return Size(768, 600);
  3170. }
  3171. bool isInHomePage() {
  3172. final controller = Get.find<DesktopTabController>();
  3173. return controller.state.value.selected == 0;
  3174. }
  3175. Widget _buildPresetPasswordWarning() {
  3176. if (bind.mainGetBuildinOption(key: kOptionRemovePresetPasswordWarning) !=
  3177. 'N') {
  3178. return SizedBox.shrink();
  3179. }
  3180. return Container(
  3181. color: Colors.yellow,
  3182. child: Column(
  3183. children: [
  3184. Align(
  3185. child: Text(
  3186. translate("Security Alert"),
  3187. style: TextStyle(
  3188. color: Colors.red,
  3189. fontSize:
  3190. 18, // https://github.com/rustdesk/rustdesk-server-pro/issues/261
  3191. fontWeight: FontWeight.bold,
  3192. ),
  3193. )).paddingOnly(bottom: 8),
  3194. Text(
  3195. translate("preset_password_warning"),
  3196. style: TextStyle(color: Colors.red),
  3197. )
  3198. ],
  3199. ).paddingAll(8),
  3200. ); // Show a warning message if the Future completed with true
  3201. }
  3202. Widget buildPresetPasswordWarningMobile() {
  3203. if (bind.isPresetPasswordMobileOnly()) {
  3204. return _buildPresetPasswordWarning();
  3205. } else {
  3206. return SizedBox.shrink();
  3207. }
  3208. }
  3209. Widget buildPresetPasswordWarning() {
  3210. return FutureBuilder<bool>(
  3211. future: bind.isPresetPassword(),
  3212. builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
  3213. if (snapshot.connectionState == ConnectionState.waiting) {
  3214. return CircularProgressIndicator(); // Show a loading spinner while waiting for the Future to complete
  3215. } else if (snapshot.hasError) {
  3216. return Text(
  3217. 'Error: ${snapshot.error}'); // Show an error message if the Future completed with an error
  3218. } else if (snapshot.hasData && snapshot.data == true) {
  3219. return _buildPresetPasswordWarning();
  3220. } else {
  3221. return SizedBox
  3222. .shrink(); // Show nothing if the Future completed with false or null
  3223. }
  3224. },
  3225. );
  3226. }
  3227. // https://github.com/leanflutter/window_manager/blob/87dd7a50b4cb47a375b9fc697f05e56eea0a2ab3/lib/src/widgets/virtual_window_frame.dart#L44
  3228. Widget buildVirtualWindowFrame(BuildContext context, Widget child) {
  3229. boxShadow() => isMainDesktopWindow
  3230. ? <BoxShadow>[
  3231. if (stateGlobal.fullscreen.isFalse || stateGlobal.isMaximized.isFalse)
  3232. BoxShadow(
  3233. color: Colors.black.withOpacity(0.1),
  3234. offset: Offset(
  3235. 0.0,
  3236. stateGlobal.isFocused.isTrue
  3237. ? kFrameBoxShadowOffsetFocused
  3238. : kFrameBoxShadowOffsetUnfocused),
  3239. blurRadius: kFrameBoxShadowBlurRadius,
  3240. ),
  3241. ]
  3242. : null;
  3243. return Obx(
  3244. () => Container(
  3245. decoration: BoxDecoration(
  3246. color: isMainDesktopWindow
  3247. ? Colors.transparent
  3248. : Theme.of(context).colorScheme.background,
  3249. border: Border.all(
  3250. color: Theme.of(context).dividerColor,
  3251. width: stateGlobal.windowBorderWidth.value,
  3252. ),
  3253. borderRadius: BorderRadius.circular(
  3254. (stateGlobal.fullscreen.isTrue || stateGlobal.isMaximized.isTrue)
  3255. ? 0
  3256. : kFrameBorderRadius,
  3257. ),
  3258. boxShadow: boxShadow(),
  3259. ),
  3260. child: ClipRRect(
  3261. borderRadius: BorderRadius.circular(
  3262. (stateGlobal.fullscreen.isTrue || stateGlobal.isMaximized.isTrue)
  3263. ? 0
  3264. : kFrameClipRRectBorderRadius,
  3265. ),
  3266. child: child,
  3267. ),
  3268. ),
  3269. );
  3270. }
  3271. get windowResizeEdgeSize =>
  3272. isLinux && !_linuxWindowResizable ? 0.0 : kWindowResizeEdgeSize;
  3273. // `windowManager.setResizable(false)` will reset the window size to the default size on Linux and then set unresizable.
  3274. // See _linuxWindowResizable for more details.
  3275. // So we use `setResizable()` instead of `windowManager.setResizable()`.
  3276. //
  3277. // We can only call `windowManager.setResizable(false)` if we need the default size on Linux.
  3278. setResizable(bool resizable) {
  3279. if (isLinux) {
  3280. _linuxWindowResizable = resizable;
  3281. stateGlobal.refreshResizeEdgeSize();
  3282. } else {
  3283. windowManager.setResizable(resizable);
  3284. }
  3285. }
  3286. isOptionFixed(String key) => bind.mainIsOptionFixed(key: key);
  3287. bool? _isCustomClient;
  3288. bool get isCustomClient {
  3289. _isCustomClient ??= bind.isCustomClient();
  3290. return _isCustomClient!;
  3291. }
  3292. get defaultOptionLang => isCustomClient ? 'default' : '';
  3293. get defaultOptionTheme => isCustomClient ? 'system' : '';
  3294. get defaultOptionYes => isCustomClient ? 'Y' : '';
  3295. get defaultOptionNo => isCustomClient ? 'N' : '';
  3296. get defaultOptionWhitelist => isCustomClient ? ',' : '';
  3297. get defaultOptionAccessMode => isCustomClient ? 'custom' : '';
  3298. get defaultOptionApproveMode => isCustomClient ? 'password-click' : '';
  3299. bool whitelistNotEmpty() {
  3300. // https://rustdesk.com/docs/en/self-host/client-configuration/advanced-settings/#whitelist
  3301. final v = bind.mainGetOptionSync(key: kOptionWhitelist);
  3302. return v != '' && v != ',';
  3303. }
  3304. // `setMovable()` is only supported on macOS.
  3305. //
  3306. // On macOS, the window can be dragged by the tab bar by default.
  3307. // We need to disable the movable feature to prevent the window from being dragged by the tabs in the tab bar.
  3308. //
  3309. // When we drag the blank tab bar (not the tab), the window will be dragged normally by adding the `onPanStart` handle.
  3310. //
  3311. // See the following code for more details:
  3312. // https://github.com/rustdesk/rustdesk/blob/ce1dac3b8613596b4d8ae981275f9335489eb935/flutter/lib/desktop/widgets/tabbar_widget.dart#L385
  3313. // https://github.com/rustdesk/rustdesk/blob/ce1dac3b8613596b4d8ae981275f9335489eb935/flutter/lib/desktop/widgets/tabbar_widget.dart#L399
  3314. //
  3315. // @platforms macos
  3316. disableWindowMovable(int? windowId) {
  3317. if (!isMacOS) {
  3318. return;
  3319. }
  3320. if (windowId == null) {
  3321. windowManager.setMovable(false);
  3322. } else {
  3323. WindowController.fromWindowId(windowId).setMovable(false);
  3324. }
  3325. }
  3326. Widget netWorkErrorWidget() {
  3327. return Center(
  3328. child: Column(
  3329. mainAxisAlignment: MainAxisAlignment.center,
  3330. crossAxisAlignment: CrossAxisAlignment.center,
  3331. children: [
  3332. Text(translate("network_error_tip")),
  3333. ElevatedButton(
  3334. onPressed: gFFI.userModel.refreshCurrentUser,
  3335. child: Text(translate("Retry")))
  3336. .marginSymmetric(vertical: 16),
  3337. SelectableText(gFFI.userModel.networkError.value,
  3338. style: TextStyle(fontSize: 11, color: Colors.red)),
  3339. ],
  3340. ));
  3341. }
  3342. List<ResizeEdge>? get windowManagerEnableResizeEdges => isWindows
  3343. ? [
  3344. ResizeEdge.topLeft,
  3345. ResizeEdge.top,
  3346. ResizeEdge.topRight,
  3347. ]
  3348. : null;
  3349. List<SubWindowResizeEdge>? get subWindowManagerEnableResizeEdges => isWindows
  3350. ? [
  3351. SubWindowResizeEdge.topLeft,
  3352. SubWindowResizeEdge.top,
  3353. SubWindowResizeEdge.topRight,
  3354. ]
  3355. : null;
  3356. void earlyAssert() {
  3357. assert('\1' == '1');
  3358. }