common.dart 112 KB

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