ModBase.vb 166 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468
  1. Imports System.Globalization
  2. Imports System.IO.Compression
  3. Imports System.Net.Sockets
  4. Imports System.Runtime.CompilerServices
  5. Imports System.Security.Cryptography
  6. Imports System.Security.Principal
  7. Imports System.Text.RegularExpressions
  8. Imports System.Threading.Tasks
  9. Imports System.Xaml
  10. Imports Newtonsoft.Json
  11. Public Module ModBase
  12. #Region "声明"
  13. '下列版本信息由更新器自动修改
  14. Public Const VersionBaseName As String = "2.12.4" '不含分支前缀的显示用版本名
  15. Public Const VersionStandardCode As String = "2.12.4." & VersionBranchCode '标准格式的四段式版本号
  16. Public Const CommitHash As String = "" 'Commit Hash,由 GitHub Workflow 自动替换
  17. #If BETA Then
  18. Public Const VersionCode As Integer = 383 'Release
  19. #Else
  20. Public Const VersionCode As Integer = 384 'Snapshot
  21. #End If
  22. '自动生成的版本信息
  23. Public Const VersionDisplayName As String = VersionBranchName & " " & VersionBaseName
  24. #If RELEASE Then
  25. Public Const VersionBranchName As String = "Snapshot"
  26. Public Const VersionBranchCode As String = "0"
  27. #ElseIf BETA Then
  28. Public Const VersionBranchName As String = "Release"
  29. Public Const VersionBranchCode As String = "50"
  30. #Else
  31. Public Const VersionBranchName As String = "Debug"
  32. Public Const VersionBranchCode As String = "100"
  33. #End If
  34. ''' <summary>
  35. ''' 主窗口句柄。
  36. ''' </summary>
  37. Public Handle As IntPtr
  38. ''' <summary>
  39. ''' 程序的启动路径,以“\”结尾。
  40. ''' </summary>
  41. Public Path As String = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
  42. ''' <summary>
  43. ''' 包含程序名的完整路径。
  44. ''' </summary>
  45. Public PathWithName As String = Path & AppDomain.CurrentDomain.SetupInformation.ApplicationName
  46. ''' <summary>
  47. ''' 程序内嵌图片文件夹路径,以“/”结尾。
  48. ''' </summary>
  49. Public PathImage As String = "pack://application:,,,/Plain Craft Launcher 2;component/Images/"
  50. ''' <summary>
  51. ''' 当前程序的语言。
  52. ''' </summary>
  53. Public Lang As String = "zh_CN"
  54. ''' <summary>
  55. ''' 程序的打开计时。
  56. ''' </summary>
  57. Public ApplicationStartTick As Long = GetTimeMs()
  58. ''' <summary>
  59. ''' 程序打开时的时间。
  60. ''' </summary>
  61. Public ApplicationOpenTime As Date = Date.Now
  62. ''' <summary>
  63. ''' 识别码。
  64. ''' </summary>
  65. Public Identify As String = SecretGetIdentify()
  66. ''' <summary>
  67. ''' 程序是否已结束。
  68. ''' </summary>
  69. Public IsProgramEnded As Boolean = False
  70. ''' <summary>
  71. ''' 是否为 32 位系统。
  72. ''' </summary>
  73. Public Is32BitSystem As Boolean = Not Environment.Is64BitOperatingSystem
  74. ''' <summary>
  75. ''' 是否使用 GBK 编码。
  76. ''' </summary>
  77. Public IsGBKEncoding As Boolean = Encoding.Default.CodePage = 936
  78. ''' <summary>
  79. ''' 系统盘盘符,以 \ 结尾。例如 “C:\”。
  80. ''' </summary>
  81. Public OsDrive As String = Environment.GetLogicalDrives().Where(Function(p) Directory.Exists(p)).First.Upper.First & ":\" '#3799
  82. ''' <summary>
  83. ''' 程序的缓存文件夹路径,以 \ 结尾。
  84. ''' </summary>
  85. Public PathTemp As String = If(Settings.Get("SystemSystemCache") = "", IO.Path.GetTempPath() & "PCL\", Settings.Get("SystemSystemCache")).ToString.Replace("/", "\").TrimEnd("\") & "\"
  86. ''' <summary>
  87. ''' AppData 中的 PCL 文件夹路径,以 \ 结尾。
  88. ''' </summary>
  89. Public PathAppdata As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\PCL\"
  90. #End Region
  91. #Region "矢量图标"
  92. Public Class Logo
  93. ''' <summary>
  94. ''' 图标按钮,心(空心),1.1x
  95. ''' </summary>
  96. Public Const IconButtonLikeLine As String = "M512 896a42.666667 42.666667 0 0 1-30.293333-12.373333l-331.52-331.946667a224.426667 224.426667 0 0 1 0-315.733333 223.573333 223.573333 0 0 1 315.733333 0L512 282.026667l46.08-46.08a223.573333 223.573333 0 0 1 315.733333 0 224.426667 224.426667 0 0 1 0 315.733333l-331.52 331.946667A42.666667 42.666667 0 0 1 512 896zM308.053333 256a136.533333 136.533333 0 0 0-97.28 40.106667 138.24 138.24 0 0 0 0 194.986666L512 792.746667l301.226667-301.653334a138.24 138.24 0 0 0 0-194.986666 141.653333 141.653333 0 0 0-194.56 0l-76.373334 76.8a42.666667 42.666667 0 0 1-60.586666 0L405.333333 296.106667A136.533333 136.533333 0 0 0 308.053333 256z"
  97. ''' <summary>
  98. ''' 图标按钮,心(实心),1.1x
  99. ''' </summary>
  100. Public Const IconButtonLikeFill As String = "M700.856 155.543c-74.769 0-144.295 72.696-190.046 127.26-45.737-54.576-115.247-127.26-190.056-127.26-134.79 0-244.443 105.78-244.443 235.799 0 77.57 39.278 131.988 70.845 175.713C238.908 694.053 469.62 852.094 479.39 858.757c9.41 6.414 20.424 9.629 31.401 9.629 11.006 0 21.998-3.215 31.398-9.63 9.782-6.662 240.514-164.703 332.238-291.701 31.587-43.724 70.874-98.143 70.874-175.713-0.001-130.02-109.656-235.8-244.445-235.8z m0 0"
  101. ''' <summary>
  102. ''' 图标按钮,垃圾桶,1.1x
  103. ''' </summary>
  104. Public Const IconButtonDelete As String = "M520.192 0C408.43 0 317.44 82.87 313.563 186.734H52.736c-29.038 0-52.663 21.943-52.663 49.079s23.625 49.152 52.663 49.152h58.075v550.473c0 103.35 75.118 187.757 167.717 187.757h472.43c92.599 0 167.716-83.894 167.716-187.757V285.477h52.59c29.038 0 52.59-21.943 52.663-49.08-0.073-27.135-23.625-49.151-52.663-49.151H726.235C723.237 83.017 631.955 0 520.192 0zM404.846 177.957c3.803-50.03 50.176-89.015 107.447-89.015 57.197 0 103.57 38.985 106.788 89.015H404.92zM284.379 933.669c-33.353 0-69.997-39.351-69.997-95.525v-549.01H833.39v549.522c0 56.247-36.645 95.525-69.998 95.525H284.379v-0.512z M357.23 800.695a48.274 48.274 0 0 0 47.616-49.006V471.7a48.274 48.274 0 0 0-47.543-49.08 48.274 48.274 0 0 0-47.69 49.006V751.69c0 27.282 20.846 49.006 47.617 49.006z m166.62 0a48.274 48.274 0 0 0 47.688-49.006V471.7a48.274 48.274 0 0 0-47.689-49.08 48.274 48.274 0 0 0-47.543 49.006V751.69c0 27.282 21.431 49.006 47.543 49.006z m142.92 0a48.274 48.274 0 0 0 47.543-49.006V471.7a48.274 48.274 0 0 0-47.543-49.08 48.274 48.274 0 0 0-47.616 49.006V751.69c0 27.282 20.773 49.006 47.543 49.006z"
  105. ''' <summary>
  106. ''' 图标按钮,禁止,1x
  107. ''' </summary>
  108. Public Const IconButtonStop As String = "M508 990.4c-261.6 0-474.4-212-474.4-474.4S246.4 41.6 508 41.6s474.4 212 474.4 474.4S769.6 990.4 508 990.4zM508 136.8c-209.6 0-379.2 169.6-379.2 379.2 0 209.6 169.6 379.2 379.2 379.2s379.2-169.6 379.2-379.2C887.2 306.4 717.6 136.8 508 136.8zM697.6 563.2 318.4 563.2c-26.4 0-47.2-21.6-47.2-47.2 0-26.4 21.6-47.2 47.2-47.2l379.2 0c26.4 0 47.2 21.6 47.2 47.2C744.8 542.4 724 563.2 697.6 563.2z"
  109. ''' <summary>
  110. ''' 图标按钮,勾选,1x
  111. ''' </summary>
  112. Public Const IconButtonCheck As String = "M512 0a512 512 0 1 0 512 512A512 512 0 0 0 512 0z m0 921.6a409.6 409.6 0 1 1 409.6-409.6 409.6 409.6 0 0 1-409.6 409.6z M716.8 339.968l-256 253.44L328.192 460.8A51.2 51.2 0 0 0 256 532.992l168.448 168.96a51.2 51.2 0 0 0 72.704 0l289.28-289.792A51.2 51.2 0 0 0 716.8 339.968z"
  113. ''' <summary>
  114. ''' 图标按钮,笔,1x
  115. ''' </summary>
  116. Public Const IconButtonEdit As String = "M732.64 64.32C688.576 21.216 613.696 21.216 569.6 64.32L120.128 499.52c-17.6 12.896-26.432 30.144-30.848 51.68L32 870.048c0 25.856 8.8 56 26.432 73.248 17.632 17.216 17.632 48.704 88.64 48.704h13.248l326.08-56c22.016-4.32 39.68-12.928 52.864-30.176l449.472-435.2c22.048-21.536 35.264-47.36 35.264-77.536 0-30.176-13.216-56-35.264-77.568l-256.096-251.2zM139.712 903.776l56-326.912 311.04-295.136 267.104 269.44-310.976 295.168-323.168 57.44zM844.576 467.84l-273.984-260.672 61.856-59.84c8.832-8.512 26.528-8.512 39.776 0l234.24 226.496c4.384 4.288 8.832 12.8 8.832 17.088s-4.416 8.544-8.864 12.8l-61.856 64.128z"
  117. ''' <summary>
  118. ''' 图标按钮,齿轮,1.1x
  119. ''' </summary>
  120. Public Const IconButtonSetup As String = "M651.946667 1001.813333c-22.186667 0-42.666667-10.24-61.44-27.306666-23.893333-23.893333-49.493333-35.84-75.093334-35.84-29.013333 0-56.32 11.946667-73.386666 30.72v3.413333c-17.066667 17.066667-42.666667 27.306667-66.56 27.306667h-6.826667c-6.826667 0-11.946667-1.706667-15.36-1.706667l-6.826667-1.706667c-64.853333-20.48-121.173333-54.613333-168.96-98.986666-29.013333-23.893333-37.546667-63.146667-25.6-95.573334 8.533333-23.893333 5.12-51.2-10.24-75.093333-15.36-27.306667-34.133333-40.96-59.733333-47.786667h-1.706667l-5.12-1.706666c-35.84-8.533333-61.44-34.133333-66.56-69.973334C1.706667 575.146667 0 537.6 0 512c0-32.426667 3.413333-63.146667 8.533333-93.866667v-6.826666l3.413334-8.533334c10.24-23.893333 23.893333-40.96 44.373333-51.2 5.12-3.413333 11.946667-6.826667 20.48-8.533333 27.306667-8.533333 51.2-25.6 63.146667-44.373333 13.653333-23.893333 17.066667-52.906667 10.24-81.92-11.946667-34.133333 0-71.68 30.72-93.866667 44.373333-37.546667 97.28-68.266667 158.72-93.866667l3.413333-1.706666c44.373333-13.653333 75.093333 3.413333 92.16 20.48 23.893333 23.893333 49.493333 35.84 75.093333 35.84 30.72 0 56.32-10.24 71.68-30.72l3.413334-3.413334c27.306667-27.306667 63.146667-35.84 93.866666-22.186666 63.146667 22.186667 117.76 54.613333 165.546667 97.28 29.013333 23.893333 37.546667 63.146667 25.6 95.573333-8.533333 23.893333-5.12 51.2 10.24 75.093333 15.36 27.306667 34.133333 40.96 59.733333 47.786667h1.706667l5.12 1.706667c35.84 8.533333 61.44 34.133333 66.56 71.68 6.826667 30.72 10.24 63.146667 11.946667 93.866666v3.413334c0 32.426667-3.413333 63.146667-8.533334 93.866666v6.826667l-3.413333 8.533333c-10.24 23.893333-23.893333 40.96-44.373333 51.2-5.12 3.413333-11.946667 6.826667-20.48 8.533334-27.306667 8.533333-51.2 25.6-63.146667 46.08-13.653333 23.893333-17.066667 52.906667-10.24 81.92 11.946667 35.84-1.706667 75.093333-30.72 95.573333-44.373333 35.84-95.573333 66.56-157.013333 92.16-15.36 3.413333-27.306667 3.413333-35.84 3.413333z m3.413333-83.626666z m1.706667 0zM517.12 853.333333c47.786667 0 93.866667 20.48 134.826667 59.733334 1.706667 1.706667 3.413333 1.706667 3.413333 3.413333 52.906667-22.186667 97.28-49.493333 136.533333-80.213333l1.706667-1.706667v-3.413333c-13.653333-52.906667-8.533333-104.106667 17.066667-148.48 23.893333-39.253333 64.853333-69.973333 114.346666-85.333334 1.706667 0 3.413333-1.706667 6.826667-6.826666 5.12-25.6 8.533333-51.2 8.533333-78.506667-1.706667-29.013333-3.413333-56.32-10.24-81.92v-5.12h-1.706666c-51.2-11.946667-90.453333-39.253333-119.466667-87.04-27.306667-44.373333-34.133333-100.693333-17.066667-148.48l-1.706666-1.706667h-3.413334c-39.253333-35.84-85.333333-63.146667-136.533333-80.213333H648.533333s-1.706667 1.706667-3.413333 1.706667c-32.426667 39.253333-80.213333 59.733333-136.533333 59.733333-47.786667 0-93.866667-20.48-134.826667-59.733333l-1.706667-1.706667h-1.706666c-54.613333 22.186667-98.986667 49.493333-136.533334 80.213333l-1.706666 1.706667v3.413333c13.653333 52.906667 8.533333 104.106667-17.066667 148.48-23.893333 39.253333-64.853333 69.973333-114.346667 85.333334-1.706667 0-3.413333 1.706667-6.826666 6.826666-6.826667 25.6-8.533333 51.2-8.533334 78.506667 0 30.72 3.413333 58.026667 6.826667 76.8l1.706667 5.12h1.706666c51.2 11.946667 90.453333 39.253333 119.466667 87.04 27.306667 44.373333 34.133333 100.693333 17.066667 148.48l1.706666 1.706667 1.706667 1.706666c37.546667 35.84 83.626667 63.146667 134.826667 80.213334 1.706667 0 3.413333 0 3.413333 1.706666h1.706667s1.706667 0 5.12-1.706666c34.133333-37.546667 81.92-59.733333 136.533333-59.733334z m-6.826667-146.773333c-110.933333 0-199.68-85.333333-199.68-196.266667 0-109.226667 87.04-196.266667 199.68-196.266666s199.68 85.333333 199.68 196.266666c-1.706667 109.226667-88.746667 196.266667-199.68 196.266667z m0-307.2c-63.146667 0-114.346667 49.493333-114.346666 110.933333 0 63.146667 49.493333 110.933333 114.346666 110.933334 30.72 0 59.733333-11.946667 80.213334-32.426667 20.48-20.48 32.426667-49.493333 32.426666-78.506667 0-63.146667-49.493333-110.933333-112.64-110.933333z"
  121. ''' <summary>
  122. ''' 图标按钮,重置,0.9x
  123. ''' </summary>
  124. Public Const IconButtonReset As String = "M667.6817627 313.65283203l-45.28564454 55.76660156L858.06933594 391.27124023 787.61950684 165.93066406l-56.01379395 69.01611328A354.47387695 354.47387695 0 0 0 520.89892578 165.93066406C324.87536621 165.93066406 165.93066406 324.43041992 165.93066406 519.91015625c0 195.52917481 158.94470215 353.97949219 354.96826172 353.97949219a355.06713867 355.06713867 0 0 0 331.73217774-227.66418458 50.52612305 50.52612305 0 0 0-29.21813966-65.25878905 50.77331543 50.77331543 0 0 0-65.50598144 29.16870117A253.61938477 253.61938477 0 0 1 520.94836426 772.78796387c-140.05920411 0-253.61938477-113.21411133-253.61938477-252.87780762 0-139.61425781 113.56018067-252.82836914 253.61938477-252.82836914 53.59130859 0 104.46350098 16.61132813 146.73339843 46.57104492"
  125. ''' <summary>
  126. ''' 图标按钮,刷新,0.85x
  127. ''' </summary>
  128. Public Const IconButtonRefresh As String = "M875.52 148.48C783.36 56.32 655.36 0 512 0 291.84 0 107.52 138.24 30.72 332.8l122.88 46.08C204.8 230.4 348.16 128 512 128c107.52 0 199.68 40.96 271.36 112.64L640 384h384V0L875.52 148.48zM512 896c-107.52 0-199.68-40.96-271.36-112.64L384 640H0v384l148.48-148.48C240.64 967.68 368.64 1024 512 1024c220.16 0 404.48-138.24 481.28-332.8L870.4 645.12C819.2 793.6 675.84 896 512 896z"
  129. ''' <summary>
  130. ''' 图标按钮,软盘,1x
  131. ''' </summary>
  132. Public Const IconButtonSave As String = "M819.392 0L1024 202.752v652.16a168.96 168.96 0 0 1-168.832 168.768h-104.192a47.296 47.296 0 0 1-10.752 0H283.776a47.232 47.232 0 0 1-10.752 0H168.832A168.96 168.96 0 0 1 0 854.912V168.768A168.96 168.96 0 0 1 168.832 0h650.56z m110.208 854.912V242.112l-149.12-147.776H168.896c-41.088 0-74.432 33.408-74.432 74.432v686.144c0 41.024 33.344 74.432 74.432 74.432h62.4v-190.528c0-33.408 27.136-60.544 60.544-60.544h440.448c33.408 0 60.544 27.136 60.544 60.544v190.528h62.4c41.088 0 74.432-33.408 74.432-74.432z m-604.032 74.432h372.864v-156.736H325.568v156.736z m403.52-596.48a47.168 47.168 0 1 1 0 94.336H287.872a47.168 47.168 0 1 1 0-94.336h441.216z m0-153.728a47.168 47.168 0 1 1 0 94.4H287.872a47.168 47.168 0 1 1 0-94.4h441.216z"
  133. ''' <summary>
  134. ''' 图标按钮,信息,1.05x
  135. ''' </summary>
  136. Public Const IconButtonInfo As String = "M512 917.333333c223.861333 0 405.333333-181.472 405.333333-405.333333S735.861333 106.666667 512 106.666667 106.666667 288.138667 106.666667 512s181.472 405.333333 405.333333 405.333333z m0 106.666667C229.226667 1024 0 794.773333 0 512S229.226667 0 512 0s512 229.226667 512 512-229.226667 512-512 512z m-32-597.333333h64a21.333333 21.333333 0 0 1 21.333333 21.333333v320a21.333333 21.333333 0 0 1-21.333333 21.333333h-64a21.333333 21.333333 0 0 1-21.333333-21.333333V448a21.333333 21.333333 0 0 1 21.333333-21.333333z m0-192h64a21.333333 21.333333 0 0 1 21.333333 21.333333v64a21.333333 21.333333 0 0 1-21.333333 21.333333h-64a21.333333 21.333333 0 0 1-21.333333-21.333333v-64a21.333333 21.333333 0 0 1 21.333333-21.333333z"
  137. ''' <summary>
  138. ''' 图标按钮,列表,1x
  139. ''' </summary>
  140. Public Const IconButtonList As String = "M384 128h640v128H384zM160 192m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0ZM384 448h640v128H384zM160 512m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0ZM384 768h640v128H384zM160 832m-96 0a96 96 0 1 0 192 0 96 96 0 1 0-192 0Z"
  141. ''' <summary>
  142. ''' 图标按钮,文件夹,1.15x
  143. ''' </summary>
  144. Public Const IconButtonOpen As String = "M889.018182 418.909091H884.363636V316.509091a93.090909 93.090909 0 0 0-99.607272-89.832727h-302.545455l-93.090909-76.334546A46.545455 46.545455 0 0 0 358.865455 139.636364H146.152727A93.090909 93.090909 0 0 0 46.545455 229.469091V837.818182a46.545455 46.545455 0 0 0 46.545454 46.545454 46.545455 46.545455 0 0 0 16.756364-3.258181 109.381818 109.381818 0 0 0 25.134545 3.258181h586.472727a85.178182 85.178182 0 0 0 87.04-63.301818l163.374546-302.545454a46.545455 46.545455 0 0 0 5.585454-21.876364A82.385455 82.385455 0 0 0 889.018182 418.909091z m-744.727273-186.181818h198.283636l93.09091 76.334545a46.545455 46.545455 0 0 0 29.323636 10.705455h319.301818a12.101818 12.101818 0 0 1 6.516364 0V418.909091H302.545455a85.178182 85.178182 0 0 0-87.04 63.301818L139.636364 622.778182V232.727273a19.549091 19.549091 0 0 1 6.516363 0z m578.094546 552.029091a27.461818 27.461818 0 0 0-2.792728 6.516363H154.530909l147.083636-272.290909a27.461818 27.461818 0 0 0 2.792728-6.981818h565.061818z"
  145. ''' <summary>
  146. ''' 图标按钮,名片,1.1x
  147. ''' </summary>
  148. Public Const IconButtonCard As String = "M834.5 684.1c-31.2-70.4-98.9-120.9-179.1-127.3 63.5-8.5 112.6-63 112.6-128.8 0-71.8-58.2-130-130-130s-130 58.2-130 130c0 65.9 49 120.3 112.6 128.8-80.2 6.4-148 57-179.1 127.3-8.7 19.7 6 42 27.6 42 12.1 0 22.7-7.5 27.7-18.5 24.3-53.9 78.5-91.5 141.3-91.5s117 37.6 141.3 91.5c5 11.1 15.6 18.5 27.7 18.5 21.4 0 36.1-22.3 27.4-42zM567.9 427.9c0-38.6 31.4-70 70-70s70 31.4 70 70-31.4 70-70 70-70-31.4-70-70zM460.3 347.9H216.9c-16.6 0-30 13.4-30 30s13.4 30 30 30h243.3c16.6 0 30-13.4 30-30 0.1-16.5-13.4-30-29.9-30zM367.4 459.6H216.9c-16.6 0-30 13.4-30 30s13.4 30 30 30h150.4c16.6 0 30-13.4 30-30 0.1-16.6-13.4-30-29.9-30zM297.4 571.2H217c-16.6 0-30 13.4-30 30s13.4 30 30 30h80.4c16.6 0 30-13.4 30-30 0-16.5-13.5-30-30-30zM900 236v552H124V236h776m0-60H124c-33.1 0-60 26.9-60 60v552c0 33.1 26.9 60 60 60h776c33.1 0 60-26.9 60-60V236c0-33.1-26.9-60-60-60z"
  149. ''' <summary>
  150. ''' 图标按钮,×,0.85x
  151. ''' </summary>
  152. Public Const IconButtonCross As String = "F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z"
  153. ''' <summary>
  154. ''' 图标按钮,Mojang,1.1x
  155. ''' </summary>
  156. Public Const IconButtonMojang As String = "M9.183,18.967c-0.109-2.239,1.336-5.119,3.92-4.96c3.657-0.027,7.319-0.044,10.977,0.005 c3.712,0.214,6.596,2.759,9.652,4.533c0.181-1.697-0.197-3.717,1.237-4.982c1.899,2.091,3.143,4.894,5.677,6.334 c1.577,0.805,2.973-0.668,4.221-1.44c1.55,2.305,2.108,5.075,2.622,7.752c0.657,3.438,0.947,6.925,1.111,10.413 c-1.734-0.733-3.355-1.708-4.971-2.671c-1.396-4.933-5.349-8.656-9.723-11.059c-3.46-1.817-7.752-2.185-11.338-0.52 c-3.761,1.593-6.285,5.666-5.891,9.75c0.121,4.577,3.17,8.765,7.391,10.456c7.746,3.285,16.407,2.234,24.521,1.243 c0.454,2.315-1.511,4.527-3.695,4.889c-10.577,0.038-21.148-0.011-31.725,0.022c-2.217,0.279-4.079-1.879-3.964-4.008 C9.167,36.141,9.216,27.556,9.183,18.967z M40.114,8.09c0.294-0.801,0.872-1.417,1.542-1.924c1.379,2.589,2.742,5.482,2.311,8.491 c-0.332,2.54-4.42,2.507-5.052,0.163C38.349,12.527,39.209,10.178,40.114,8.09z M0,53 l0.1,0 z"
  157. ''' <summary>
  158. ''' 图标按钮,用户,0.95x
  159. ''' </summary>
  160. Public Const IconButtonUser As String = "M660.338 528.065c63.61-46.825 105.131-121.964 105.131-206.83 0-141.7-115.29-256.987-256.997-256.987-141.706 0-256.998 115.288-256.998 256.987 0 85.901 42.52 161.887 107.456 208.562-152.1 59.92-260.185 207.961-260.185 381.077 0 21.276 17.253 38.53 38.53 38.53 21.278 0 38.53-17.254 38.53-38.53 0-183.426 149.232-332.671 332.667-332.671 1.589 0 3.113-0.207 4.694-0.244 0.8 0.056 1.553 0.244 2.362 0.244 183.434 0 332.664 149.245 332.664 332.671 0 21.276 17.255 38.53 38.533 38.53 21.277 0 38.53-17.254 38.53-38.53 0-174.885-110.354-324.13-264.917-382.809z m-331.803-206.83c0-99.22 80.72-179.927 179.935-179.927s179.937 80.708 179.937 179.927c0 99.203-80.721 179.91-179.937 179.91s-179.935-80.708-179.935-179.91z"
  161. ''' <summary>
  162. ''' 图标按钮,盾牌,1x
  163. ''' </summary>
  164. Public Const IconButtonShield As String = "M511.488256 95.184408c35.310345 22.516742 95.184408 55.78011 167.34033 84.437781 75.738131 29.681159 148.405797 40.93953 191.392304 45.033483v353.615193c0 73.691154-50.662669 164.781609-136.123938 244.101949C649.65917 901.181409 558.568716 942.12094 512 942.12094c-46.568716 0-137.65917-40.93953-222.096952-119.748126C204.441779 742.54073 153.77911 651.450275 153.77911 577.247376v-353.103448c42.474763-4.093953 116.165917-15.352324 191.904048-45.545227 75.226387-30.192904 133.565217-63.456272 165.805098-83.414293M512 0c-4.093953 0-8.187906 1.535232-11.258371 3.582209l-14.84058 10.234882c-1.023488 0.511744-67.550225 47.592204-170.410794 88.531735-100.813593 39.916042-198.556722 41.963018-199.58021 41.963018l-25.075462 0.511744c-10.746627 0.511744-18.934533 8.187906-18.934533 18.422789v414.000999c0 216.97951 286.064968 446.24088 440.09995 446.24088s440.09995-229.261369 440.09995-445.729136V163.758121c0-10.234883-8.69965-18.422789-18.934533-18.422789l-24.563718-0.511744c-1.023488 0-98.766617-2.046977-199.58021-41.963018-103.372314-40.93953-170.410795-88.01999-170.922538-88.531734L523.258371 3.582209c-3.070465-2.558721-7.164418-3.582209-11.258371-3.582209z M743.308346 410.930535l-260.477761 260.477761c-15.864068 15.864068-41.963018 15.864068-57.827087 0l-144.823588-144.823588c-15.864068-15.864068-15.864068-41.963018 0-57.827087 8.187906-8.187906 18.422789-11.770115 29.169415-11.770115 10.234883 0 20.981509 4.093953 29.169416 11.770115l115.654173 115.654173L685.993003 352.591704c15.864068-15.864068 41.963018-15.864068 57.827087 0 15.352324 16.375812 15.352324 42.474763-0.511744 58.338831z"
  165. ''' <summary>
  166. ''' 图标按钮,离线,0.85x
  167. ''' </summary>
  168. Public Const IconButtonOffline As String = "M533.293176 788.841412a60.235294 60.235294 0 1 1 85.202824 85.202823l-42.616471 42.586353c-129.355294 129.385412-339.124706 129.385412-468.510117 0-129.385412-129.385412-129.385412-339.124706 0-468.510117l42.586353-42.616471a60.235294 60.235294 0 1 1 85.202823 85.202824l-42.61647 42.586352a210.823529 210.823529 0 1 0 298.164706 298.164706l42.586352-42.61647z m255.548236-255.548236l42.61647-42.586352a210.823529 210.823529 0 1 0-298.164706-298.164706l-42.586352 42.61647a60.235294 60.235294 0 1 1-85.202824-85.202823l42.616471-42.586353c129.355294-129.385412 339.124706-129.385412 468.510117 0 129.385412 129.385412 129.385412 339.124706 0 468.510117l-42.586353 42.616471a60.235294 60.235294 0 1 1-85.202823-85.202824zM192.542118 192.542118a60.235294 60.235294 0 0 1 85.202823 0l553.712941 553.712941a60.235294 60.235294 0 0 1-85.202823 85.202823L192.542118 277.744941a60.235294 60.235294 0 0 1 0-85.202823z"
  169. ''' <summary>
  170. ''' 图标,服务端,1x
  171. ''' </summary>
  172. Public Const IconButtonServer As String = "M224 160a64 64 0 0 0-64 64v576a64 64 0 0 0 64 64h576a64 64 0 0 0 64-64V224a64 64 0 0 0-64-64H224z m0 384h576v256H224v-256z m192 96v64h320v-64H416z m-128 0v64h64v-64H288zM224 224h576v256H224V224z m192 96v64h320v-64H416z m-128 0v64h64v-64H288z"
  173. ''' <summary>
  174. ''' 图标,音符,1x
  175. ''' </summary>
  176. Public Const IconMusic As String = "M348.293565 716.53287V254.797913c0-41.672348 28.004174-78.358261 68.919652-90.37913L815.994435 40.826435c62.775652-18.610087 125.907478 26.579478 125.907478 89.933913v539.158261c8.013913 42.25113-8.94887 89.177043-47.014956 127.109565a232.848696 232.848696 0 0 1-170.785392 65.758609c-61.885217-2.938435-111.081739-33.435826-129.113043-80.050087-18.031304-46.614261-2.137043-102.177391 41.672348-145.853218a232.848696 232.848696 0 0 1 170.785391-65.80313c21.014261 1.024 40.514783 5.164522 57.878261 12.065391V233.338435c0-12.109913-10.551652-20.034783-20.569044-20.034783a24.620522 24.620522 0 0 0-5.787826 0.934957L439.785739 338.18713a19.545043 19.545043 0 0 0-14.825739 19.144348v438.984348H423.846957c11.53113 43.987478-5.164522 94.208-45.412174 134.322087a232.848696 232.848696 0 0 1-170.785392 65.758609c-61.885217-2.938435-111.081739-33.435826-129.113043-80.050087-18.031304-46.614261-2.137043-102.177391 41.672348-145.853218a232.848696 232.848696 0 0 1 170.785391-65.80313c20.791652 1.024 40.069565 5.075478 57.299478 11.842783z"
  177. ''' <summary>
  178. ''' 图标,播放,0.8x
  179. ''' </summary>
  180. Public Const IconPlay As String = "M803.904 463.936a55.168 55.168 0 0 1 0 96.128l-463.616 264.448C302.848 845.888 256 819.136 256 776.448V247.616c0-42.752 46.848-69.44 84.288-48.064l463.616 264.384z"
  181. End Class
  182. #End Region
  183. #Region "自定义类"
  184. ''' <summary>
  185. ''' 支持小数与常见类型隐式转换的颜色。
  186. ''' </summary>
  187. Public Class MyColor
  188. Public A As Double = 255
  189. Public R As Double = 0
  190. Public G As Double = 0
  191. Public B As Double = 0
  192. '类型转换
  193. Public Shared Widening Operator CType(str As String) As MyColor
  194. Return New MyColor(str)
  195. End Operator
  196. Public Shared Widening Operator CType(col As Color) As MyColor
  197. Return New MyColor(col)
  198. End Operator
  199. Public Shared Widening Operator CType(conv As MyColor) As Color
  200. Return Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  201. End Operator
  202. Public Shared Widening Operator CType(conv As MyColor) As System.Drawing.Color
  203. Return System.Drawing.Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  204. End Operator
  205. Public Shared Widening Operator CType(bru As SolidColorBrush) As MyColor
  206. Return New MyColor(bru.Color)
  207. End Operator
  208. Public Shared Widening Operator CType(conv As MyColor) As SolidColorBrush
  209. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  210. End Operator
  211. Public Shared Widening Operator CType(bru As Brush) As MyColor
  212. Return New MyColor(bru)
  213. End Operator
  214. Public Shared Widening Operator CType(conv As MyColor) As Brush
  215. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  216. End Operator
  217. '颜色运算
  218. Public Shared Operator +(a As MyColor, b As MyColor) As MyColor
  219. Return New MyColor With {.A = a.A + b.A, .B = a.B + b.B, .G = a.G + b.G, .R = a.R + b.R}
  220. End Operator
  221. Public Shared Operator -(a As MyColor, b As MyColor) As MyColor
  222. Return New MyColor With {.A = a.A - b.A, .B = a.B - b.B, .G = a.G - b.G, .R = a.R - b.R}
  223. End Operator
  224. Public Shared Operator *(a As MyColor, b As Double) As MyColor
  225. Return New MyColor With {.A = a.A * b, .B = a.B * b, .G = a.G * b, .R = a.R * b}
  226. End Operator
  227. Public Shared Operator /(a As MyColor, b As Double) As MyColor
  228. Return New MyColor With {.A = a.A / b, .B = a.B / b, .G = a.G / b, .R = a.R / b}
  229. End Operator
  230. Public Shared Operator =(a As MyColor, b As MyColor) As Boolean
  231. If IsNothing(a) AndAlso IsNothing(b) Then Return True
  232. If IsNothing(a) OrElse IsNothing(b) Then Return False
  233. Return a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B
  234. End Operator
  235. Public Shared Operator <>(a As MyColor, b As MyColor) As Boolean
  236. If IsNothing(a) AndAlso IsNothing(b) Then Return False
  237. If IsNothing(a) OrElse IsNothing(b) Then Return True
  238. Return Not (a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B)
  239. End Operator
  240. '构造函数
  241. Public Sub New()
  242. End Sub
  243. Public Sub New(col As Color)
  244. Me.A = col.A
  245. Me.R = col.R
  246. Me.G = col.G
  247. Me.B = col.B
  248. End Sub
  249. Public Sub New(HexString As String)
  250. Dim StringColor As Media.Color = ColorConverter.ConvertFromString(HexString)
  251. A = StringColor.A
  252. R = StringColor.R
  253. G = StringColor.G
  254. B = StringColor.B
  255. End Sub
  256. Public Sub New(newA As Double, col As MyColor)
  257. Me.A = newA
  258. Me.R = col.R
  259. Me.G = col.G
  260. Me.B = col.B
  261. End Sub
  262. Public Sub New(newR As Double, newG As Double, newB As Double)
  263. Me.A = 255
  264. Me.R = newR
  265. Me.G = newG
  266. Me.B = newB
  267. End Sub
  268. Public Sub New(newA As Double, newR As Double, newG As Double, newB As Double)
  269. Me.A = newA
  270. Me.R = newR
  271. Me.G = newG
  272. Me.B = newB
  273. End Sub
  274. Public Sub New(brush As Brush)
  275. Dim Color As Color = CType(brush, SolidColorBrush).Color
  276. A = Color.A
  277. R = Color.R
  278. G = Color.G
  279. B = Color.B
  280. End Sub
  281. Public Sub New(brush As SolidColorBrush)
  282. Dim Color As Color = brush.Color
  283. A = Color.A
  284. R = Color.R
  285. G = Color.G
  286. B = Color.B
  287. End Sub
  288. Public Sub New(obj As Object)
  289. If obj Is Nothing Then
  290. A = 255 : R = 255 : G = 255 : B = 255
  291. Else
  292. If TypeOf obj Is SolidColorBrush Then
  293. '避免反复获取 Color 对象造成性能下降
  294. Dim Color As Color = CType(obj, SolidColorBrush).Color
  295. A = Color.A
  296. R = Color.R
  297. G = Color.G
  298. B = Color.B
  299. Else
  300. A = obj.A
  301. R = obj.R
  302. G = obj.G
  303. B = obj.B
  304. End If
  305. End If
  306. End Sub
  307. 'HSL
  308. Public Function Hue(v1 As Double, v2 As Double, vH As Double) As Double
  309. If vH < 0 Then vH += 1
  310. If vH > 1 Then vH -= 1
  311. If vH < 0.16667 Then Return v1 + (v2 - v1) * 6 * vH
  312. If vH < 0.5 Then Return v2
  313. If vH < 0.66667 Then Return v1 + (v2 - v1) * (4 - vH * 6)
  314. Return v1
  315. End Function
  316. Public Function FromHSL(sH As Double, sS As Double, sL As Double) As MyColor
  317. If sS = 0 Then
  318. R = sL * 2.55
  319. G = R
  320. B = R
  321. Else
  322. Dim H = sH / 360
  323. Dim S = sS / 100
  324. Dim L = sL / 100
  325. S = If(L < 0.5, S * L + L, S * (1.0 - L) + L)
  326. L = 2 * L - S
  327. R = 255 * Hue(L, S, H + 1 / 3)
  328. G = 255 * Hue(L, S, H)
  329. B = 255 * Hue(L, S, H - 1 / 3)
  330. End If
  331. A = 255
  332. Return Me
  333. End Function
  334. Public Function FromHSL2(sH As Double, sS As Double, sL As Double) As MyColor
  335. If sS = 0 Then
  336. R = sL * 2.55 : G = R : B = R
  337. Else
  338. '初始化
  339. sH = (sH + 3600000) Mod 360
  340. Dim cent As Double() = {
  341. +0.1, -0.06, -0.3, '0, 30, 60
  342. -0.19, -0.15, -0.24, '90, 120, 150
  343. -0.32, -0.09, +0.18, '180, 210, 240
  344. +0.05, -0.12, -0.02, '270, 300, 330
  345. +0.1, -0.06} '最后两位与前两位一致,加是变亮,减是变暗
  346. '计算色调对应的亮度片区
  347. Dim center As Double = sH / 30.0
  348. Dim intCenter As Integer = Math.Floor(center) '亮度片区编号
  349. center = 50 - (
  350. (1 - center + intCenter) * cent(intCenter) + (center - intCenter) * cent(intCenter + 1)
  351. ) * sS
  352. 'center = 50 + (cent(intCenter) + (center - intCenter) * (cent(intCenter + 1) - cent(intCenter))) * sS
  353. sL = If(sL < center, sL / center, 1 + (sL - center) / (100 - center)) * 50
  354. FromHSL(sH, sS, sL)
  355. End If
  356. A = 255
  357. Return Me
  358. End Function
  359. Public Overrides Function ToString() As String
  360. Return "(" & A & "," & R & "," & G & "," & B & ")"
  361. End Function
  362. Public Overrides Function Equals(obj As Object) As Boolean
  363. Return Me = obj
  364. End Function
  365. End Class
  366. ''' <summary>
  367. ''' 支持负数与浮点数的矩形。
  368. ''' </summary>
  369. Public Class MyRect
  370. '属性
  371. Public Property Width As Double = 0
  372. Public Property Height As Double = 0
  373. Public Property Left As Double = 0
  374. Public Property Top As Double = 0
  375. '构造函数
  376. Public Sub New()
  377. End Sub
  378. Public Sub New(left As Double, top As Double, width As Double, height As Double)
  379. Me.Left = left
  380. Me.Top = top
  381. Me.Width = width
  382. Me.Height = height
  383. End Sub
  384. End Class
  385. ''' <summary>
  386. ''' 模块加载状态枚举。
  387. ''' </summary>
  388. Public Enum LoadState
  389. Waiting
  390. Loading
  391. Finished
  392. Failed
  393. Interrupted
  394. End Enum
  395. ''' <summary>
  396. ''' 执行返回值。
  397. ''' </summary>
  398. Public Enum ProcessReturnValues
  399. ''' <summary>
  400. ''' 执行成功。
  401. ''' </summary>
  402. Success = 0
  403. ''' <summary>
  404. ''' 执行失败。
  405. ''' </summary>
  406. Fail = 1
  407. ''' <summary>
  408. ''' 执行时出现未经处理的异常。
  409. ''' </summary>
  410. Exception = 2
  411. ''' <summary>
  412. ''' 执行超时。
  413. ''' </summary>
  414. Timeout = 3
  415. ''' <summary>
  416. ''' 取消执行。可能是由于不满足执行的前置条件。
  417. ''' </summary>
  418. Cancel = 4
  419. ''' <summary>
  420. ''' 任务成功完成。
  421. ''' </summary>
  422. TaskDone = 5
  423. End Enum
  424. ''' <summary>
  425. ''' 可以使用 Equals 和等号的 List。
  426. ''' </summary>
  427. Public Class EqualableList(Of T)
  428. Inherits List(Of T)
  429. Public Overrides Function Equals(obj As Object) As Boolean
  430. If TryCast(obj, List(Of T)) Is Nothing Then
  431. '类型不同
  432. Return False
  433. Else
  434. '类型相同
  435. Dim objList As List(Of T) = obj
  436. If objList.Count <> Count Then Return False
  437. For i = 0 To objList.Count - 1
  438. If Not objList(i).Equals(Me(i)) Then Return False
  439. Next
  440. Return True
  441. End If
  442. End Function
  443. Public Shared Operator =(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  444. Return EqualityComparer(Of EqualableList(Of T)).Default.Equals(left, right)
  445. End Operator
  446. Public Shared Operator <>(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  447. Return Not left = right
  448. End Operator
  449. End Class
  450. #End Region
  451. #Region "数学"
  452. ''' <summary>
  453. ''' 2~65 进制的转换。
  454. ''' </summary>
  455. Public Function RadixConvert(Input As String, FromRadix As Integer, ToRadix As Integer) As String
  456. Const Digits As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+="
  457. '零与负数的处理
  458. If String.IsNullOrEmpty(Input) Then Return "0"
  459. Dim IsNegative As Boolean = Input.StartsWithF("-")
  460. If IsNegative Then Input = Input.TrimStart("-")
  461. '转换为十进制
  462. Dim RealNum As Long = 0, Scale As Long = 1
  463. For Each Digit In Input.Reverse.Select(Function(l) Digits.IndexOfF(l))
  464. RealNum += Digit * Scale
  465. Scale *= FromRadix
  466. Next
  467. If RealNum = 0 Then Return "0"
  468. '转换为指定进制
  469. Dim Result = ""
  470. While RealNum > 0
  471. Dim NewNum As Integer = RealNum Mod ToRadix
  472. RealNum = (RealNum - NewNum) / ToRadix
  473. Result = Digits(NewNum) & Result
  474. End While
  475. '负数的结束处理与返回
  476. Return If(IsNegative, "-", "") & Result
  477. End Function
  478. ''' <summary>
  479. ''' 计算二阶贝塞尔曲线。
  480. ''' </summary>
  481. Public Function MathBezier(x As Double, x1 As Double, y1 As Double, x2 As Double, y2 As Double, Optional acc As Double = 0.01) As Double
  482. If x <= 0 OrElse Double.IsNaN(x) Then Return 0
  483. If x >= 1 Then Return 1
  484. Dim a, b
  485. a = x
  486. Do
  487. b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1)
  488. a += (x - b) * 0.5
  489. Loop Until Math.Abs(b - x) < acc '精度
  490. Return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1)
  491. End Function
  492. ''' <summary>
  493. ''' 将一个数字限制为 0~255 的 Byte 值。
  494. ''' </summary>
  495. Public Function MathByte(d As Double) As Byte
  496. If d < 0 Then d = 0
  497. If d > 255 Then d = 255
  498. Return Math.Round(d)
  499. End Function
  500. ''' <summary>
  501. ''' 提供 MyColor 类型支持的 Math.Round。
  502. ''' </summary>
  503. Public Function MathRound(col As MyColor, Optional w As Integer = 0) As MyColor
  504. Return New MyColor With {.A = Math.Round(col.A, w), .R = Math.Round(col.R, w), .G = Math.Round(col.G, w), .B = Math.Round(col.B, w)}
  505. End Function
  506. ''' <summary>
  507. ''' 获取两数间的百分比。小数点精确到 6 位。
  508. ''' </summary>
  509. ''' <returns></returns>
  510. Public Function MathPercent(ValueA As Double, ValueB As Double, Percent As Double) As Double
  511. Return Math.Round(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决 Double 计算错误
  512. End Function
  513. ''' <summary>
  514. ''' 获取两颜色间的百分比,根据 RGB 计算。小数点精确到 6 位。
  515. ''' </summary>
  516. Public Function MathPercent(ValueA As MyColor, ValueB As MyColor, Percent As Double) As MyColor
  517. Return MathRound(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决Double计算错误
  518. End Function
  519. ''' <summary>
  520. ''' 将数值限定在某个范围内。
  521. ''' </summary>
  522. Public Function MathClamp(value As Double, min As Double, max As Double) As Double
  523. Return Math.Max(min, Math.Min(max, value))
  524. End Function
  525. ''' <summary>
  526. ''' 符号函数。
  527. ''' </summary>
  528. Public Function MathSgn(Value As Double) As Integer
  529. If Value = 0 Then
  530. Return 0
  531. ElseIf Value > 0 Then
  532. Return 1
  533. Else
  534. Return -1
  535. End If
  536. End Function
  537. #End Region
  538. #Region "文件"
  539. '=============================
  540. ' 注册表
  541. '=============================
  542. ''' <summary>
  543. ''' 读取注册表键。如果失败则返回默认值。
  544. ''' </summary>
  545. Public Function ReadReg(Key As String, Optional DefaultValue As String = "") As String
  546. Try
  547. Return If(My.Computer.Registry.CurrentUser.OpenSubKey("Software\" & RegFolder, False)?.GetValue(Key), DefaultValue)
  548. Catch ex As Exception
  549. Log(ex, "读取注册表出错:" & Key, LogLevel.Hint)
  550. Return DefaultValue
  551. End Try
  552. End Function
  553. ''' <summary>
  554. ''' 写入注册表键。
  555. ''' </summary>
  556. Public Sub WriteReg(Key As String, Value As String, Optional ThrowException As Boolean = False)
  557. Try
  558. Dim SubKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\" & RegFolder, True)
  559. If SubKey Is Nothing Then SubKey = My.Computer.Registry.CurrentUser.CreateSubKey("Software\" & RegFolder) '如果不存在就创建
  560. SubKey.SetValue(Key, Value)
  561. Catch ex As Exception
  562. Log(ex, "写入注册表出错:" & Key, If(ThrowException, LogLevel.Hint, LogLevel.Developer))
  563. If ThrowException Then Throw
  564. End Try
  565. End Sub
  566. ''' <summary>
  567. ''' 是否存在某个注册表键。
  568. ''' </summary>
  569. Public Function HasReg(Key As String) As Boolean
  570. Return ReadReg(Key, Nothing) IsNot Nothing
  571. End Function
  572. ''' <summary>
  573. ''' 删除注册表键。
  574. ''' </summary>
  575. Public Sub DeleteReg(Key As String, Optional ThrowException As Boolean = False)
  576. Try
  577. Dim SubKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\" & RegFolder, True)
  578. If SubKey?.GetValue(Key) Is Nothing Then Return
  579. SubKey.DeleteValue(Key)
  580. Catch ex As Exception
  581. Log(ex, "删除注册表出错:" & Key, If(ThrowException, LogLevel.Hint, LogLevel.Developer))
  582. If ThrowException Then Throw
  583. End Try
  584. End Sub
  585. '=============================
  586. ' ini
  587. '=============================
  588. Private ReadOnly IniCache As New SafeDictionary(Of String, SafeDictionary(Of String, String))
  589. ''' <summary>
  590. ''' 清除某 ini 文件的运行时缓存。
  591. ''' </summary>
  592. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  593. Public Sub IniClearCache(FileName As String)
  594. If Not FileName.Contains(":\") Then FileName = $"{Path}PCL\{FileName}.ini"
  595. If IniCache.ContainsKey(FileName) Then IniCache.Remove(FileName)
  596. End Sub
  597. ''' <summary>
  598. ''' 获取 ini 文件缓存。如果没有,则新读取 ini 文件内容。
  599. ''' 在文件不存在或读取失败时返回 Nothing。
  600. ''' </summary>
  601. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  602. Private Function IniGetContent(FileName As String) As SafeDictionary(Of String, String)
  603. Try
  604. '还原文件路径
  605. If Not FileName.Contains(":\") Then FileName = $"{Path}PCL\{FileName}.ini"
  606. '检索缓存
  607. If IniCache.ContainsKey(FileName) Then Return IniCache(FileName)
  608. '读取文件
  609. If Not File.Exists(FileName) Then Return Nothing
  610. Dim Ini As New SafeDictionary(Of String, String)
  611. For Each Line In ReadFile(FileName).Split(vbCrLf.ToArray(), StringSplitOptions.RemoveEmptyEntries)
  612. Dim Index As Integer = Line.IndexOfF(":")
  613. If Index > 0 Then Ini(Line.Substring(0, Index)) = Line.Substring(Index + 1) '可能会有重复键,见 #3616
  614. Next
  615. IniCache(FileName) = Ini
  616. Return Ini
  617. Catch ex As Exception
  618. Log(ex, $"生成 ini 文件缓存失败({FileName})", LogLevel.Hint)
  619. Return Nothing
  620. End Try
  621. End Function
  622. ''' <summary>
  623. ''' 读取 ini 文件。这可能会使用到缓存。
  624. ''' </summary>
  625. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  626. ''' <param name="Key">键。</param>
  627. ''' <param name="DefaultValue">没有找到键时返回的默认值。</param>
  628. Public Function ReadIni(FileName As String, Key As String, Optional DefaultValue As String = "") As String
  629. Dim Content = IniGetContent(FileName)
  630. If Content Is Nothing OrElse Not Content.ContainsKey(Key) Then Return DefaultValue
  631. Return Content(Key)
  632. End Function
  633. ''' <summary>
  634. ''' 判断 ini 文件中是否包含某个键。这可能会使用到缓存。
  635. ''' </summary>
  636. Public Function HasIniKey(FileName As String, Key As String) As Boolean
  637. Dim Content = IniGetContent(FileName)
  638. Return Content IsNot Nothing AndAlso Content.ContainsKey(Key)
  639. End Function
  640. ''' <summary>
  641. ''' 从 ini 文件中移除某个键。这会更新缓存。
  642. ''' </summary>
  643. Public Sub DeleteIniKey(FileName As String, Key As String)
  644. WriteIni(FileName, Key, Nothing)
  645. End Sub
  646. ''' <summary>
  647. ''' 写入 ini 文件,这会更新缓存。
  648. ''' 若 Value 为 Nothing,则删除该键。
  649. ''' </summary>
  650. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  651. ''' <param name="Key">键。</param>
  652. ''' <param name="Value">值。</param>
  653. ''' <remarks></remarks>
  654. Public Sub WriteIni(FileName As String, Key As String, Value As String)
  655. Try
  656. '预处理
  657. If Key.Contains(":") Then Throw New Exception($"尝试写入 ini 文件 {FileName} 的键名中包含了冒号:{Key}")
  658. Key = Key.Replace(vbCr, "").Replace(vbLf, "")
  659. Value = Value?.Replace(vbCr, "").Replace(vbLf, "")
  660. '防止争用
  661. SyncLock WriteIniLock
  662. '获取目前文件
  663. Dim Content As SafeDictionary(Of String, String) = IniGetContent(FileName)
  664. If Content Is Nothing Then Content = New SafeDictionary(Of String, String)
  665. '更新值
  666. If Value Is Nothing Then
  667. If Not Content.ContainsKey(Key) Then Return '无需处理
  668. Content.Remove(Key)
  669. Else
  670. If Content.ContainsKey(Key) AndAlso Content(Key) = Value Then Return '无需处理
  671. Content(Key) = Value
  672. End If
  673. '写入文件
  674. Dim FileContent As New StringBuilder
  675. For Each Pair In Content
  676. FileContent.Append(Pair.Key)
  677. FileContent.Append(":")
  678. FileContent.Append(Pair.Value)
  679. FileContent.Append(vbCrLf)
  680. Next
  681. If Not FileName.Contains(":\") Then FileName = $"{Path}PCL\{FileName}.ini"
  682. WriteFile(FileName, FileContent.ToString)
  683. End SyncLock
  684. Catch ex As Exception
  685. Log(ex, $"写入文件失败({FileName} → {Key}:{Value})", LogLevel.Hint)
  686. End Try
  687. End Sub
  688. Private WriteIniLock As New Object
  689. '路径处理
  690. ''' <summary>
  691. ''' 从文件路径或者 Url 获取不包含文件名的路径,或获取文件夹的父文件夹路径。
  692. ''' 取决于原路径格式,路径以 / 或 \ 结尾。
  693. ''' 不包含路径将会抛出异常。
  694. ''' </summary>
  695. Public Function GetPathFromFullPath(FilePath As String) As String
  696. If Not (FilePath.Contains("\") OrElse FilePath.Contains("/")) Then Throw New Exception("不包含路径:" & FilePath)
  697. If FilePath.EndsWithF("\") OrElse FilePath.EndsWithF("/") Then
  698. '是文件夹路径
  699. Dim IsRight As Boolean = FilePath.EndsWithF("\")
  700. FilePath = Left(FilePath, Len(FilePath) - 1)
  701. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"})) & If(IsRight, "\", "/")
  702. Else
  703. '是文件路径
  704. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"}) + 1)
  705. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  706. End If
  707. End Function
  708. ''' <summary>
  709. ''' 从文件路径或者 Url 获取不包含路径的文件名。不包含文件名将会抛出异常。
  710. ''' </summary>
  711. Public Function GetFileNameFromPath(FilePath As String) As String
  712. FilePath = FilePath.Replace("/", "\")
  713. If FilePath.EndsWithF("\") Then Throw New Exception("不包含文件名:" & FilePath)
  714. If FilePath.Contains("?") Then FilePath = FilePath.Substring(0, FilePath.IndexOfF("?")) '去掉网络参数后的 ?
  715. If FilePath.Contains("\") Then FilePath = FilePath.Substring(FilePath.LastIndexOfF("\") + 1)
  716. Dim length As Integer = FilePath.Length
  717. If length = 0 Then Throw New Exception("不包含文件名:" & FilePath)
  718. Return FilePath
  719. End Function
  720. ''' <summary>
  721. ''' 从文件夹路径获取文件夹名。
  722. ''' </summary>
  723. Public Function GetFolderNameFromPath(FolderPath As String) As String
  724. If FolderPath.EndsWithF(":\") OrElse FolderPath.EndsWithF(":\\") Then Return FolderPath.Substring(0, 1)
  725. If FolderPath.EndsWithF("\") OrElse FolderPath.EndsWithF("/") Then FolderPath = Left(FolderPath, FolderPath.Length - 1)
  726. Return GetFileNameFromPath(FolderPath)
  727. End Function
  728. '读取、写入、复制文件
  729. ''' <summary>
  730. ''' 复制文件。会自动创建文件夹、会覆盖已有的文件。
  731. ''' </summary>
  732. Public Sub CopyFile(FromPath As String, ToPath As String)
  733. Try
  734. '还原文件路径
  735. FromPath = If(FromPath.Contains(":\"), FromPath, Path & FromPath)
  736. ToPath = If(ToPath.Contains(":\"), ToPath, Path & ToPath)
  737. '如果复制同一个文件则跳过
  738. If FromPath = ToPath Then Return
  739. '确保目录存在
  740. Directory.CreateDirectory(GetPathFromFullPath(ToPath))
  741. '复制文件
  742. File.Copy(FromPath, ToPath, True)
  743. Catch ex As Exception
  744. Throw New Exception("复制文件出错:" & FromPath & " → " & ToPath, ex)
  745. End Try
  746. End Sub
  747. ''' <summary>
  748. ''' 读取文件,如果失败则返回空数组。
  749. ''' </summary>
  750. Public Function ReadFileBytes(FilePath As String, Optional Encoding As Encoding = Nothing) As Byte()
  751. Try
  752. '还原文件路径
  753. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  754. If File.Exists(FilePath) Then
  755. Dim FileBytes As Byte()
  756. Using ReadStream As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) '支持读取使用中的文件
  757. ReDim FileBytes(ReadStream.Length - 1)
  758. ReadStream.Read(FileBytes, 0, ReadStream.Length)
  759. End Using
  760. Return FileBytes
  761. Else
  762. Log("[System] 欲读取的文件不存在,已返回空内容:" & FilePath)
  763. Return {}
  764. End If
  765. Catch ex As Exception
  766. Log(ex, "读取文件出错:" & FilePath)
  767. Return {}
  768. End Try
  769. End Function
  770. ''' <summary>
  771. ''' 读取文件,如果失败则返回空字符串。
  772. ''' </summary>
  773. ''' <param name="FilePath">文件完整或相对路径。</param>
  774. Public Function ReadFile(FilePath As String, Optional Encoding As Encoding = Nothing) As String
  775. Dim FileBytes = ReadFileBytes(FilePath)
  776. ReadFile = If(Encoding Is Nothing, DecodeBytes(FileBytes), Encoding.GetString(FileBytes))
  777. End Function
  778. ''' <summary>
  779. ''' 读取流中的所有文本。
  780. ''' </summary>
  781. Public Function ReadFile(Stream As Stream, Optional Encoding As Encoding = Nothing) As String
  782. Try
  783. Dim srcBuf As Byte() = New Byte(16384) {}
  784. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  785. Dim Result As New List(Of Byte)
  786. While DataCount > 0
  787. If DataCount > 0 Then Result.AddRange(srcBuf.ToList.GetRange(0, DataCount))
  788. DataCount = Stream.Read(srcBuf, 0, 16384)
  789. End While
  790. Dim Bts = Result.ToArray
  791. Return If(Encoding, GetEncoding(Bts)).GetString(Bts)
  792. Catch ex As Exception
  793. Log(ex, "读取流出错")
  794. Return ""
  795. End Try
  796. End Function
  797. ''' <summary>
  798. ''' 写入文件。
  799. ''' </summary>
  800. ''' <param name="FilePath">文件完整或相对路径。</param>
  801. ''' <param name="Text">文件内容。</param>
  802. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  803. Public Sub WriteFile(FilePath As String, Text As String, Optional Append As Boolean = False, Optional Encoding As Encoding = Nothing)
  804. '处理相对路径
  805. FilePath = If(FilePath.Contains(":\"), FilePath, Path & FilePath)
  806. '确保目录存在
  807. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  808. '写入文件
  809. If Append Then
  810. '追加目前文件
  811. Using writer As New StreamWriter(FilePath, True, If(Encoding, GetEncoding(ReadFileBytes(FilePath))))
  812. writer.Write(Text)
  813. writer.Flush()
  814. writer.Close()
  815. End Using
  816. Else
  817. '直接写入字节
  818. File.WriteAllBytes(FilePath, If(Encoding Is Nothing, New UTF8Encoding(False).GetBytes(Text), Encoding.GetBytes(Text)))
  819. End If
  820. End Sub
  821. ''' <summary>
  822. ''' 写入文件。
  823. ''' 如果 CanThrow 设置为 False,返回是否写入成功。
  824. ''' </summary>
  825. ''' <param name="FilePath">文件完整或相对路径。</param>
  826. ''' <param name="Content">文件内容。</param>
  827. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  828. Public Sub WriteFile(FilePath As String, Content As Byte(), Optional Append As Boolean = False)
  829. '处理相对路径
  830. FilePath = If(FilePath.Contains(":\"), FilePath, Path & FilePath)
  831. '确保目录存在
  832. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  833. '写入文件
  834. File.WriteAllBytes(FilePath, Content)
  835. End Sub
  836. ''' <summary>
  837. ''' 将流写入文件。
  838. ''' </summary>
  839. ''' <param name="FilePath">文件完整或相对路径。</param>
  840. Public Function WriteFile(FilePath As String, Stream As Stream) As Boolean
  841. Try
  842. '还原文件路径
  843. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  844. '确保目录存在
  845. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  846. '读取流
  847. Using fs As New FileStream(FilePath, FileMode.Create, FileAccess.Write)
  848. Dim srcBuf As Byte() = New Byte(16384) {}
  849. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  850. While DataCount > 0
  851. If DataCount > 0 Then fs.Write(srcBuf, 0, DataCount)
  852. DataCount = Stream.Read(srcBuf, 0, 16384)
  853. End While
  854. fs.Close()
  855. End Using
  856. Return True
  857. Catch ex As Exception
  858. Log(ex, "保存流出错")
  859. Return False
  860. End Try
  861. End Function
  862. '文件编码
  863. ''' <summary>
  864. ''' 根据字节数组分析其编码。
  865. ''' </summary>
  866. Public Function GetEncoding(Bytes As Byte()) As Encoding
  867. Dim Length As Integer = Bytes.Count
  868. If Length < 3 Then Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  869. '根据 BOM 判断编码
  870. If Bytes(0) >= &HEF Then
  871. '有 BOM 类型
  872. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  873. Return New UTF8Encoding(True) '带 BOM 的 UTF8
  874. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  875. Return Encoding.BigEndianUnicode
  876. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  877. Return Encoding.Unicode
  878. Else
  879. Return Encoding.GetEncoding("GB18030")
  880. End If
  881. End If
  882. '无 BOM 文件:GB18030(ANSI)或 UTF8
  883. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  884. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  885. If UTF8.Contains(ErrorChar) Then
  886. Return Encoding.GetEncoding("GB18030")
  887. Else
  888. Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  889. End If
  890. End Function
  891. ''' <summary>
  892. ''' 解码 Bytes。
  893. ''' </summary>
  894. Public Function DecodeBytes(Bytes As Byte()) As String
  895. Dim Length As Integer = Bytes.Length
  896. If Length < 3 Then Return Encoding.UTF8.GetString(Bytes)
  897. '根据 BOM 判断编码
  898. If Bytes(0) >= &HEF Then
  899. '有 BOM 类型
  900. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  901. Return Encoding.UTF8.GetString(Bytes, 3, Length - 3)
  902. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  903. Return Encoding.BigEndianUnicode.GetString(Bytes, 3, Length - 3)
  904. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  905. Return Encoding.Unicode.GetString(Bytes, 3, Length - 3)
  906. Else
  907. Return Encoding.GetEncoding("GB18030").GetString(Bytes, 3, Length - 3)
  908. End If
  909. End If
  910. '无 BOM 文件:GB18030(ANSI)或 UTF8
  911. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  912. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  913. If UTF8.Contains(ErrorChar) Then
  914. Return Encoding.GetEncoding("GB18030").GetString(Bytes)
  915. Else
  916. Return UTF8
  917. End If
  918. End Function
  919. '对话框
  920. ''' <summary>
  921. ''' 弹出保存对话框并且要求保存位置,返回用户输入的完整路径。
  922. ''' </summary>
  923. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  924. ''' <param name="Title">弹窗的标题。</param>
  925. ''' <param name="FileName">默认的文件名。</param>
  926. Public Function SelectSaveFile(Title As String, FileName As String, Optional FileFilter As String = Nothing, Optional InitialDirectory As String = Nothing) As String
  927. Using fileDialog As New Forms.SaveFileDialog
  928. fileDialog.AddExtension = True
  929. fileDialog.AutoUpgradeEnabled = True
  930. fileDialog.Title = Title
  931. fileDialog.FileName = FileName
  932. If FileFilter IsNot Nothing Then fileDialog.Filter = FileFilter
  933. If Not String.IsNullOrEmpty(InitialDirectory) AndAlso Directory.Exists(InitialDirectory) Then fileDialog.InitialDirectory = InitialDirectory
  934. fileDialog.ShowDialog()
  935. SelectSaveFile = If(fileDialog.FileName.Contains(":\"), fileDialog.FileName, "")
  936. Log("[UI] 选择文件返回:" & SelectSaveFile)
  937. End Using
  938. End Function
  939. ''' <summary>
  940. ''' 弹出选取文件对话框,要求选择一个文件。
  941. ''' </summary>
  942. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  943. ''' <param name="Title">弹窗的标题。</param>
  944. Public Function SelectFile(FileFilter As String, Title As String, Optional InitialDirectory As String = Nothing) As String
  945. Using fileDialog As New Forms.OpenFileDialog
  946. fileDialog.AddExtension = True
  947. fileDialog.AutoUpgradeEnabled = True
  948. fileDialog.CheckFileExists = True
  949. fileDialog.Filter = FileFilter
  950. fileDialog.Multiselect = False
  951. fileDialog.Title = Title
  952. fileDialog.ValidateNames = True
  953. If Not String.IsNullOrEmpty(InitialDirectory) AndAlso Directory.Exists(InitialDirectory) Then fileDialog.InitialDirectory = InitialDirectory
  954. fileDialog.ShowDialog()
  955. Log("[UI] 选择单个文件返回:" & fileDialog.FileName)
  956. Return fileDialog.FileName
  957. End Using
  958. End Function
  959. ''' <summary>
  960. ''' 弹出选取文件对话框,要求选择多个文件。
  961. ''' </summary>
  962. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  963. ''' <param name="Title">弹窗的标题。</param>
  964. Public Function SelectFiles(FileFilter As String, Title As String) As String()
  965. Using fileDialog As New Forms.OpenFileDialog
  966. fileDialog.AddExtension = True
  967. fileDialog.AutoUpgradeEnabled = True
  968. fileDialog.CheckFileExists = True
  969. fileDialog.Filter = FileFilter
  970. fileDialog.Multiselect = True
  971. fileDialog.Title = Title
  972. fileDialog.ValidateNames = True
  973. fileDialog.ShowDialog()
  974. Log("[UI] 选择多个文件返回:" & fileDialog.FileNames.Join(","))
  975. Return fileDialog.FileNames
  976. End Using
  977. End Function
  978. ''' <summary>
  979. ''' 弹出选取文件夹对话框,要求选取文件夹。
  980. ''' 返回以 \ 结尾的完整路径,如果没有选择则返回空字符串。
  981. ''' </summary>
  982. Public Function SelectFolder(Optional Title As String = "选择文件夹") As String
  983. Dim folderDialog As New Ookii.Dialogs.Wpf.VistaFolderBrowserDialog With {.ShowNewFolderButton = True, .RootFolder = Environment.SpecialFolder.Desktop, .Description = Title, .UseDescriptionForTitle = True}
  984. folderDialog.ShowDialog()
  985. SelectFolder = If(String.IsNullOrEmpty(folderDialog.SelectedPath), "", folderDialog.SelectedPath & If(folderDialog.SelectedPath.EndsWithF("\"), "", "\"))
  986. Log("[UI] 选择文件夹返回:" & SelectFolder)
  987. End Function
  988. '文件校验
  989. ''' <summary>
  990. ''' 检查是否拥有某一文件夹的 I/O 权限。如果文件夹不存在,会返回 False。
  991. ''' </summary>
  992. Public Function CheckPermission(Path As String) As Boolean
  993. Try
  994. If String.IsNullOrEmpty(Path) Then Return False
  995. If Not Path.EndsWithF("\") Then Path += "\"
  996. If Path.EndsWithF(":\System Volume Information\") OrElse Path.EndsWithF(":\$RECYCLE.BIN\") Then Return False
  997. If Not Directory.Exists(Path) Then Return False
  998. Dim FileName As String = "CheckPermission" & GetUuid()
  999. If File.Exists(Path & FileName) Then File.Delete(Path & FileName)
  1000. File.Create(Path & FileName).Dispose()
  1001. File.Delete(Path & FileName)
  1002. Return True
  1003. Catch ex As Exception
  1004. Log(ex, "没有对文件夹 " & Path & " 的权限,请尝试以管理员权限运行 PCL")
  1005. Return False
  1006. End Try
  1007. End Function
  1008. ''' <summary>
  1009. ''' 检查是否拥有某一文件夹的 I/O 权限。如果出错,则抛出异常。
  1010. ''' </summary>
  1011. Public Sub CheckPermissionWithException(Path As String)
  1012. If String.IsNullOrWhiteSpace(Path) Then Throw New ArgumentNullException("文件夹名不能为空!")
  1013. If Not Path.EndsWithF("\") Then Path += "\"
  1014. If Not Directory.Exists(Path) Then Throw New DirectoryNotFoundException("文件夹不存在!")
  1015. If File.Exists(Path & "CheckPermission") Then File.Delete(Path & "CheckPermission")
  1016. File.Create(Path & "CheckPermission").Dispose()
  1017. File.Delete(Path & "CheckPermission")
  1018. End Sub
  1019. ''' <summary>
  1020. ''' 获取文件 MD5,若失败则返回空字符串。
  1021. ''' </summary>
  1022. Public Function GetFileMD5(FilePath As String) As String
  1023. Dim Retried As Boolean = False
  1024. Re:
  1025. Try
  1026. Using File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1027. Using h = MD5Cng.Create()
  1028. Dim Retval As Byte() = h.ComputeHash(File)
  1029. Dim Result As New StringBuilder(Retval.Length * 2)
  1030. For i = 0 To Retval.Length - 1
  1031. Result.Append(Retval(i).ToString("x2"))
  1032. Next
  1033. Return Result.ToString
  1034. End Using
  1035. End Using
  1036. Catch ex As Exception
  1037. If Retried OrElse TypeOf ex Is FileNotFoundException Then
  1038. Log(ex, "获取文件 MD5 失败:" & FilePath)
  1039. Return ""
  1040. Else
  1041. Retried = True
  1042. Log(ex, "获取文件 MD5 可重试失败:" & FilePath, LogLevel.Normal)
  1043. Thread.Sleep(RandomInteger(200, 500))
  1044. GoTo Re
  1045. End If
  1046. End Try
  1047. End Function
  1048. ''' <summary>
  1049. ''' 获取文件 SHA512,若失败则返回空字符串。
  1050. ''' </summary>
  1051. Public Function GetFileSHA512(FilePath As String) As String
  1052. Dim Retried As Boolean = False
  1053. Re:
  1054. Try
  1055. Using File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1056. Using h = SHA512Cng.Create()
  1057. Dim retval As Byte() = h.ComputeHash(File)
  1058. Dim Result As New StringBuilder(retval.Length * 2)
  1059. For i As Integer = 0 To retval.Length - 1
  1060. Result.Append(retval(i).ToString("x2"))
  1061. Next
  1062. Return Result.ToString
  1063. End Using
  1064. End Using
  1065. Catch ex As Exception
  1066. If Retried OrElse TypeOf ex Is FileNotFoundException Then
  1067. Log(ex, "获取文件 SHA512 失败:" & FilePath)
  1068. Return ""
  1069. Else
  1070. Retried = True
  1071. Log(ex, "获取文件 SHA512 可重试失败:" & FilePath, LogLevel.Normal)
  1072. Thread.Sleep(RandomInteger(200, 500))
  1073. GoTo Re
  1074. End If
  1075. End Try
  1076. End Function
  1077. ''' <summary>
  1078. ''' 获取文件 SHA256,若失败则返回空字符串。
  1079. ''' </summary>
  1080. Public Function GetFileSHA256(FilePath As String) As String
  1081. Dim Retry As Boolean = False
  1082. Re:
  1083. Try
  1084. Using File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1085. Using h = SHA256Cng.Create()
  1086. Dim retval As Byte() = h.ComputeHash(File)
  1087. Dim Result As New StringBuilder(retval.Length * 2)
  1088. For i As Integer = 0 To retval.Length - 1
  1089. Result.Append(retval(i).ToString("x2"))
  1090. Next
  1091. Return Result.ToString()
  1092. End Using
  1093. End Using
  1094. Catch ex As Exception
  1095. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1096. Log(ex, "获取文件 SHA256 失败:" & FilePath)
  1097. Return ""
  1098. Else
  1099. Retry = True
  1100. Log(ex, "获取文件 SHA256 可重试失败:" & FilePath, LogLevel.Normal)
  1101. Thread.Sleep(RandomInteger(200, 500))
  1102. GoTo Re
  1103. End If
  1104. End Try
  1105. End Function
  1106. ''' <summary>
  1107. ''' 获取文件 SHA1,若失败则返回空字符串。
  1108. ''' </summary>
  1109. Public Function GetFileSHA1(FilePath As String) As String
  1110. Dim Retry As Boolean = False
  1111. Re:
  1112. Try
  1113. Using File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1114. Using h = SHA1Cng.Create()
  1115. Dim retval As Byte() = h.ComputeHash(File)
  1116. Dim Result As New StringBuilder(retval.Length * 2)
  1117. For i As Integer = 0 To retval.Length - 1
  1118. Result.Append(retval(i).ToString("x2"))
  1119. Next
  1120. Return Result.ToString
  1121. End Using
  1122. End Using
  1123. Catch ex As Exception
  1124. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1125. Log(ex, "获取文件 SHA1 失败:" & FilePath)
  1126. Return ""
  1127. Else
  1128. Retry = True
  1129. Log(ex, "获取文件 SHA1 可重试失败:" & FilePath, LogLevel.Normal)
  1130. Thread.Sleep(RandomInteger(200, 500))
  1131. GoTo Re
  1132. End If
  1133. End Try
  1134. End Function
  1135. ''' <summary>
  1136. ''' 获取流的 SHA1,若失败则返回空字符串。
  1137. ''' </summary>
  1138. Public Function GetAuthSHA1(Stream As Stream) As String
  1139. Try
  1140. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1141. Dim retval As Byte() = sha1.ComputeHash(Stream)
  1142. Dim Result As New StringBuilder()
  1143. For i As Integer = 0 To retval.Length - 1
  1144. Result.Append(retval(i).ToString("x2"))
  1145. Next
  1146. Return Result.ToString
  1147. Catch ex As Exception
  1148. Log(ex, "获取流 SHA1 失败")
  1149. Return ""
  1150. End Try
  1151. End Function
  1152. ''' <summary>
  1153. ''' 文件的校验规则。
  1154. ''' </summary>
  1155. Public Class FileChecker
  1156. ''' <summary>
  1157. ''' 文件的准确大小。
  1158. ''' 不检查则为 -1。
  1159. ''' </summary>
  1160. Public ActualSize As Long = -1
  1161. ''' <summary>
  1162. ''' 文件的最小大小。
  1163. ''' 不检查则为 -1。
  1164. ''' </summary>
  1165. Public MinSize As Long = -1
  1166. ''' <summary>
  1167. ''' 文件的 MD5、SHA1 或 SHA256。会根据输入字符串的长度自动判断种类。
  1168. ''' 不检查则为 Nothing。
  1169. ''' </summary>
  1170. Public Hash As String = Nothing
  1171. ''' <summary>
  1172. ''' 是否可以使用已经存在的文件。
  1173. ''' </summary>
  1174. Public CanUseExistsFile As Boolean = True
  1175. ''' <summary>
  1176. ''' 是否要求为 JSON 文件。
  1177. ''' 即,开头结尾必须为 {} 或 []。
  1178. ''' </summary>
  1179. Public IsJson As Boolean = False
  1180. Public Sub New(Optional MinSize As Long = -1, Optional ActualSize As Long = -1, Optional Hash As String = Nothing, Optional CanUseExistsFile As Boolean = True, Optional IsJson As Boolean = False)
  1181. Me.ActualSize = ActualSize
  1182. Me.MinSize = MinSize
  1183. Me.Hash = Hash
  1184. Me.CanUseExistsFile = CanUseExistsFile
  1185. Me.IsJson = IsJson
  1186. End Sub
  1187. ''' <summary>
  1188. ''' 检查文件。若成功则返回 Nothing,失败则返回错误的描述文本,描述文本不以句号结尾。不会抛出错误。
  1189. ''' </summary>
  1190. Public Function Check(LocalPath As String) As String
  1191. Try
  1192. Dim Info As New FileInfo(LocalPath)
  1193. If Not Info.Exists Then Return "文件不存在:" & LocalPath
  1194. Dim FileSize As Long = Info.Length
  1195. If ActualSize >= 0 AndAlso ActualSize <> FileSize Then
  1196. Return $"文件大小应为 {ActualSize} B,实际为 {FileSize} B" &
  1197. If(FileSize < 2000, ",内容为:" & ReadFile(LocalPath), "")
  1198. End If
  1199. If MinSize >= 0 AndAlso MinSize > FileSize Then
  1200. Return $"文件大小应大于 {MinSize} B,实际为 {FileSize} B" &
  1201. If(FileSize < 2000, ",内容为:" & ReadFile(LocalPath), "")
  1202. End If
  1203. If Not String.IsNullOrEmpty(Hash) Then
  1204. If Hash.Length < 35 Then 'MD5
  1205. If Hash.Lower <> GetFileMD5(LocalPath) Then Return "文件 MD5 应为 " & Hash & ",实际为 " & GetFileMD5(LocalPath)
  1206. ElseIf Hash.Length = 64 Then 'SHA256
  1207. If Hash.Lower <> GetFileSHA256(LocalPath) Then Return "文件 SHA256 应为 " & Hash & ",实际为 " & GetFileSHA256(LocalPath)
  1208. Else 'SHA1 (40)
  1209. If Hash.Lower <> GetFileSHA1(LocalPath) Then Return "文件 SHA1 应为 " & Hash & ",实际为 " & GetFileSHA1(LocalPath)
  1210. End If
  1211. End If
  1212. If IsJson Then
  1213. Dim Content As String = ReadFile(LocalPath)
  1214. If Content = "" Then Throw New Exception("读取到的文件为空")
  1215. Try
  1216. GetJson(Content)
  1217. Catch ex As Exception
  1218. Throw New Exception("不是有效的 json 文件", ex)
  1219. End Try
  1220. End If
  1221. Return Nothing
  1222. Catch ex As Exception
  1223. Log(ex, "检查文件出错")
  1224. Return ex.GetBrief()
  1225. End Try
  1226. End Function
  1227. End Class
  1228. ''' <summary>
  1229. ''' 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  1230. ''' 会尝试创建,但不会清空目标文件夹。
  1231. ''' 会先使用 UTF-8 解压,失败后换用 GB18030 解压。
  1232. ''' </summary>
  1233. Public Sub ExtractCompressedFile(CompressFilePath As String, DestDirectory As String, Optional ProgressIncrementHandler As Action(Of Double) = Nothing)
  1234. Directory.CreateDirectory(DestDirectory)
  1235. '解压 gz(gz 不需要考虑编码)
  1236. If CompressFilePath.EndsWithF(".gz", True) Then
  1237. Using stream As New GZipStream(New FileStream(CompressFilePath, FileMode.Open, FileAccess.Read, FileShare.Read), CompressionMode.Decompress)
  1238. Using decompressedFile As New FileStream(DestDirectory & GetFileNameFromPath(CompressFilePath).Lower.Replace(".tar", "").Replace(".gz", ""),
  1239. FileMode.OpenOrCreate, FileAccess.Write)
  1240. Dim data As Integer = stream.ReadByte()
  1241. While data <> -1
  1242. decompressedFile.WriteByte(data)
  1243. data = stream.ReadByte()
  1244. End While
  1245. End Using
  1246. End Using
  1247. Return
  1248. End If
  1249. '解压 zip
  1250. Dim TryExtractZip =
  1251. Sub(Encoding As Encoding)
  1252. Using Archive = ZipFile.Open(CompressFilePath, ZipArchiveMode.Read, Encoding)
  1253. Dim EntryCount = Archive.Entries.Count
  1254. For Each Entry In Archive.Entries
  1255. If ProgressIncrementHandler IsNot Nothing AndAlso EntryCount > 0 Then ProgressIncrementHandler(1 / EntryCount)
  1256. Dim DestinationFullPath As String = IO.Path.Combine(DestDirectory, Entry.FullName)
  1257. If Not IO.Path.GetFullPath(DestinationFullPath).StartsWithF(IO.Path.GetFullPath(DestDirectory), True) Then Continue For 'ZipSlip 漏洞修复
  1258. If DestinationFullPath.EndsWithF("\") OrElse DestinationFullPath.EndsWithF("/") Then Continue For '不创建空文件夹
  1259. Dim DestinationDirectory As String = GetPathFromFullPath(DestinationFullPath)
  1260. Directory.CreateDirectory(DestinationDirectory)
  1261. Entry.ExtractToFile(DestinationFullPath.Replace(DestinationDirectory, ShortenPath(DestinationDirectory)), True) '#7329
  1262. Next
  1263. End Using
  1264. End Sub
  1265. Try
  1266. TryExtractZip(New UTF8Encoding(False, True))
  1267. Catch ex As Exception
  1268. Log(ex, $"首次解压尝试失败,将更换编码并重试({CompressFilePath} → {DestDirectory})")
  1269. Try
  1270. TryExtractZip(Encoding.GetEncoding("GB18030"))
  1271. Catch
  1272. Throw
  1273. End Try
  1274. End Try
  1275. End Sub
  1276. ''' <summary>
  1277. ''' 删除文件夹,返回删除的文件个数。通过参数选择是否抛出异常。
  1278. ''' </summary>
  1279. Public Function DeleteDirectory(Path As String, Optional IgnoreIssue As Boolean = False) As Integer
  1280. If Not Directory.Exists(Path) Then Return 0
  1281. If Not Path.EndsWithF("\") Then Path &= "\"
  1282. If Path.EndsWithF(":\") OrElse
  1283. Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" OrElse
  1284. Path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\" OrElse
  1285. Path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) & "\" Then '#7030
  1286. Throw New UnauthorizedAccessException("这是重要的系统文件夹,无法删除:" & Path)
  1287. End If
  1288. '实际删除
  1289. Dim DeletedCount As Integer = 0
  1290. Dim Files As String()
  1291. Try
  1292. Files = Directory.GetFiles(Path)
  1293. Catch ex As DirectoryNotFoundException '#4549
  1294. If Not Directory.Exists(Path) Then Return 0 '可能已被其他线程删除
  1295. Log(ex, $"疑似为孤立符号链接,尝试直接删除({Path})", LogLevel.Developer)
  1296. Directory.Delete(Path)
  1297. Return 0
  1298. End Try
  1299. For Each FilePath As String In Files
  1300. Dim RetriedFile As Boolean = False
  1301. RetryFile:
  1302. Try
  1303. File.Delete(FilePath)
  1304. DeletedCount += 1
  1305. Catch ex As Exception
  1306. If Not RetriedFile Then
  1307. RetriedFile = True
  1308. Log(ex, $"删除文件失败,将在 0.3s 后重试({FilePath})")
  1309. Thread.Sleep(300)
  1310. GoTo RetryFile
  1311. ElseIf IgnoreIssue Then
  1312. Log(ex, "删除单个文件可忽略地失败")
  1313. Else
  1314. Throw
  1315. End If
  1316. End Try
  1317. Next
  1318. For Each str As String In Directory.GetDirectories(Path)
  1319. DeleteDirectory(str, IgnoreIssue)
  1320. Next
  1321. Dim RetriedDir As Boolean = False
  1322. RetryDir:
  1323. Try
  1324. Directory.Delete(Path, True)
  1325. Catch ex As DirectoryNotFoundException
  1326. Catch ex As Exception
  1327. If Not RetriedDir AndAlso Not RunInUi() Then
  1328. RetriedDir = True
  1329. Log(ex, $"删除文件夹失败,将在 0.3s 后重试({Path})")
  1330. Thread.Sleep(300)
  1331. GoTo RetryDir
  1332. ElseIf IgnoreIssue Then
  1333. Log(ex, "删除单个文件夹可忽略地失败")
  1334. Else
  1335. Throw
  1336. End If
  1337. End Try
  1338. Return DeletedCount
  1339. End Function
  1340. ''' <summary>
  1341. ''' 复制文件夹,失败会抛出异常。
  1342. ''' </summary>
  1343. Public Sub CopyDirectory(FromPath As String, ToPath As String, Optional ProgressIncrementHandler As Action(Of Double) = Nothing)
  1344. FromPath = FromPath.Replace("/", "\")
  1345. If Not FromPath.EndsWithF("\") Then FromPath &= "\"
  1346. ToPath = ToPath.Replace("/", "\")
  1347. If Not ToPath.EndsWithF("\") Then ToPath &= "\"
  1348. Dim AllFiles = EnumerateFiles(FromPath).ToList
  1349. Dim FileCount As Long = AllFiles.Count
  1350. For Each File In AllFiles
  1351. CopyFile(File.FullName, File.FullName.Replace(FromPath, ToPath))
  1352. If ProgressIncrementHandler IsNot Nothing AndAlso FileCount > 0 Then ProgressIncrementHandler(1 / FileCount)
  1353. Next
  1354. End Sub
  1355. ''' <summary>
  1356. ''' 遍历文件夹中的所有文件。
  1357. ''' </summary>
  1358. Public Function EnumerateFiles(Directory As String) As IEnumerable(Of FileInfo)
  1359. Dim Info As New DirectoryInfo(Directory)
  1360. If Not Info.Exists Then Return New List(Of FileInfo)
  1361. Return Info.EnumerateFiles("*", SearchOption.AllDirectories)
  1362. End Function
  1363. ''' <summary>
  1364. ''' 若路径长度大于指定值,则将长路径转换为短路径。
  1365. ''' </summary>
  1366. Public Function ShortenPath(Raw As String) As String
  1367. If Raw.Length <= 200 OrElse Raw.StartsWithF("http", True) Then Return Raw
  1368. If Not Directory.Exists(Raw) AndAlso Not File.Exists(Raw) Then Return Raw
  1369. Dim PathToShorten As String, Ignored As String
  1370. If Not Directory.Exists(Raw) AndAlso Raw.EndsWithF(".jar", True) Then '只能缩短文件夹部分,必须保留 jar 文件名,否则会导致 Forge 1.20.1 无法通过文件名识别模块名
  1371. PathToShorten = GetPathFromFullPath(Raw)
  1372. Ignored = GetFileNameFromPath(Raw)
  1373. Else
  1374. PathToShorten = Raw
  1375. Ignored = ""
  1376. End If
  1377. Dim ShortPathBuffer As New StringBuilder(260)
  1378. GetShortPathNameW(PathToShorten.Replace("/", "\"), ShortPathBuffer, 260)
  1379. Dim DirShortPath As String = ShortPathBuffer.ToString()
  1380. If String.IsNullOrEmpty(DirShortPath) Then Return Raw
  1381. Return If(String.IsNullOrEmpty(Ignored), DirShortPath, IO.Path.Combine(DirShortPath, Ignored))
  1382. End Function
  1383. Private Declare Unicode Function GetShortPathNameW Lib "kernel32" Alias "GetShortPathNameW" (lpszLongPath As String, lpszShortPath As StringBuilder, cchBuffer As Integer) As Integer
  1384. #End Region
  1385. #Region "文本"
  1386. Public vbLQ As Char = Convert.ToChar(8220)
  1387. Public vbRQ As Char = Convert.ToChar(8221)
  1388. ''' <summary>
  1389. ''' 提取 Exception 与 Inner Exception 的详细描述与堆栈信息。返回内容总是多于一行。
  1390. ''' </summary>
  1391. ''' <param name="ShowAllStacks">是否必须显示所有堆栈。通常用于判定堆栈信息。</param>
  1392. <Extension> Public Function GetDetail(Ex As Exception, Optional ShowAllStacks As Boolean = False) As String
  1393. If Ex Is Nothing Then Return "无可用错误信息!"
  1394. '获取最底层的异常
  1395. Dim OuterEx As Exception = Ex
  1396. Dim InnerEx As Exception = Ex
  1397. Do Until InnerEx.InnerException Is Nothing
  1398. InnerEx = InnerEx.InnerException
  1399. Loop
  1400. '获取各级错误的描述与堆栈信息
  1401. Dim DescList As New List(Of String)
  1402. Dim IsInner As Boolean = False
  1403. Do Until Ex Is Nothing
  1404. DescList.Add(If(IsInner, "→ ", "") & Ex.Message.Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, vbCrLf))
  1405. If Ex.StackTrace IsNot Nothing Then
  1406. For Each Stack As String In Ex.StackTrace.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
  1407. If ShowAllStacks OrElse Stack.ContainsF("pcl", True) Then
  1408. DescList.Add(Stack.Replace(vbCr, String.Empty).Replace(vbLf, String.Empty))
  1409. End If
  1410. Next
  1411. End If
  1412. If Ex.GetType.FullName <> "System.Exception" Then DescList.Add(" 错误类型:" & Ex.GetType.FullName)
  1413. Ex = Ex.InnerException
  1414. IsInner = True
  1415. Loop
  1416. '构造输出信息
  1417. Dim UsualReason As String = AnalyzeUsualReason(InnerEx, OuterEx, DescList)
  1418. If UsualReason Is Nothing Then
  1419. Return DescList.Join(vbCrLf)
  1420. Else
  1421. Return UsualReason & vbCrLf & vbCrLf & "————————————" & vbCrLf & "详细错误信息:" & vbCrLf & DescList.Join(vbCrLf)
  1422. End If
  1423. End Function
  1424. ''' <summary>
  1425. ''' 提取 Exception 与 Inner Exception 的描述,汇总到一行。
  1426. ''' </summary>
  1427. <Extension> Public Function GetBrief(Ex As Exception) As String
  1428. If Ex Is Nothing Then Return "无可用错误信息!"
  1429. '获取最底层的异常
  1430. Dim OuterEx As Exception = Ex
  1431. Dim InnerEx As Exception = Ex
  1432. Do Until InnerEx.InnerException Is Nothing
  1433. InnerEx = InnerEx.InnerException
  1434. Loop
  1435. '获取各级错误的描述
  1436. Dim DescList As New List(Of String)
  1437. Do Until Ex Is Nothing
  1438. DescList.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, " "))
  1439. Ex = Ex.InnerException
  1440. Loop
  1441. DescList = DescList.Distinct.ToList
  1442. Dim Desc As String = DescList.Join(vbCrLf & "→ ")
  1443. '构造输出信息
  1444. Dim UsualReason As String = AnalyzeUsualReason(InnerEx, OuterEx, DescList)
  1445. If UsualReason IsNot Nothing Then
  1446. Return UsualReason & "详细错误:" & DescList.First
  1447. Else
  1448. DescList.Reverse() '让最深层错误在最左边
  1449. Return DescList.Join(" ← ")
  1450. End If
  1451. End Function
  1452. Private Function AnalyzeUsualReason(InnerEx As Exception, OuterEx As Exception, DescList As List(Of String)) As String
  1453. If TypeOf InnerEx Is TypeLoadException OrElse TypeOf InnerEx Is BadImageFormatException OrElse TypeOf InnerEx Is MissingMethodException OrElse TypeOf InnerEx Is NotImplementedException OrElse TypeOf InnerEx Is TypeInitializationException Then
  1454. Return "PCL 的运行环境存在问题。请尝试重新安装 .NET Framework 4.6.2 然后再试。若无法安装,请先卸载较新版本的 .NET Framework,然后再尝试安装。"
  1455. ElseIf TypeOf InnerEx Is UnauthorizedAccessException Then
  1456. Return "PCL 的权限不足。请尝试右键 PCL 选择以管理员身份运行。"
  1457. ElseIf TypeOf InnerEx Is OutOfMemoryException Then
  1458. Return "你的电脑运行内存不足,导致 PCL 无法继续运行。请在关闭一部分不需要的程序后再试。"
  1459. ElseIf TypeOf InnerEx Is Runtime.InteropServices.COMException Then
  1460. Return "由于操作系统或显卡存在问题,导致出现错误。请尝试重启 PCL。"
  1461. ElseIf TypeOf InnerEx Is SocketException AndAlso DescList.Any(Function(l) l.Contains("WSAStartup")) Then
  1462. Return "请尝试卸载中国移动云盘,然后再试。"
  1463. ElseIf OuterEx.IsNetworkRelated() Then
  1464. Return "你的网络环境不佳,请稍后再试,或使用 VPN 改善网络环境。"
  1465. Else
  1466. Return Nothing
  1467. End If
  1468. End Function
  1469. ''' <summary>
  1470. ''' 返回一个枚举对应的字符串。
  1471. ''' </summary>
  1472. ''' <param name="EnumData">一个已经实例化的枚举类型。</param>
  1473. Public Function GetStringFromEnum(EnumData As [Enum]) As String
  1474. Return [Enum].GetName(EnumData.GetType, EnumData)
  1475. End Function
  1476. ''' <summary>
  1477. ''' 将字符串转换为枚举类型,支持数字或原文两种格式,若为空字符串则返回 0。
  1478. ''' 若转换失败会抛出异常。
  1479. ''' </summary>
  1480. <Extension> Public Function ParseToEnum(Of T)(Str As String) As T
  1481. If String.IsNullOrEmpty(Str) Then
  1482. Return CType(0, Object)
  1483. ElseIf IsNumeric(Str) Then
  1484. Return CType(CInt(Str), Object)
  1485. Else
  1486. Return [Enum].Parse(GetType(T), Str, True)
  1487. End If
  1488. End Function
  1489. ''' <summary>
  1490. ''' 将文件大小转化为适合的文本形式,如“1.28 M”。
  1491. ''' </summary>
  1492. ''' <param name="FileSize">以字节为单位的大小表示。</param>
  1493. Public Function GetString(FileSize As Long) As String
  1494. Dim IsNegative = FileSize < 0
  1495. If IsNegative Then FileSize *= -1
  1496. If FileSize < 1000 Then
  1497. 'B 级
  1498. Return If(IsNegative, "-", "") & FileSize & " B"
  1499. ElseIf FileSize < 1024 * 1000 Then
  1500. 'K 级
  1501. Dim RoundResult As String = Math.Round(FileSize / 1024)
  1502. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " K"
  1503. ElseIf FileSize < 1024 * 1024 * 1000 Then
  1504. 'M 级
  1505. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024)
  1506. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024 / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " M"
  1507. Else
  1508. 'G 级
  1509. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024 / 1024)
  1510. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024 / 1024 / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " G"
  1511. End If
  1512. End Function
  1513. ''' <summary>
  1514. ''' 获取 JSON 对象。
  1515. ''' </summary>
  1516. Public Function GetJson(Data As String) As JToken
  1517. Try
  1518. Return JsonConvert.DeserializeObject(Data, New JsonSerializerSettings With {.DateTimeZoneHandling = DateTimeZoneHandling.Local})
  1519. Catch ex As Exception
  1520. Dim Length As Integer = If(Data, "").Length
  1521. Throw New Exception("格式化 JSON 失败:" & If(Length > 2000, Data.Substring(0, 500) & $"...(全长 {Length} 个字符)..." & Right(Data, 500), Data), ex)
  1522. End Try
  1523. End Function
  1524. ''' <summary>
  1525. ''' 将第一个字符转换为大写,其余字符转换为小写。
  1526. ''' </summary>
  1527. <Extension> Public Function Capitalize(word As String) As String
  1528. If String.IsNullOrEmpty(word) Then Return word
  1529. Return word.Substring(0, 1).Upper() & word.Substring(1).Lower()
  1530. End Function
  1531. ''' <summary>
  1532. ''' 将字符串统一至某个长度,过短则以 Code 将其右侧填充,过长则截取靠左的指定长度。
  1533. ''' </summary>
  1534. Public Function StrFill(Str As String, Code As String, Length As Byte) As String
  1535. If Str.Length > Length Then Return Mid(Str, 1, Length)
  1536. Return Mid(Str.PadRight(Length, Code), Str.Length + 1) & Str
  1537. End Function
  1538. ''' <summary>
  1539. ''' 移除字符串首尾的标点符号、回车,以及括号中、冒号后的补充说明内容。
  1540. ''' </summary>
  1541. Public Function StrTrim(Str As String, Optional RemoveQuote As Boolean = True)
  1542. If RemoveQuote Then Str = Str.Split("(")(0).Split(":")(0).Split("(")(0).Split(":")(0)
  1543. Return Str.Trim(".", "。", "!", " ", "!", "?", "?", vbCr, vbLf)
  1544. End Function
  1545. ''' <summary>
  1546. ''' 连接字符串。
  1547. ''' </summary>
  1548. <Extension> Public Function Join(List As IEnumerable, Split As Char) As String
  1549. Dim Builder As New StringBuilder
  1550. Dim IsFirst As Boolean = True
  1551. For Each Element In List
  1552. If IsFirst Then
  1553. IsFirst = False
  1554. Else
  1555. Builder.Append(Split)
  1556. End If
  1557. If Element IsNot Nothing Then Builder.Append(Element)
  1558. Next
  1559. Return Builder.ToString
  1560. End Function
  1561. ''' <summary>
  1562. ''' 连接字符串。
  1563. ''' </summary>
  1564. <Extension> Public Function Join(List As IEnumerable, Split As String) As String
  1565. If Split.IsSingle Then Return List.Join(Split(0))
  1566. Dim Builder As New StringBuilder
  1567. Dim IsFirst As Boolean = True
  1568. For Each Element In List
  1569. If IsFirst Then
  1570. IsFirst = False
  1571. Else
  1572. Builder.Append(Split)
  1573. End If
  1574. If Element IsNot Nothing Then Builder.Append(Element)
  1575. Next
  1576. Return Builder.ToString
  1577. End Function
  1578. ''' <summary>
  1579. ''' 分割字符串。
  1580. ''' 若原始字符串为空,则返回 {""}。
  1581. ''' </summary>
  1582. <Extension> Public Function Split(FullStr As String, SplitStr As String) As String()
  1583. If SplitStr.IsSingle Then
  1584. Return FullStr.Split(SplitStr(0))
  1585. Else
  1586. Return FullStr.Split({SplitStr}, StringSplitOptions.None)
  1587. End If
  1588. End Function
  1589. ''' <summary>
  1590. ''' 获取字符串哈希值。
  1591. ''' </summary>
  1592. Public Function GetHash(Str As String) As ULong
  1593. GetHash = 5381
  1594. For i = 0 To Str.Length - 1
  1595. GetHash = (GetHash << 5) Xor GetHash Xor CType(AscW(Str(i)), ULong)
  1596. Next
  1597. Return GetHash Xor &HA98F501BC684032FUL
  1598. End Function
  1599. ''' <summary>
  1600. ''' 获取字符串 MD5。
  1601. ''' </summary>
  1602. Public Function GetStringMD5(Str As String) As String
  1603. Using h = MD5Cng.Create()
  1604. Dim hashedDataBytes = h.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(Str))
  1605. Dim tmp As New StringBuilder(hashedDataBytes.Length * 2)
  1606. For Each i As Byte In hashedDataBytes
  1607. tmp.Append(i.ToString("x2"))
  1608. Next
  1609. Return tmp.ToString()
  1610. End Using
  1611. End Function
  1612. ''' <summary>
  1613. ''' 检查字符串中的字符是否均为 ASCII 字符。
  1614. ''' </summary>
  1615. <Extension> Public Function IsASCII(Input As String) As Boolean
  1616. Return Input.All(Function(c) AscW(c) < 128)
  1617. End Function
  1618. ''' <summary>
  1619. ''' 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。
  1620. ''' 如果未找到子字符串则不裁切。
  1621. ''' </summary>
  1622. <Extension> Public Function BeforeFirst(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1623. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.IndexOfF(Text, IgnoreCase))
  1624. If Pos >= 0 Then
  1625. Return Str.Substring(0, Pos)
  1626. Else
  1627. Return Str
  1628. End If
  1629. End Function
  1630. ''' <summary>
  1631. ''' 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。
  1632. ''' 如果未找到子字符串则不裁切。
  1633. ''' </summary>
  1634. <Extension> Public Function BeforeLast(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1635. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.LastIndexOfF(Text, IgnoreCase))
  1636. If Pos >= 0 Then
  1637. Return Str.Substring(0, Pos)
  1638. Else
  1639. Return Str
  1640. End If
  1641. End Function
  1642. ''' <summary>
  1643. ''' 获取在子字符串第一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 11/08。
  1644. ''' 如果未找到子字符串则不裁切。
  1645. ''' </summary>
  1646. <Extension> Public Function AfterFirst(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1647. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.IndexOfF(Text, IgnoreCase))
  1648. If Pos >= 0 Then
  1649. Return Str.Substring(Pos + Text.Length)
  1650. Else
  1651. Return Str
  1652. End If
  1653. End Function
  1654. ''' <summary>
  1655. ''' 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。
  1656. ''' 如果未找到子字符串则不裁切。
  1657. ''' </summary>
  1658. <Extension> Public Function AfterLast(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1659. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.LastIndexOfF(Text, IgnoreCase))
  1660. If Pos >= 0 Then
  1661. Return Str.Substring(Pos + Text.Length)
  1662. Else
  1663. Return Str
  1664. End If
  1665. End Function
  1666. ''' <summary>
  1667. ''' 获取处于两个子字符串之间的部分,裁切尽可能多的内容。
  1668. ''' 等效于 AfterLast 后接 BeforeFirst。
  1669. ''' 如果未找到子字符串则不裁切。
  1670. ''' </summary>
  1671. <Extension> Public Function Between(Str As String, After As String, Before As String, Optional IgnoreCase As Boolean = False) As String
  1672. Dim StartPos As Integer = If(String.IsNullOrEmpty(After), -1, Str.LastIndexOfF(After, IgnoreCase))
  1673. If StartPos >= 0 Then
  1674. StartPos += After.Length
  1675. Else
  1676. StartPos = 0
  1677. End If
  1678. Dim EndPos As Integer = If(String.IsNullOrEmpty(Before), -1, Str.IndexOfF(Before, StartPos, IgnoreCase))
  1679. If EndPos >= 0 Then
  1680. Return Str.Substring(StartPos, EndPos - StartPos)
  1681. ElseIf StartPos > 0 Then
  1682. Return Str.Substring(StartPos)
  1683. Else
  1684. Return Str
  1685. End If
  1686. End Function
  1687. ''' <summary>
  1688. ''' 高速的 StartsWith。
  1689. ''' </summary>
  1690. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1691. Public Function StartsWithF(Str As String, Prefix As String, Optional IgnoreCase As Boolean = False) As Boolean
  1692. If Str Is Nothing Then Return False
  1693. Return Str.StartsWith(Prefix, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1694. End Function
  1695. ''' <summary>
  1696. ''' 高速的 EndsWith。
  1697. ''' </summary>
  1698. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1699. Public Function EndsWithF(Str As String, Suffix As String, Optional IgnoreCase As Boolean = False) As Boolean
  1700. If Str Is Nothing Then Return False
  1701. Return Str.EndsWith(Suffix, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1702. End Function
  1703. ''' <summary>
  1704. ''' 支持可变大小写判断的 Contains。
  1705. ''' </summary>
  1706. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1707. Public Function ContainsF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Boolean
  1708. If Str Is Nothing Then Return False
  1709. Return Str.IndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal)) >= 0
  1710. End Function
  1711. ''' <summary>
  1712. ''' 高速的 IndexOf。
  1713. ''' </summary>
  1714. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1715. Public Function IndexOfF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Integer
  1716. Return Str.IndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1717. End Function
  1718. ''' <summary>
  1719. ''' 高速的 IndexOf。
  1720. ''' </summary>
  1721. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1722. Public Function IndexOfF(Str As String, SubStr As String, StartIndex As Integer, Optional IgnoreCase As Boolean = False) As Integer
  1723. Return Str.IndexOf(SubStr, StartIndex, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1724. End Function
  1725. ''' <summary>
  1726. ''' 高速的 LastIndexOf。
  1727. ''' </summary>
  1728. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1729. Public Function LastIndexOfF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Integer
  1730. Return Str.LastIndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1731. End Function
  1732. ''' <summary>
  1733. ''' 高速的 LastIndexOf。
  1734. ''' </summary>
  1735. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1736. Public Function LastIndexOfF(Str As String, SubStr As String, StartIndex As Integer, Optional IgnoreCase As Boolean = False) As Integer
  1737. Return Str.LastIndexOf(SubStr, StartIndex, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1738. End Function
  1739. ''' <summary>
  1740. ''' 不会报错的 Val。
  1741. ''' 如果输入有误,返回 0。
  1742. ''' </summary>
  1743. Public Function Val(Str As Object) As Double
  1744. If Str Is Nothing Then Return 0
  1745. Try
  1746. Return If(TypeOf Str Is String AndAlso Str = "&", 0, Conversion.Val(Str))
  1747. Catch
  1748. Return 0
  1749. End Try
  1750. End Function
  1751. ''' <summary>
  1752. ''' 等效 ToLowerInvariant。
  1753. ''' </summary>
  1754. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)> Public Function Lower(Str As String) As String
  1755. Return Str.ToLowerInvariant()
  1756. End Function
  1757. ''' <summary>
  1758. ''' 等效 ToUpperInvariant。
  1759. ''' </summary>
  1760. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)> Public Function Upper(Str As String) As String
  1761. Return Str.ToUpperInvariant()
  1762. End Function
  1763. '转义
  1764. ''' <summary>
  1765. ''' 为字符串进行 XML 转义。
  1766. ''' </summary>
  1767. Public Function EscapeXML(Str As String) As String
  1768. If Str.StartsWithF("{") Then Str = "{}" & Str '#4187
  1769. Return Str.
  1770. Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;").
  1771. Replace("""", "&quot;").Replace(vbCrLf, "&#xa;")
  1772. End Function
  1773. ''' <summary>
  1774. ''' 为字符串进行 Like 关键字转义。
  1775. ''' </summary>
  1776. Public Function EscapeLikePattern(input As String) As String
  1777. Dim sb As New StringBuilder()
  1778. For Each c As Char In input
  1779. Select Case c
  1780. Case "["c, "]"c, "*"c, "?"c, "#"c
  1781. sb.Append("["c).Append(c).Append("]"c)
  1782. Case Else
  1783. sb.Append(c)
  1784. End Select
  1785. Next
  1786. Return sb.ToString()
  1787. End Function
  1788. '正则
  1789. ''' <summary>
  1790. ''' 搜索字符串中的所有正则匹配项。
  1791. ''' </summary>
  1792. <Extension> Public Function RegexSearch(str As String, regex As String, Optional options As RegexOptions = RegexOptions.None) As List(Of String)
  1793. Try
  1794. RegexSearch = New List(Of String)
  1795. Dim RegexSearchRes = New Regex(regex, options).Matches(str)
  1796. If RegexSearchRes Is Nothing Then Return RegexSearch
  1797. For Each item As Match In RegexSearchRes
  1798. RegexSearch.Add(item.Value)
  1799. Next
  1800. Catch ex As Exception
  1801. Log(ex, "正则匹配全部项出错")
  1802. Return New List(Of String)
  1803. End Try
  1804. End Function
  1805. ''' <summary>
  1806. ''' 获取字符串中的第一个正则匹配项,若无匹配则返回 Nothing。
  1807. ''' </summary>
  1808. <Extension> Public Function RegexSeek(str As String, regex As String, Optional options As RegexOptions = RegexOptions.None) As String
  1809. Try
  1810. Dim Result = RegularExpressions.Regex.Match(str, regex, options).Value
  1811. Return If(Result = "", Nothing, Result)
  1812. Catch ex As Exception
  1813. Log(ex, "正则匹配第一项出错")
  1814. Return Nothing
  1815. End Try
  1816. End Function
  1817. ''' <summary>
  1818. ''' 检查字符串是否匹配某正则模式。
  1819. ''' </summary>
  1820. <Extension> Public Function RegexCheck(str As String, regex As String, Optional options As RegexOptions = RegexOptions.None) As Boolean
  1821. Try
  1822. Return RegularExpressions.Regex.IsMatch(str, regex, options)
  1823. Catch ex As Exception
  1824. Log(ex, "正则检查出错")
  1825. Return False
  1826. End Try
  1827. End Function
  1828. ''' <summary>
  1829. ''' 进行正则替换,会抛出错误。
  1830. ''' </summary>
  1831. <Extension> Public Function RegexReplace(AllContents As String, SearchRegex As String, ReplaceTo As String, Optional options As RegexOptions = RegexOptions.None) As String
  1832. Return Regex.Replace(AllContents, SearchRegex, ReplaceTo, options)
  1833. End Function
  1834. ''' <summary>
  1835. ''' 对每个正则匹配分别进行替换,会抛出错误。
  1836. ''' </summary>
  1837. <Extension> Public Function RegexReplaceEach(AllContents As String, SearchRegex As String, ReplaceTo As MatchEvaluator, Optional options As RegexOptions = RegexOptions.None) As String
  1838. Return Regex.Replace(AllContents, SearchRegex, ReplaceTo, options)
  1839. End Function
  1840. #End Region
  1841. #Region "搜索"
  1842. ''' <summary>
  1843. ''' 获取搜索文本的相似度。
  1844. ''' </summary>
  1845. ''' <param name="Source">被搜索的长内容。</param>
  1846. ''' <param name="Query">用户输入的搜索文本。</param>
  1847. Private Function SearchSimilarity(Source As String, Query As String) As Double
  1848. If String.IsNullOrEmpty(Source) OrElse String.IsNullOrEmpty(Query) Then Return 0
  1849. Dim qp As Integer = 0, lenSum As Double = 0
  1850. Dim str As New StringBuilder(Source.Length)
  1851. str.Append(Source.Lower().Replace(" ", ""))
  1852. Query = Query.Lower().Replace(" ", "")
  1853. Dim sourceLength As Integer = str.Length, queryLength As Integer = Query.Length '用于计算最后因数的长度缓存
  1854. If queryLength = 0 Then Return 0
  1855. Do While qp < queryLength
  1856. '对 qp 作为开始位置计算
  1857. Dim sp As Integer = 0, lenMax As Integer = 0, spMax As Integer = 0
  1858. Dim currentSourceLength As Integer = str.Length
  1859. Do While sp < currentSourceLength
  1860. Dim len As Integer = 0
  1861. While (qp + len) < queryLength AndAlso (sp + len) < currentSourceLength AndAlso str(sp + len) = Query(qp + len)
  1862. len += 1
  1863. End While
  1864. '存储 len
  1865. If len > lenMax Then
  1866. lenMax = len
  1867. spMax = sp
  1868. End If
  1869. '根据结果增加 sp
  1870. sp += If(len > 0, len, 1)
  1871. Loop
  1872. If lenMax > 0 Then
  1873. str.Remove(spMax, lenMax) '将源中的对应字段移除
  1874. '存储 lenSum
  1875. Dim IncWeight = (Math.Pow(1.4, 3 + lenMax) - 3.6) '根据长度加成
  1876. IncWeight *= 1 + 0.3 * Math.Max(0, 3 - Math.Abs(qp - spMax)) '根据位置加成
  1877. lenSum += IncWeight
  1878. End If
  1879. qp += If(lenMax > 0, lenMax, 1)
  1880. Loop
  1881. '计算结果:重复字段量 × 源长度影响比例
  1882. Return (lenSum / queryLength) * (3 / Math.Sqrt(sourceLength + 15)) * If(queryLength <= 2, 3 - queryLength, 1)
  1883. End Function
  1884. ''' <summary>
  1885. ''' 获取多段文本加权后的相似度。
  1886. ''' </summary>
  1887. Private Function SearchSimilarityWeighted(Source As List(Of SearchSource), Query As String) As Double
  1888. Dim TotalWeight As Double = 0
  1889. Dim Sum As Double = 0
  1890. For Each Pair In Source
  1891. If Pair.Aliases.Any Then
  1892. Sum += Pair.Aliases.Max(Function(a) SearchSimilarity(a, Query)) * Pair.Weight
  1893. End If
  1894. TotalWeight += Pair.Weight
  1895. Next
  1896. Return Sum / TotalWeight
  1897. End Function
  1898. ''' <summary>
  1899. ''' 用于搜索的项目。
  1900. ''' </summary>
  1901. Public Class SearchEntry(Of T)
  1902. ''' <summary>
  1903. ''' 该项目对应的源数据。
  1904. ''' </summary>
  1905. Public Item As T
  1906. ''' <summary>
  1907. ''' 该项目用于搜索的文本源。
  1908. ''' 在搜索时,会对每个文本源单独加权,但单个文本源内的多个别名只取最高的一个的相似度。
  1909. ''' </summary>
  1910. Public SearchSource As List(Of SearchSource)
  1911. ''' <summary>
  1912. ''' 相似度。
  1913. ''' </summary>
  1914. Public Similarity As Double
  1915. ''' <summary>
  1916. ''' 是否完全匹配。
  1917. ''' </summary>
  1918. Public AbsoluteRight As Boolean
  1919. Public Overrides Function ToString() As String
  1920. Return Math.Round(Similarity, 3) & " - " & Item.ToString()
  1921. End Function
  1922. End Class
  1923. ''' <summary>
  1924. ''' 单个用于搜索的文本源。
  1925. ''' </summary>
  1926. Public Class SearchSource
  1927. Public Aliases As String()
  1928. Public Weight As Double
  1929. Public Sub New(Aliases As String(), Optional Weight As Double = 1)
  1930. Me.Aliases = Aliases
  1931. Me.Weight = Weight
  1932. End Sub
  1933. Public Sub New(Text As String, Optional Weight As Double = 1)
  1934. Me.Aliases = {Text}
  1935. Me.Weight = Weight
  1936. End Sub
  1937. End Class
  1938. ''' <summary>
  1939. ''' 进行多段文本加权搜索,获取相似度较高的数项结果。
  1940. ''' 在搜索时,会对每个文本源单独加权,但单个文本源内的多个别名只取最高的一个的相似度。
  1941. ''' 这会修改 Entries 中每项的 Similarity 与 AbsoluteRight 字段。
  1942. ''' </summary>
  1943. ''' <param name="MaxBlurCount">返回的最大模糊结果数。</param>
  1944. ''' <param name="MinBlurSimilarity">返回结果要求的最低相似度。</param>
  1945. Public Function Search(Of T)(Entries As List(Of SearchEntry(Of T)), Query As String, Optional MaxBlurCount As Integer = 5, Optional MinBlurSimilarity As Double = 0.1) As List(Of SearchEntry(Of T))
  1946. '初始化
  1947. Dim ResultList As New List(Of SearchEntry(Of T))
  1948. If Not Entries.Any() Then Return ResultList
  1949. '进行搜索,获取相似信息
  1950. Dim QueryParts = Query.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
  1951. Dim Candidates As New List(Of SearchEntry(Of T))
  1952. For Each Entry In Entries
  1953. Entry.Similarity = SearchSimilarityWeighted(Entry.SearchSource, Query)
  1954. Entry.AbsoluteRight =
  1955. QueryParts.All( '对于按空格分割的每一段
  1956. Function(QueryPart) Entry.SearchSource.Any( '若与任意一个搜索源完全匹配,则标记为完全匹配项
  1957. Function(Source) Source.Aliases.Any(
  1958. Function([Alias]) [Alias].Replace(" ", "").ContainsF(QueryPart, True))))
  1959. If Entry.AbsoluteRight OrElse Entry.Similarity >= MinBlurSimilarity Then Candidates.Add(Entry)
  1960. Next
  1961. '按照相似度进行排序
  1962. Candidates = Candidates.SortByComparison(Function(Left, Right) If(Left.AbsoluteRight <> Right.AbsoluteRight, Left.AbsoluteRight, Left.Similarity > Right.Similarity))
  1963. '返回结果
  1964. Dim BlurCount As Integer = 0
  1965. For Each Entry In Candidates
  1966. If Entry.AbsoluteRight Then
  1967. ResultList.Add(Entry) '完全匹配,直接加入
  1968. Else
  1969. If BlurCount = MaxBlurCount Then Exit For
  1970. ResultList.Add(Entry)
  1971. BlurCount += 1 '模糊结果计数
  1972. End If
  1973. Next
  1974. Return ResultList
  1975. End Function
  1976. #End Region
  1977. #Region "系统"
  1978. ''' <summary>
  1979. ''' 线程安全的 List。
  1980. ''' 通过在 For Each 循环中使用一个浅表副本规避多线程操作或移除自身导致的异常。
  1981. ''' </summary>
  1982. Public Class SafeList(Of T)
  1983. Inherits SynchronizedCollection(Of T)
  1984. Implements IEnumerable, IEnumerable(Of T)
  1985. '构造函数
  1986. Public Sub New()
  1987. MyBase.New()
  1988. End Sub
  1989. Public Sub New(Data As IEnumerable(Of T))
  1990. MyBase.New(New Object, Data)
  1991. End Sub
  1992. Public Shared Widening Operator CType(Data As List(Of T)) As SafeList(Of T)
  1993. Return New SafeList(Of T)(Data)
  1994. End Operator
  1995. Public Shared Widening Operator CType(Data As SafeList(Of T)) As List(Of T)
  1996. Return New List(Of T)(Data)
  1997. End Operator
  1998. '基于 SyncLock 覆写
  1999. Public Overloads Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
  2000. SyncLock SyncRoot
  2001. Return Items.ToList.GetEnumerator()
  2002. End SyncLock
  2003. End Function
  2004. Private Overloads Function GetEnumeratorGeneral() As IEnumerator Implements IEnumerable.GetEnumerator
  2005. SyncLock SyncRoot
  2006. Return Items.ToList.GetEnumerator()
  2007. End SyncLock
  2008. End Function
  2009. End Class
  2010. ''' <summary>
  2011. ''' 线程安全的字典。
  2012. ''' 通过在 For Each 循环中使用一个浅表副本规避多线程操作或移除自身导致的异常。
  2013. ''' </summary>
  2014. Public Class SafeDictionary(Of TKey, TValue)
  2015. Implements IDictionary(Of TKey, TValue)
  2016. Implements IEnumerable(Of KeyValuePair(Of TKey, TValue))
  2017. Public ReadOnly SyncRoot As New Object
  2018. Private ReadOnly _Dictionary As New Dictionary(Of TKey, TValue)
  2019. '构造函数
  2020. Public Sub New()
  2021. End Sub
  2022. Public Sub New(Data As IEnumerable(Of KeyValuePair(Of TKey, TValue)))
  2023. For Each DataItem In Data
  2024. _Dictionary.Add(DataItem.Key, DataItem.Value)
  2025. Next
  2026. End Sub
  2027. '线程安全的方法实现
  2028. Public Sub Add(key As TKey, value As TValue) Implements IDictionary(Of TKey, TValue).Add
  2029. SyncLock SyncRoot
  2030. _Dictionary.Add(key, value)
  2031. End SyncLock
  2032. End Sub
  2033. Public Function ContainsKey(key As TKey) As Boolean Implements IDictionary(Of TKey, TValue).ContainsKey
  2034. SyncLock SyncRoot
  2035. Return _Dictionary.ContainsKey(key)
  2036. End SyncLock
  2037. End Function
  2038. Public ReadOnly Property Keys As ICollection(Of TKey) Implements IDictionary(Of TKey, TValue).Keys
  2039. Get
  2040. SyncLock SyncRoot
  2041. Return New List(Of TKey)(_Dictionary.Keys)
  2042. End SyncLock
  2043. End Get
  2044. End Property
  2045. Public Function Remove(key As TKey) As Boolean Implements IDictionary(Of TKey, TValue).Remove
  2046. SyncLock SyncRoot
  2047. Return _Dictionary.Remove(key)
  2048. End SyncLock
  2049. End Function
  2050. Public Function TryGetValue(key As TKey, ByRef value As TValue) As Boolean Implements IDictionary(Of TKey, TValue).TryGetValue
  2051. SyncLock SyncRoot
  2052. Return _Dictionary.TryGetValue(key, value)
  2053. End SyncLock
  2054. End Function
  2055. Public ReadOnly Property Values As ICollection(Of TValue) Implements IDictionary(Of TKey, TValue).Values
  2056. Get
  2057. SyncLock SyncRoot
  2058. Return New List(Of TValue)(_Dictionary.Values)
  2059. End SyncLock
  2060. End Get
  2061. End Property
  2062. Default Public Property Item(key As TKey) As TValue Implements IDictionary(Of TKey, TValue).Item
  2063. Get
  2064. SyncLock SyncRoot
  2065. Return _Dictionary(key)
  2066. End SyncLock
  2067. End Get
  2068. Set(value As TValue)
  2069. SyncLock SyncRoot
  2070. _Dictionary(key) = value
  2071. End SyncLock
  2072. End Set
  2073. End Property
  2074. Public Sub Add(item As KeyValuePair(Of TKey, TValue)) Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Add
  2075. SyncLock SyncRoot
  2076. _Dictionary.Add(item.Key, item.Value)
  2077. End SyncLock
  2078. End Sub
  2079. Public Sub Clear() Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Clear
  2080. SyncLock SyncRoot
  2081. _Dictionary.Clear()
  2082. End SyncLock
  2083. End Sub
  2084. Public Function Contains(item As KeyValuePair(Of TKey, TValue)) As Boolean Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Contains
  2085. SyncLock SyncRoot
  2086. Return DirectCast(_Dictionary, IDictionary(Of TKey, TValue)).Contains(item)
  2087. End SyncLock
  2088. End Function
  2089. Public Sub CopyTo(array() As KeyValuePair(Of TKey, TValue), arrayIndex As Integer) Implements ICollection(Of KeyValuePair(Of TKey, TValue)).CopyTo
  2090. SyncLock SyncRoot
  2091. DirectCast(_Dictionary, IDictionary(Of TKey, TValue)).CopyTo(array, arrayIndex)
  2092. End SyncLock
  2093. End Sub
  2094. Public ReadOnly Property Count As Integer Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Count
  2095. Get
  2096. SyncLock SyncRoot
  2097. Return _Dictionary.Count
  2098. End SyncLock
  2099. End Get
  2100. End Property
  2101. Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of KeyValuePair(Of TKey, TValue)).IsReadOnly
  2102. Get
  2103. Return False
  2104. End Get
  2105. End Property
  2106. Public Function Remove(item As KeyValuePair(Of TKey, TValue)) As Boolean Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Remove
  2107. SyncLock SyncRoot
  2108. Return DirectCast(_Dictionary, IDictionary(Of TKey, TValue)).Remove(item)
  2109. End SyncLock
  2110. End Function
  2111. '枚举器
  2112. Public Function GetEnumerator() As IEnumerator(Of KeyValuePair(Of TKey, TValue)) Implements IEnumerable(Of KeyValuePair(Of TKey, TValue)).GetEnumerator
  2113. SyncLock SyncRoot
  2114. Return New List(Of KeyValuePair(Of TKey, TValue))(_Dictionary).GetEnumerator()
  2115. End SyncLock
  2116. End Function
  2117. Private Function GetEnumeratorGeneral() As IEnumerator Implements IEnumerable.GetEnumerator
  2118. Return GetEnumerator()
  2119. End Function
  2120. End Class
  2121. ''' <summary>
  2122. ''' 将二维数组转换为字典。
  2123. ''' </summary>
  2124. <Extension> Public Function ToDictionary(Of T)(arr As T(,)) As Dictionary(Of T, T)
  2125. Dim result As New Dictionary(Of T, T)
  2126. If arr.Length = 0 Then Return result
  2127. If arr.GetLength(1) <> 2 Then Throw New ArgumentException("数组必须为两列,第一列为 Key,第二列为 Value。")
  2128. For i As Integer = 0 To arr.GetLength(0) - 1
  2129. result(arr(i, 0)) = arr(i, 1)
  2130. Next
  2131. Return result
  2132. End Function
  2133. ''' <summary>
  2134. ''' 为 Task 设置超时,在超时时抛出 TimeoutException。
  2135. ''' </summary>
  2136. <Extension> Public Function GetResultWithTimeout(Of T)(TargetTask As Task(Of T), TokenSource As CancellationTokenSource, TimeoutMs As Integer) As T
  2137. Dim DelayTask = Task.Delay(TimeoutMs)
  2138. If Task.WhenAny(TargetTask, DelayTask).ConfigureAwait(False).GetAwaiter().GetResult() Is DelayTask Then
  2139. TokenSource.Cancel()
  2140. Throw New TimeoutException($"任务超时({TimeoutMs} ms)")
  2141. End If
  2142. Return TargetTask.GetAwaiter().GetResult()
  2143. End Function
  2144. ''' <summary>
  2145. ''' 为 Task 设置超时,在超时时抛出 TimeoutException。
  2146. ''' </summary>
  2147. <Extension> Public Sub GetResultWithTimeout(TargetTask As Task, TokenSource As CancellationTokenSource, TimeoutMs As Integer)
  2148. Dim DelayTask = Task.Delay(TimeoutMs)
  2149. If Task.WhenAny(TargetTask, DelayTask).ConfigureAwait(False).GetAwaiter().GetResult() Is DelayTask Then
  2150. TokenSource.Cancel()
  2151. Throw New TimeoutException($"任务超时({TimeoutMs} ms)")
  2152. End If
  2153. TargetTask.GetAwaiter().GetResult()
  2154. End Sub
  2155. ''' <summary>
  2156. ''' 可用于临时存放文件的,不含任何特殊字符的文件夹路径,以“\”结尾。
  2157. ''' </summary>
  2158. Public PathPure As String = GetPureASCIIDir()
  2159. Private Function GetPureASCIIDir() As String
  2160. If (Path & "PCL").IsASCII() Then
  2161. Return Path & "PCL\"
  2162. ElseIf PathAppdata.IsASCII() Then
  2163. Return PathAppdata
  2164. ElseIf PathTemp.IsASCII() Then
  2165. Return PathTemp
  2166. Else
  2167. Return OsDrive & "ProgramData\PCL\"
  2168. End If
  2169. End Function
  2170. ''' <summary>
  2171. ''' 指示接取到这个异常的函数进行重试。
  2172. ''' </summary>
  2173. Public Class RestartException
  2174. Inherits Exception
  2175. End Class
  2176. ''' <summary>
  2177. ''' 指示用户手动取消了操作,或用户已知晓操作被取消的原因。
  2178. ''' </summary>
  2179. Public Class CancelledException
  2180. Inherits Exception
  2181. End Class
  2182. ''' <summary>
  2183. ''' 当前程序是否拥有管理员权限。
  2184. ''' </summary>
  2185. Public Function IsAdmin() As Boolean
  2186. Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
  2187. Dim principal As New WindowsPrincipal(id)
  2188. Return principal.IsInRole(WindowsBuiltInRole.Administrator)
  2189. End Function
  2190. ''' <summary>
  2191. ''' 以管理员权限运行当前程序,并等待程序运行结束。
  2192. ''' 返回程序的返回代码,如果运行失败将抛出异常。
  2193. ''' </summary>
  2194. Public Function RunAsAdmin(Argument As String) As Integer
  2195. Dim NewProcess = StartProcess(New ProcessStartInfo(PathWithName) With {.Verb = "runas", .Arguments = Argument})
  2196. NewProcess.WaitForExit()
  2197. Return NewProcess.ExitCode
  2198. End Function
  2199. ''' <summary>
  2200. ''' 判断当前系统语言是否为中文。
  2201. ''' </summary>
  2202. Public Function IsSystemLanguageChinese() As Boolean
  2203. Return CultureInfo.CurrentCulture.Name.StartsWithF("zh-") OrElse CultureInfo.CurrentUICulture.Name.StartsWithF("zh-")
  2204. End Function
  2205. ''' <summary>
  2206. ''' 判断对象是否为某个泛型类型的实例。
  2207. ''' </summary>
  2208. <Extension> Public Function IsInstanceOfGenericType(genericType As Type, obj As Object) As Boolean
  2209. If obj Is Nothing Then Return False
  2210. Dim t = obj.GetType()
  2211. While t IsNot Nothing
  2212. If t.IsGenericType AndAlso t.GetGenericTypeDefinition() Is genericType Then Return True
  2213. t = t.BaseType
  2214. End While
  2215. Return False
  2216. End Function
  2217. Private Uuid As Integer = 1
  2218. Private UuidLock As Object
  2219. ''' <summary>
  2220. ''' 获取一个全程序内不会重复的数字(伪 Uuid)。
  2221. ''' </summary>
  2222. Public Function GetUuid() As Integer
  2223. If UuidLock Is Nothing Then UuidLock = New Object
  2224. SyncLock UuidLock
  2225. Uuid += 1
  2226. Return Uuid
  2227. End SyncLock
  2228. End Function
  2229. ''' <summary>
  2230. ''' 将元素与 List 的混合体拆分为元素组。
  2231. ''' </summary>
  2232. Public Function GetFullList(Of T)(data As IList) As List(Of T)
  2233. GetFullList = New List(Of T)
  2234. For i = 0 To data.Count - 1
  2235. If TypeOf data(i) Is ICollection Then
  2236. GetFullList.AddRange(data(i))
  2237. Else
  2238. GetFullList.Add(data(i))
  2239. End If
  2240. Next i
  2241. End Function
  2242. ''' <summary>
  2243. ''' 去重。
  2244. ''' </summary>
  2245. <Extension> Public Function Distinct(Of T)(Arr As ICollection(Of T), IsEqual As ComparisonBoolean(Of T)) As List(Of T)
  2246. Dim ResultArray As New List(Of T)
  2247. For i = 0 To Arr.Count - 1
  2248. For ii = i + 1 To Arr.Count - 1
  2249. If IsEqual(Arr(i), Arr(ii)) Then GoTo NextElement
  2250. Next
  2251. ResultArray.Add(Arr(i))
  2252. NextElement:
  2253. Next i
  2254. Return ResultArray
  2255. End Function
  2256. <Extension> Public Function Any(Arr As UIElementCollection) As Boolean
  2257. Return Arr?.Count > 0
  2258. End Function
  2259. ''' <summary>
  2260. ''' 判断这是否是仅有一个元素的集合。
  2261. ''' </summary>
  2262. <Extension> Public Function IsSingle(Of T)(Source As IEnumerable(Of T)) As Boolean
  2263. If Source Is Nothing Then
  2264. Return False
  2265. ElseIf TypeOf Source Is IList(Of T) Then
  2266. Return DirectCast(Source, IList(Of T)).Count = 1
  2267. Else
  2268. Using Enumerator = Source.GetEnumerator()
  2269. If Not Enumerator.MoveNext() Then Return False
  2270. If Enumerator.MoveNext() Then Return False
  2271. Return True
  2272. End Using
  2273. End If
  2274. End Function
  2275. ''' <summary>
  2276. ''' 对集合的每个元素执行指定操作。
  2277. ''' </summary>
  2278. <Extension> Public Function ForEach(Of T)(Collection As IEnumerable(Of T), Action As Action(Of T)) As IEnumerable(Of T)
  2279. For Each Item As T In Collection
  2280. Action(Item)
  2281. Next
  2282. Return Collection
  2283. End Function
  2284. ''' <summary>
  2285. ''' 获取格式类似于“11:08:52.037”的当前时间的字符串。
  2286. ''' </summary>
  2287. Public Function GetTimeNow() As String
  2288. Return Date.Now.ToString("HH':'mm':'ss'.'fff")
  2289. End Function
  2290. ''' <summary>
  2291. ''' 获取一个单调递增时间值(毫秒)。
  2292. ''' </summary>
  2293. Public Function GetTimeMs() As Long
  2294. Return Stopwatch.GetTimestamp() \ (Stopwatch.Frequency \ 1000L)
  2295. End Function
  2296. ''' <summary>
  2297. ''' 将时间间隔转换为类似“5 分 10 秒前”的易于阅读的形式。
  2298. ''' </summary>
  2299. Public Function GetTimeSpanString(Span As TimeSpan, IsShortForm As Boolean) As String
  2300. Dim EndFix = If(Span.TotalMilliseconds > 0, "后", "前")
  2301. If Span.TotalMilliseconds < 0 Then Span = -Span
  2302. Dim TotalMonthes = Math.Floor(Span.Days / 30)
  2303. If IsShortForm Then
  2304. If TotalMonthes >= 12 Then
  2305. '1+ 年,“3 年”
  2306. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  2307. ElseIf TotalMonthes >= 2 Then
  2308. '2~11 月,“5 个月”
  2309. GetTimeSpanString = TotalMonthes & " 个月"
  2310. ElseIf Span.TotalDays >= 2 Then
  2311. '2 天 ~ 2 月,“23 天”
  2312. GetTimeSpanString = Span.Days & " 天"
  2313. ElseIf Span.TotalHours >= 1 Then
  2314. '1 小时 ~ 2 天,“15 小时”
  2315. GetTimeSpanString = Span.Hours & " 小时"
  2316. ElseIf Span.TotalMinutes >= 1 Then
  2317. '1 分钟 ~ 1 小时,“49 分钟”
  2318. GetTimeSpanString = Span.Minutes & " 分钟"
  2319. ElseIf Span.TotalSeconds >= 1 Then
  2320. '1 秒 ~ 1 分钟,“23 秒”
  2321. GetTimeSpanString = Span.Seconds & " 秒"
  2322. Else
  2323. '不到 1 秒
  2324. GetTimeSpanString = "1 秒"
  2325. End If
  2326. Else
  2327. If TotalMonthes >= 61 Then
  2328. '5+ 年,“5 年”
  2329. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  2330. ElseIf TotalMonthes >= 12 Then
  2331. '12~60 月,“1 年 2 个月”
  2332. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年" & If((TotalMonthes Mod 12) > 0, " " & (TotalMonthes Mod 12) & " 个月", "")
  2333. ElseIf TotalMonthes >= 4 Then
  2334. '4~11 月,“5 个月”
  2335. GetTimeSpanString = TotalMonthes & " 个月"
  2336. ElseIf TotalMonthes >= 1 Then
  2337. '1~4 月,“2 个月 13 天”
  2338. GetTimeSpanString = TotalMonthes & " 月" & If((Span.Days Mod 30) > 0, " " & (Span.Days Mod 30) & " 天", "")
  2339. ElseIf Span.TotalDays >= 4 Then
  2340. '4~30 天,“23 天”
  2341. GetTimeSpanString = Span.Days & " 天"
  2342. ElseIf Span.TotalDays >= 1 Then
  2343. '1~3 天,“2 天 20 小时”
  2344. GetTimeSpanString = Span.Days & " 天" & If(Span.Hours > 0, " " & Span.Hours & " 小时", "")
  2345. ElseIf Span.TotalHours >= 10 Then
  2346. '10 小时 ~ 1 天,“15 小时”
  2347. GetTimeSpanString = Span.Hours & " 小时"
  2348. ElseIf Span.TotalHours >= 1 Then
  2349. '1~10 小时,“1 小时 20 分钟”
  2350. GetTimeSpanString = Span.Hours & " 小时" & If(Span.Minutes > 0, " " & Span.Minutes & " 分钟", "")
  2351. ElseIf Span.TotalMinutes >= 10 Then
  2352. '10 分钟 ~ 1 小时,“49 分钟”
  2353. GetTimeSpanString = Span.Minutes & " 分钟"
  2354. ElseIf Span.TotalMinutes >= 1 Then
  2355. '1~10 分钟,“9 分 23 秒”
  2356. GetTimeSpanString = Span.Minutes & " 分" & If(Span.Seconds > 0, " " & Span.Seconds & " 秒", "")
  2357. ElseIf Span.TotalSeconds >= 1 Then
  2358. '1 秒 ~ 1 分钟,“23 秒”
  2359. GetTimeSpanString = Span.Seconds & " 秒"
  2360. Else
  2361. '不到 1 秒
  2362. GetTimeSpanString = "1 秒"
  2363. End If
  2364. End If
  2365. GetTimeSpanString += EndFix
  2366. End Function
  2367. ''' <summary>
  2368. ''' 获取十进制 Unix 时间戳。
  2369. ''' </summary>
  2370. Public Function GetUnixTimestamp() As Long
  2371. Return (Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000
  2372. End Function
  2373. ''' <summary>
  2374. ''' 用于储存 RaiseByMouse 的 EventArgs。
  2375. ''' </summary>
  2376. Public NotInheritable Class RouteEventArgs
  2377. Inherits EventArgs
  2378. Public RaiseByMouse As Boolean
  2379. Public Handled As Boolean = False
  2380. Public Sub New(Optional RaiseByMouse As Boolean = False)
  2381. Me.RaiseByMouse = RaiseByMouse
  2382. End Sub
  2383. End Class
  2384. ''' <summary>
  2385. ''' 启动进程并返回进程实例,若失败则抛出异常。
  2386. ''' 会自动进行长路径处理。
  2387. ''' </summary>
  2388. Public Function StartProcess(FileName As String, Optional Arguments As String = "") As Process
  2389. Return StartProcess(New ProcessStartInfo With {.FileName = FileName, .Arguments = Arguments})
  2390. End Function
  2391. ''' <summary>
  2392. ''' 启动进程并返回进程实例,若失败则抛出异常。
  2393. ''' 会自动进行长路径处理。
  2394. ''' </summary>
  2395. Public Function StartProcess(StartInfo As ProcessStartInfo) As Process
  2396. StartInfo.FileName = ShortenPath(StartInfo.FileName)
  2397. If Not String.IsNullOrEmpty(StartInfo.WorkingDirectory) Then StartInfo.WorkingDirectory = ShortenPath(StartInfo.WorkingDirectory)
  2398. Log("[System] 启动进程:" & StartInfo.FileName & " " & StartInfo.Arguments)
  2399. Return Process.Start(StartInfo)
  2400. End Function
  2401. ''' <summary>
  2402. ''' 静默运行文件并返回输出流字符串。执行失败会抛出异常。
  2403. ''' </summary>
  2404. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  2405. ''' <param name="Arguments">运行参数。</param>
  2406. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会抛出错误。</param>
  2407. Public Function StartProcessAndGetOutput(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000,
  2408. Optional WorkingDirectory As String = Nothing, Optional Encoding As Encoding = Nothing, Optional PrintLog As Boolean = True) As String
  2409. Dim Info = New ProcessStartInfo With {
  2410. .Arguments = Arguments,
  2411. .FileName = ShortenPath(FileName),
  2412. .UseShellExecute = False,
  2413. .CreateNoWindow = True,
  2414. .RedirectStandardError = True,
  2415. .RedirectStandardOutput = True,
  2416. .WorkingDirectory = ShortenPath(If(WorkingDirectory, Path.TrimEnd("\"c))),
  2417. .StandardErrorEncoding = Encoding,
  2418. .StandardOutputEncoding = Encoding
  2419. }
  2420. If WorkingDirectory IsNot Nothing Then
  2421. If Info.EnvironmentVariables.ContainsKey("appdata") Then
  2422. Info.EnvironmentVariables("appdata") = WorkingDirectory
  2423. Else
  2424. Info.EnvironmentVariables.Add("appdata", WorkingDirectory)
  2425. End If
  2426. End If
  2427. If PrintLog Then Log("[System] 执行命令并等待返回结果:" & FileName & " " & Arguments)
  2428. Using Program As New Process With {.StartInfo = Info}
  2429. Program.Start()
  2430. Dim Result As String = Program.StandardOutput.ReadToEnd & Program.StandardError.ReadToEnd
  2431. Program.WaitForExit(Timeout)
  2432. If Not Program.HasExited Then Program.Kill()
  2433. Return Result
  2434. End Using
  2435. End Function
  2436. ''' <summary>
  2437. ''' 在新的工作线程中执行代码。
  2438. ''' </summary>
  2439. Public Function RunInNewThread(Action As Action, Optional Name As String = Nothing, Optional Priority As ThreadPriority = ThreadPriority.Normal) As Thread
  2440. Dim th As New Thread(
  2441. Sub()
  2442. Try
  2443. Action()
  2444. Catch ex As ThreadInterruptedException
  2445. Log(Name & ":线程已中止")
  2446. Catch ex As Exception
  2447. Log(ex, Name & ":线程执行失败", LogLevel.Feedback)
  2448. End Try
  2449. End Sub) With {.Name = If(Name, "Runtime New Invoke " & GetUuid() & "#"), .Priority = Priority}
  2450. th.Start()
  2451. Return th
  2452. End Function
  2453. ''' <summary>
  2454. ''' 确保在 UI 线程中执行代码。
  2455. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  2456. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  2457. ''' </summary>
  2458. Public Function RunInUiWait(Of Output)(Action As Func(Of Output)) As Output
  2459. If RunInUi() Then
  2460. Return Action()
  2461. Else
  2462. Return Application.Current.Dispatcher.Invoke(Action)
  2463. End If
  2464. End Function
  2465. ''' <summary>
  2466. ''' 确保在 UI 线程中执行代码。
  2467. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  2468. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  2469. ''' </summary>
  2470. Public Sub RunInUiWait(Action As Action)
  2471. If RunInUi() Then
  2472. Action()
  2473. Else
  2474. Application.Current.Dispatcher.Invoke(Action)
  2475. End If
  2476. End Sub
  2477. ''' <summary>
  2478. ''' 确保在 UI 线程中执行代码,代码按触发顺序执行。
  2479. ''' 如果当前并非 UI 线程,也不阻断当前线程的执行。
  2480. ''' </summary>
  2481. Public Sub RunInUi(Action As Action, Optional ForceWaitUntilLoaded As Boolean = False)
  2482. If ForceWaitUntilLoaded Then
  2483. Application.Current.Dispatcher.InvokeAsync(Action, Threading.DispatcherPriority.Loaded)
  2484. ElseIf RunInUi() Then
  2485. Action()
  2486. Else
  2487. Application.Current.Dispatcher.InvokeAsync(Action)
  2488. End If
  2489. End Sub
  2490. ''' <summary>
  2491. ''' 确保在工作线程中执行代码。
  2492. ''' </summary>
  2493. Public Sub RunInThread(Action As Action)
  2494. If RunInUi() Then
  2495. RunInNewThread(Action, "Invoke " & GetUuid())
  2496. Else
  2497. Action()
  2498. End If
  2499. End Sub
  2500. ''' <summary>
  2501. ''' 选择所有最大值对应的对象。
  2502. ''' 若没有元素则返回空列表。
  2503. ''' </summary>
  2504. <Extension> Public Function MaxByAll(Of T, C As IComparable(Of C))(Source As IEnumerable(Of T), Selector As Func(Of T, C)) As List(Of T)
  2505. Dim Results As New List(Of T)
  2506. Using Enumerator = Source.GetEnumerator()
  2507. If Not Enumerator.MoveNext() Then Return Results
  2508. Dim MaxItem As T = Enumerator.Current
  2509. Dim MaxValue As C = Selector(MaxItem)
  2510. Results.Add(MaxItem)
  2511. While Enumerator.MoveNext()
  2512. Dim CurrentItem = Enumerator.Current
  2513. Dim CurrentValue = Selector(CurrentItem)
  2514. Dim Comparison = CurrentValue.CompareTo(MaxValue)
  2515. If Comparison > 0 Then
  2516. MaxValue = CurrentValue
  2517. Results.Clear()
  2518. Results.Add(CurrentItem)
  2519. ElseIf Comparison = 0 Then
  2520. Results.Add(CurrentItem)
  2521. End If
  2522. End While
  2523. End Using
  2524. Return Results
  2525. End Function
  2526. ''' <summary>
  2527. ''' 选择所有最小值对应的对象。
  2528. ''' 若没有元素则返回空列表。
  2529. ''' </summary>
  2530. <Extension> Public Function MinByAll(Of T, C As IComparable(Of C))(List As IEnumerable(Of T), Selector As Func(Of T, C)) As List(Of T)
  2531. Dim Results As New List(Of T)
  2532. Using Enumerator = List.GetEnumerator()
  2533. If Not Enumerator.MoveNext() Then Return Results
  2534. Dim MinItem As T = Enumerator.Current
  2535. Dim MinValue As C = Selector(MinItem)
  2536. Results.Add(MinItem)
  2537. While Enumerator.MoveNext()
  2538. Dim CurrentItem = Enumerator.Current
  2539. Dim CurrentValue = Selector(CurrentItem)
  2540. Dim Comparison = CurrentValue.CompareTo(MinValue)
  2541. If Comparison < 0 Then
  2542. MinValue = CurrentValue
  2543. Results.Clear()
  2544. Results.Add(CurrentItem)
  2545. ElseIf Comparison = 0 Then
  2546. Results.Add(CurrentItem)
  2547. End If
  2548. End While
  2549. End Using
  2550. Return Results
  2551. End Function
  2552. ''' <summary>
  2553. ''' 选择最大值对应的对象。
  2554. ''' 若没有元素则返回 Nothing。
  2555. ''' </summary>
  2556. <Extension> Public Function MaxBy(Of T, C As IComparable(Of C))(Source As IEnumerable(Of T), Selector As Func(Of T, C)) As T
  2557. Using Enumerator = Source.GetEnumerator()
  2558. If Not Enumerator.MoveNext() Then Return Nothing
  2559. Dim MaxItem As T = Enumerator.Current
  2560. Dim MaxValue As C = Selector(MaxItem)
  2561. While Enumerator.MoveNext()
  2562. Dim Value = Selector(Enumerator.Current)
  2563. If Value.CompareTo(MaxValue) <= 0 Then Continue While
  2564. MaxItem = Enumerator.Current
  2565. MaxValue = Value
  2566. End While
  2567. Return MaxItem
  2568. End Using
  2569. End Function
  2570. ''' <summary>
  2571. ''' 选择最小值对应的对象。
  2572. ''' 若没有元素则返回 Nothing。
  2573. ''' </summary>
  2574. <Extension> Public Function MinBy(Of T, C As IComparable(Of C))(List As IEnumerable(Of T), Selector As Func(Of T, C)) As T
  2575. Using Enumerator = List.GetEnumerator()
  2576. If Not Enumerator.MoveNext() Then Return Nothing
  2577. Dim MinItem As T = Enumerator.Current
  2578. Dim MinValue As C = Selector(MinItem)
  2579. While Enumerator.MoveNext()
  2580. Dim Value = Selector(Enumerator.Current)
  2581. If Value.CompareTo(MinValue) >= 0 Then Continue While
  2582. MinItem = Enumerator.Current
  2583. MinValue = Value
  2584. End While
  2585. Return MinItem
  2586. End Using
  2587. End Function
  2588. ''' <summary>
  2589. ''' 按照既定的函数进行选择排序。
  2590. ''' 返回第一个对象是否应该排在前面(a > b)。
  2591. ''' </summary>
  2592. <Extension> Public Function SortByComparison(Of T)(List As IList(Of T), SortRule As ComparisonBoolean(Of T)) As List(Of T)
  2593. Dim NewList As New List(Of T)
  2594. While List.Any
  2595. Dim Highest = List(0)
  2596. For i = 1 To List.Count - 1
  2597. If SortRule(List(i), Highest) Then Highest = List(i)
  2598. Next
  2599. List.Remove(Highest)
  2600. NewList.Add(Highest)
  2601. End While
  2602. Return NewList
  2603. End Function
  2604. Public Delegate Function ComparisonBoolean(Of T)(Left As T, Right As T) As Boolean
  2605. ''' <summary>
  2606. ''' 返回列表的浅表副本。
  2607. ''' </summary>
  2608. <Extension> Public Function Clone(Of T)(list As IList(Of T)) As IList(Of T)
  2609. Return New List(Of T)(list)
  2610. End Function
  2611. ''' <summary>
  2612. ''' 尝试从字典中获取某项,如果该项不存在,则返回默认值。
  2613. ''' </summary>
  2614. <Extension> Public Function GetOrDefault(Of TKey, TValue)(Dict As IDictionary(Of TKey, TValue), Key As TKey, Optional DefaultValue As TValue = Nothing) As TValue
  2615. Dim Result As TValue
  2616. Return If(Dict.TryGetValue(Key, Result), Result, DefaultValue)
  2617. End Function
  2618. ''' <summary>
  2619. ''' 将某项添加到以列表作为值的字典中。
  2620. ''' </summary>
  2621. <Extension> Public Sub AddToList(Of TKey, TValue)(Dict As IDictionary(Of TKey, List(Of TValue)), Key As TKey, Value As TValue)
  2622. If Dict.ContainsKey(Key) Then
  2623. Dict(Key).Add(Value)
  2624. Else
  2625. Dict.Add(Key, New List(Of TValue) From {Value})
  2626. End If
  2627. End Sub
  2628. ''' <summary>
  2629. ''' 获取程序启动参数。
  2630. ''' </summary>
  2631. ''' <param name="Name">参数名。</param>
  2632. ''' <param name="DefaultValue">默认值。</param>
  2633. Public Function GetProgramArgument(Name As String, Optional DefaultValue As Object = "")
  2634. Dim AllArguments() As String = Command.Split(" ")
  2635. For i = 0 To AllArguments.Length - 1
  2636. If AllArguments(i) = "-" & Name Then
  2637. If AllArguments.Length = i + 1 OrElse AllArguments(i + 1).StartsWithF("-") Then Return True
  2638. Return AllArguments(i + 1)
  2639. End If
  2640. Next
  2641. Return DefaultValue
  2642. End Function
  2643. ''' <summary>
  2644. ''' 时间戳转化为日期。
  2645. ''' </summary>
  2646. Public Function GetDate(timeStamp As Integer) As Date
  2647. Dim dtStart As Date = TimeZone.CurrentTimeZone.ToLocalTime(New Date(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
  2648. Dim lTime As Long = (CLng(timeStamp) * 10000000)
  2649. Return dtStart.Add(New TimeSpan(lTime))
  2650. End Function
  2651. ''' <summary>
  2652. ''' 将 UTC 时间转化为当前时区的时间。
  2653. ''' </summary>
  2654. Public Function GetLocalTime(UtcDate As Date) As Date
  2655. Return DateTime.SpecifyKind(UtcDate, DateTimeKind.Utc).ToLocalTime
  2656. End Function
  2657. ''' <summary>
  2658. ''' 打开网页。
  2659. ''' </summary>
  2660. Public Sub OpenWebsite(Url As String)
  2661. Try
  2662. If Not Url.StartsWithF("http", True) AndAlso Not Url.StartsWithF("minecraft://", True) AndAlso Not Url.StartsWithF("minecraft-preview://", True) Then
  2663. Throw New Exception(Url & " 不是一个有效的网址,它必须以 http 开头!")
  2664. End If
  2665. Log("[System] 正在打开网页:" & Url)
  2666. StartProcess(Url)
  2667. Catch ex As Exception
  2668. Log(ex, "无法打开网页(" & Url & ")")
  2669. ClipboardSet(Url, False)
  2670. MyMsgBox("可能由于浏览器未正确配置,PCL 无法为你打开网页。" & vbCrLf & "网址已经复制到剪贴板,若有需要可以手动粘贴访问。" & vbCrLf &
  2671. $"网址:{Url}", "无法打开网页")
  2672. End Try
  2673. End Sub
  2674. ''' <summary>
  2675. ''' 打开 explorer。
  2676. ''' 若不以 \ 结尾,则将视作文件路径,打开并选中此文件。
  2677. ''' </summary>
  2678. Public Sub OpenExplorer(Location As String)
  2679. Try
  2680. Location = Location.Replace("/", "\").Trim(" "c, """"c)
  2681. Log("[System] 正在打开资源管理器:" & Location)
  2682. If Location.EndsWithF("\") Then
  2683. StartProcess(Location)
  2684. Else
  2685. StartProcess("explorer", $"/select,""{Location}""")
  2686. End If
  2687. Catch ex As Exception
  2688. Log(ex, "打开资源管理器失败,请尝试关闭安全软件(如 360 安全卫士)", LogLevel.Msgbox)
  2689. End Try
  2690. End Sub
  2691. ''' <summary>
  2692. ''' 设置剪贴板。将在另一线程运行,且不会抛出异常。
  2693. ''' </summary>
  2694. Public Sub ClipboardSet(Text As String, Optional ShowSuccessHint As Boolean = True)
  2695. RunInThread(
  2696. Sub()
  2697. Dim RetryCount As Integer = 0
  2698. Retry:
  2699. Try
  2700. RunInUi(
  2701. Sub()
  2702. My.Computer.Clipboard.Clear()
  2703. If Not String.IsNullOrEmpty(Text) Then My.Computer.Clipboard.SetText(Text)
  2704. End Sub)
  2705. Catch ex As Exception
  2706. RetryCount += 1
  2707. If RetryCount <= 5 Then
  2708. Thread.Sleep(20)
  2709. GoTo Retry
  2710. Else
  2711. Log(ex, "可能由于剪贴板被其他程序占用,文本复制失败", LogLevel.Hint)
  2712. End If
  2713. End Try
  2714. If ShowSuccessHint Then Hint("已成功复制!", HintType.Green)
  2715. End Sub)
  2716. End Sub
  2717. ''' <summary>
  2718. ''' 获取剪贴板文本。将在 UI 线程运行,且不会抛出异常。
  2719. ''' </summary>
  2720. Public Function ClipboardGetText() As String
  2721. Dim Result As String = Nothing
  2722. RunInUiWait(
  2723. Sub()
  2724. Try
  2725. If My.Computer.Clipboard.ContainsText() Then Result = My.Computer.Clipboard.GetText()
  2726. Catch ex As Exception
  2727. Log(ex, "获取剪贴板文本失败")
  2728. End Try
  2729. End Sub)
  2730. Return Result
  2731. End Function
  2732. ''' <summary>
  2733. ''' 以 Byte() 形式获取程序中的资源。
  2734. ''' </summary>
  2735. Public Function GetResources(ResourceName As String) As Byte()
  2736. Log("[System] 获取资源:" & ResourceName)
  2737. Dim Raw As Byte() = My.Resources.ResourceManager.GetObject(ResourceName)
  2738. Return Raw
  2739. End Function
  2740. #End Region
  2741. #Region "UI"
  2742. '边距改变
  2743. ''' <summary>
  2744. ''' 相对增减控件的左边距。
  2745. ''' </summary>
  2746. Public Sub DeltaLeft(control As FrameworkElement, newValue As Double)
  2747. If TypeOf control Is Window Then
  2748. '窗口改变
  2749. CType(control, Window).Left += newValue
  2750. Else
  2751. '根据 HorizontalAlignment 改变数值
  2752. Select Case control.HorizontalAlignment
  2753. Case HorizontalAlignment.Left, HorizontalAlignment.Stretch
  2754. control.Margin = New Thickness(control.Margin.Left + newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2755. Case HorizontalAlignment.Right
  2756. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right - newValue, control.Margin.Bottom)
  2757. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2758. End Select
  2759. End If
  2760. End Sub
  2761. ''' <summary>
  2762. ''' 设置控件的左边距。(仅针对置左控件)
  2763. ''' </summary>
  2764. Public Sub SetLeft(control As FrameworkElement, newValue As Double)
  2765. control.Margin = New Thickness(newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2766. End Sub
  2767. ''' <summary>
  2768. ''' 相对增减控件的上边距。
  2769. ''' </summary>
  2770. Public Sub DeltaTop(control As FrameworkElement, newValue As Double)
  2771. If TypeOf control Is Window Then
  2772. '窗口改变
  2773. CType(control, Window).Top += newValue
  2774. Else
  2775. '根据 VerticalAlignment 改变数值
  2776. Select Case control.VerticalAlignment
  2777. Case VerticalAlignment.Top
  2778. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top + newValue, control.Margin.Right, control.Margin.Bottom)
  2779. Case VerticalAlignment.Bottom
  2780. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, control.Margin.Bottom - newValue)
  2781. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2782. End Select
  2783. End If
  2784. 'If Double.IsNaN(newValue) OrElse Double.IsInfinity(newValue) Then Return '安全性检查
  2785. 'Select Case control.VerticalAlignment
  2786. ' Case VerticalAlignment.Top, VerticalAlignment.Stretch, VerticalAlignment.Center
  2787. ' control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2788. ' Case VerticalAlignment.Bottom
  2789. ' control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, -newValue)
  2790. ' 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, CType(control.Parent, Object).ActualHeight - control.ActualHeight - newValue)
  2791. 'End Select
  2792. End Sub
  2793. ''' <summary>
  2794. ''' 设置控件的顶边距。(仅针对置上控件)
  2795. ''' </summary>
  2796. Public Sub SetTop(control As FrameworkElement, newValue As Double)
  2797. control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2798. End Sub
  2799. 'DPI 转换
  2800. Public ReadOnly DPI As Integer = System.Drawing.Graphics.FromHwnd(IntPtr.Zero).DpiX
  2801. ''' <summary>
  2802. ''' 将经过 DPI 缩放的 WPF 尺寸转化为实际的像素尺寸。
  2803. ''' </summary>
  2804. Public Function GetPixelSize(WPFSize As Double) As Double
  2805. Return WPFSize / 96 * DPI
  2806. End Function
  2807. ''' <summary>
  2808. ''' 将实际的像素尺寸转化为经过 DPI 缩放的 WPF 尺寸。
  2809. ''' </summary>
  2810. Public Function GetWPFSize(PixelSize As Double) As Double
  2811. Return PixelSize * 96 / DPI
  2812. End Function
  2813. 'UI 截图
  2814. ''' <summary>
  2815. ''' 将某个控件的呈现转换为图片。
  2816. ''' </summary>
  2817. Public Function ControlBrush(UI As FrameworkElement) As ImageBrush
  2818. Dim Width = UI.ActualWidth, Height = UI.ActualHeight
  2819. If Width < 1 OrElse Height < 1 Then Return New ImageBrush
  2820. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Pbgra32)
  2821. bmp.Render(UI)
  2822. Return New ImageBrush(bmp)
  2823. End Function
  2824. ''' <summary>
  2825. ''' 将某个控件的模拟呈现转换为图片。
  2826. ''' </summary>
  2827. Public Function ControlBrush(UI As FrameworkElement, Width As Double, Height As Double, Optional Left As Double = 0, Optional Top As Double = 0) As ImageBrush
  2828. UI.Measure(New Size(Width, Height))
  2829. UI.Arrange(New Rect(0, 0, Width, Height))
  2830. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Default)
  2831. bmp.Render(UI)
  2832. If Not (Left = 0 AndAlso Top = 0) Then UI.Arrange(New Rect(Left, Top, Width, Height))
  2833. Return New ImageBrush(bmp)
  2834. End Function
  2835. ''' <summary>
  2836. ''' 将 UI 内容固定为图片并进行 Clear。
  2837. ''' </summary>
  2838. Public Sub ControlFreeze(UI As Panel)
  2839. UI.Background = ControlBrush(UI)
  2840. UI.Children.Clear()
  2841. End Sub
  2842. ''' <summary>
  2843. ''' 将 UI 内容固定为图片并进行 Clear。
  2844. ''' </summary>
  2845. Public Sub ControlFreeze(UI As Border)
  2846. UI.Background = ControlBrush(UI)
  2847. UI.Child = Nothing
  2848. End Sub
  2849. ''' <summary>
  2850. ''' 将 XML 转换为对应 UI 对象。
  2851. ''' 注意:性能较差,不应大量使用。
  2852. ''' </summary>
  2853. Public Function GetObjectFromXML(Str As XElement)
  2854. Return GetObjectFromXML(Str.ToString)
  2855. End Function
  2856. ''' <summary>
  2857. ''' 将 XML 转换为对应 UI 对象。
  2858. ''' 注意:性能较差,不应大量使用。
  2859. ''' </summary>
  2860. Public Function GetObjectFromXML(Str As String) As Object
  2861. Str = Str. '兼容旧版自定义事件写法
  2862. Replace("EventType=""", "local:CustomEventService.EventType=""").
  2863. Replace("EventData=""", "local:CustomEventService.EventData=""").
  2864. Replace("EventType='", "local:CustomEventService.EventType='").
  2865. Replace("EventData='", "local:CustomEventService.EventData='").
  2866. Replace("Property=""EventType""", "Property=""local:CustomEventService.EventType""").
  2867. Replace("Property=""EventData""", "Property=""local:CustomEventService.EventData""").
  2868. Replace("Property='EventType'", "Property='local:CustomEventService.EventType'").
  2869. Replace("Property='EventData'", "Property='local:CustomEventService.EventData'")
  2870. Using Stream As New MemoryStream(Encoding.UTF8.GetBytes(Str))
  2871. '类型检查
  2872. Using Reader As New XamlXmlReader(Stream)
  2873. While Reader.Read()
  2874. For Each BlackListType In {GetType(WebBrowser), GetType(Frame), GetType(MediaElement), GetType(ObjectDataProvider), GetType(XamlReader), GetType(Window), GetType(XmlDataProvider), GetType(SettingService)}
  2875. If Reader.Type IsNot Nothing AndAlso BlackListType.IsAssignableFrom(Reader.Type.UnderlyingType) Then Throw New UnauthorizedAccessException($"基于安全考虑,不允许使用 {BlackListType.Name} 类型。")
  2876. If Reader.Value IsNot Nothing AndAlso Reader.Value = BlackListType.Name Then Throw New UnauthorizedAccessException($"基于安全考虑,不允许使用 {BlackListType.Name} 值。")
  2877. Next
  2878. For Each BlackListMember In {"Code", "FactoryMethod", "Static"}
  2879. If Reader.Member IsNot Nothing AndAlso Reader.Member.Name = BlackListMember Then Throw New UnauthorizedAccessException($"基于安全考虑,不允许使用 {BlackListMember} 成员。")
  2880. Next
  2881. End While
  2882. End Using
  2883. '实际的加载
  2884. Stream.Position = 0
  2885. Using Writer As New StreamWriter(Stream)
  2886. Writer.Write(Str)
  2887. Writer.Flush()
  2888. Stream.Position = 0
  2889. Return Markup.XamlReader.Load(Stream)
  2890. End Using
  2891. End Using
  2892. End Function
  2893. Private ReadOnly UiThreadId As Integer = Thread.CurrentThread.ManagedThreadId
  2894. ''' <summary>
  2895. ''' 当前线程是否为主线程。
  2896. ''' </summary>
  2897. Public Function RunInUi() As Boolean
  2898. Return Thread.CurrentThread.ManagedThreadId = UiThreadId
  2899. End Function
  2900. ''' <summary>
  2901. ''' 检查某个控件是否位于主窗口可视区域内,且控件本身可见。
  2902. ''' </summary>
  2903. <Extension> Public Function IsVisibleInForm(element As FrameworkElement) As Boolean
  2904. If Not element.IsVisible Then Return False
  2905. Dim bounds As Rect = element.TransformToAncestor(FrmMain).TransformBounds(New Rect(0, 0, element.ActualWidth, element.ActualHeight))
  2906. Dim rect As New Rect(0, 0, FrmMain.ActualWidth, FrmMain.ActualHeight)
  2907. Return rect.Contains(bounds.TopLeft) OrElse rect.Contains(bounds.BottomRight)
  2908. End Function
  2909. ''' <summary>
  2910. ''' 控件是否受到 TextTrimming 属性影响,导致内容被截取。
  2911. ''' </summary>
  2912. <Extension> Public Function IsTextTrimmed(Control As TextBlock) As Boolean
  2913. Control.Measure(New Size(Double.MaxValue, Double.MaxValue))
  2914. Return Control.DesiredSize.Width > Control.ActualWidth
  2915. End Function
  2916. ''' <summary>
  2917. ''' 获取文本在被渲染后的宽度。
  2918. ''' </summary>
  2919. Public Function MeasureStringWidth(text As String, Optional fontSize As Double = 14, Optional fontFamily As FontFamily = Nothing) As Double
  2920. If fontFamily Is Nothing Then fontFamily = New FontFamily("微软雅黑")
  2921. Dim formattedText = New FormattedText(
  2922. text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, New Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
  2923. fontSize, Brushes.Black, New NumberSubstitution(), TextFormattingMode.Display, New DpiScale(1, 1).PixelsPerDip)
  2924. Return formattedText.Width
  2925. End Function
  2926. ''' <summary>
  2927. ''' 将布尔值转换为 Visibility。True 转换为 Visible,False 转换为 Collapsed。
  2928. ''' </summary>
  2929. <Extension> Public Function ToVisibility(IsVisible As Boolean) As Visibility
  2930. Return If(IsVisible, Visibility.Visible, Visibility.Collapsed)
  2931. End Function
  2932. #End Region
  2933. #Region "Debug"
  2934. Public ReadOnly Property ModeDebug As Boolean
  2935. Get
  2936. Return Settings.Get("SystemDebugMode")
  2937. End Get
  2938. End Property
  2939. 'Log
  2940. Public Enum LogLevel
  2941. ''' <summary>
  2942. ''' 不提示,只记录日志。
  2943. ''' </summary>
  2944. Normal = 0
  2945. ''' <summary>
  2946. ''' 只提示开发者。
  2947. ''' </summary>
  2948. Developer = 1
  2949. ''' <summary>
  2950. ''' 只提示开发者与调试模式用户。
  2951. ''' </summary>
  2952. Debug = 2
  2953. ''' <summary>
  2954. ''' 弹出提示所有用户。
  2955. ''' </summary>
  2956. Hint = 3
  2957. ''' <summary>
  2958. ''' 弹窗,不要求反馈。
  2959. ''' </summary>
  2960. Msgbox = 4
  2961. ''' <summary>
  2962. ''' 弹窗,要求反馈。
  2963. ''' </summary>
  2964. Feedback = 5
  2965. ''' <summary>
  2966. ''' 弹出 Windows 原生弹窗,要求反馈。在无法保证 WPF 窗口能正常运行时使用此级别。
  2967. ''' 在第二次触发后会直接结束程序。
  2968. ''' </summary>
  2969. Critical = 6
  2970. End Enum
  2971. Private LogList As New StringBuilder
  2972. Private LogWritter As StreamWriter
  2973. Public Sub LogStart()
  2974. RunInNewThread(
  2975. Sub()
  2976. Dim IsInitSuccess As Boolean = True
  2977. Try
  2978. For i = 4 To 1 Step -1
  2979. If File.Exists(Path & "PCL\Log" & i & ".txt") Then
  2980. If File.Exists(Path & "PCL\Log" & (i + 1) & ".txt") Then File.Delete(Path & "PCL\Log" & (i + 1) & ".txt")
  2981. CopyFile(Path & "PCL\Log" & i & ".txt", Path & "PCL\Log" & (i + 1) & ".txt")
  2982. End If
  2983. Next
  2984. File.Create(Path & "PCL\Log1.txt").Dispose()
  2985. Catch ex As IOException
  2986. IsInitSuccess = False
  2987. Hint("可能同时开启了多个 PCL,程序可能会出现未知问题!", HintType.Red)
  2988. Log(ex, "日志初始化失败(疑似文件占用问题)")
  2989. Catch ex As Exception
  2990. IsInitSuccess = False
  2991. Log(ex, "日志初始化失败", LogLevel.Hint)
  2992. End Try
  2993. Try
  2994. LogWritter = New StreamWriter(Path & "PCL\Log1.txt", True) With {.AutoFlush = True}
  2995. Catch ex As Exception
  2996. LogWritter = Nothing
  2997. Log(ex, "日志写入失败", LogLevel.Hint)
  2998. End Try
  2999. While True
  3000. If IsInitSuccess Then
  3001. LogFlush()
  3002. Else
  3003. LogList = New StringBuilder '清空 LogList 避免内存爆炸
  3004. End If
  3005. Thread.Sleep(50)
  3006. End While
  3007. End Sub, "Log Writer", ThreadPriority.Lowest)
  3008. End Sub
  3009. Private ReadOnly LogFlushLock As New Object '防止外部调用 LogFlush 时同时输出多次日志
  3010. Public Sub LogFlush()
  3011. On Error Resume Next
  3012. If LogWritter Is Nothing Then Return
  3013. Dim Log As String = Nothing
  3014. SyncLock LogFlushLock
  3015. If LogList.Length > 0 Then
  3016. Dim LogListCache As StringBuilder
  3017. LogListCache = LogList
  3018. LogList = New StringBuilder
  3019. Log = LogListCache.ToString
  3020. End If
  3021. End SyncLock
  3022. If Log IsNot Nothing Then
  3023. LogWritter.Write(Log)
  3024. End If
  3025. End Sub
  3026. Private ReadOnly LogListLock As New Object '防止日志乱码,只在调试模式下启用
  3027. Private IsCriticalErrorTriggered As Boolean = False
  3028. ''' <summary>
  3029. ''' 输出 Log。
  3030. ''' </summary>
  3031. ''' <param name="Title">如果要求弹窗,指定弹窗的标题。</param>
  3032. Public Sub Log(Text As String, Optional Level As LogLevel = LogLevel.Normal, Optional Title As String = "出现错误")
  3033. On Error Resume Next
  3034. '放在最后会导致无法显示极端错误下的弹窗(如无法写入日志文件)
  3035. '处理错误会导致再次调用 Log() 导致无限循环
  3036. '输出日志
  3037. Dim AppendText As String = $"[{GetTimeNow()}] <{If(Thread.CurrentThread.Name = "", "主线程", Thread.CurrentThread.Name)}> {Text}{vbCrLf}" '减轻同步锁占用
  3038. AppendText = FilterUserName(FilterAccessToken(AppendText, "*"), "*")
  3039. If ModeDebug Then
  3040. SyncLock LogListLock
  3041. LogList.Append(AppendText)
  3042. End SyncLock
  3043. Else
  3044. LogList.Append(AppendText)
  3045. End If
  3046. #If DEBUG Then
  3047. Console.Write(AppendText)
  3048. #End If
  3049. If IsProgramEnded OrElse Level = LogLevel.Normal Then Return
  3050. '去除前缀
  3051. Text = Text.RegexReplace("\[[^\]]+?\] ", "")
  3052. '输出提示
  3053. Select Case Level
  3054. #If DEBUG Then
  3055. Case LogLevel.Developer
  3056. Hint("[开发者模式] " & Text, HintType.Blue, False)
  3057. Case LogLevel.Debug
  3058. Hint("[调试模式] " & Text, HintType.Blue, False)
  3059. #Else
  3060. Case LogLevel.Developer
  3061. Case LogLevel.Debug
  3062. If ModeDebug Then Hint("[调试模式] " & Text, HintType.Blue, False)
  3063. #End If
  3064. Case LogLevel.Hint
  3065. Hint(Text, HintType.Red, False)
  3066. Case LogLevel.Msgbox
  3067. MyMsgBox(Text, Title, IsWarn:=True)
  3068. Case LogLevel.Feedback
  3069. If CanFeedback(False) Then
  3070. If MyMsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  3071. Else
  3072. MyMsgBox(Text & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  3073. End If
  3074. Case LogLevel.Critical
  3075. If IsCriticalErrorTriggered Then
  3076. FormMain.EndProgramForce(ProcessReturnValues.Exception)
  3077. Return
  3078. End If
  3079. IsCriticalErrorTriggered = True
  3080. If CanFeedback(False) Then
  3081. If MsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  3082. Else
  3083. MsgBox(Text & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  3084. End If
  3085. End Select
  3086. '上报
  3087. If Level >= LogLevel.Hint Then
  3088. Telemetry("PCL 错误",
  3089. "Level", GetStringFromEnum(Level),
  3090. "Title", FilterUserName(FilterAccessToken(Title, "*"), "*"),
  3091. "Exception", FilterUserName(FilterAccessToken(Text, "*"), "*"))
  3092. End If
  3093. End Sub
  3094. ''' <summary>
  3095. ''' 输出错误信息。
  3096. ''' </summary>
  3097. ''' <param name="Desc">错误描述。会在处理时在末尾加入冒号。</param>
  3098. Public Sub Log(Ex As Exception, Desc As String, Optional Level As LogLevel = LogLevel.Debug, Optional Title As String = "出现错误")
  3099. On Error Resume Next
  3100. If TypeOf Ex Is ThreadInterruptedException Then Return
  3101. '获取错误信息
  3102. Dim ExFull As String = $"{Desc}:{Ex.GetDetail()}"
  3103. '输出日志
  3104. Dim AppendText As String = $"[{GetTimeNow()}] <{If(Thread.CurrentThread.Name = "", "主线程", Thread.CurrentThread.Name)}> {Desc}:{Ex.GetDetail(True)}{vbCrLf}" '减轻同步锁占用
  3105. AppendText = FilterUserName(FilterAccessToken(AppendText, "*"), "*")
  3106. If ModeDebug Then
  3107. SyncLock LogListLock
  3108. LogList.Append(AppendText)
  3109. End SyncLock
  3110. Else
  3111. LogList.Append(AppendText)
  3112. End If
  3113. #If DEBUG Then
  3114. Console.Write(AppendText)
  3115. #End If
  3116. If IsProgramEnded Then Return
  3117. '输出提示
  3118. Select Case Level
  3119. Case LogLevel.Normal
  3120. #If DEBUG Then
  3121. Case LogLevel.Developer
  3122. Dim ExLine As String = Desc & ":" & Ex.GetBrief()
  3123. Hint("[开发者模式] " & ExLine, HintType.Blue, False)
  3124. Case LogLevel.Debug
  3125. Dim ExLine As String = Desc & ":" & Ex.GetBrief()
  3126. Hint("[调试模式] " & ExLine, HintType.Blue, False)
  3127. #Else
  3128. Case LogLevel.Developer
  3129. Case LogLevel.Debug
  3130. Dim ExLine As String = Desc & ":" & Ex.GetBrief()
  3131. If ModeDebug Then Hint("[调试模式] " & ExLine, HintType.Blue, False)
  3132. #End If
  3133. Case LogLevel.Hint
  3134. Dim ExLine As String = Desc & ":" & Ex.GetBrief()
  3135. Hint(ExLine, HintType.Red, False)
  3136. Case LogLevel.Msgbox
  3137. MyMsgBox(ExFull, Title, IsWarn:=True)
  3138. Case LogLevel.Feedback
  3139. If CanFeedback(False) Then
  3140. If MyMsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  3141. Else
  3142. MyMsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  3143. End If
  3144. Case LogLevel.Critical
  3145. If IsCriticalErrorTriggered Then
  3146. FormMain.EndProgramForce(ProcessReturnValues.Exception)
  3147. Return
  3148. End If
  3149. IsCriticalErrorTriggered = True
  3150. If CanFeedback(False) Then
  3151. If MsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  3152. Else
  3153. MsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  3154. End If
  3155. End Select
  3156. '上报
  3157. If Level >= LogLevel.Hint Then
  3158. Telemetry("PCL 异常",
  3159. "Level", GetStringFromEnum(Level),
  3160. "Title", FilterUserName(FilterAccessToken(Title, "*"), "*"),
  3161. "Exception", FilterUserName(FilterAccessToken(ExFull, "*"), "*"))
  3162. End If
  3163. End Sub
  3164. '反馈
  3165. Public Sub Feedback(Optional ShowMsgbox As Boolean = True, Optional ForceOpenLog As Boolean = False)
  3166. On Error Resume Next
  3167. FeedbackInfo()
  3168. If ForceOpenLog OrElse (ShowMsgbox AndAlso MyMsgBox("若你在汇报一个 Bug,请点击 打开文件夹 按钮,并上传 Log(1~5).txt 中包含错误信息的文件。" & vbCrLf & "游戏崩溃一般与启动器无关,请不要因为游戏崩溃而提交反馈。", "反馈提交提醒", "打开文件夹", "不需要") = 1) Then
  3169. OpenExplorer(Path & "PCL\Log1.txt")
  3170. End If
  3171. OpenWebsite("https://github.com/Meloong-Git/PCL/issues/")
  3172. End Sub
  3173. Public Function CanFeedback(ShowHint As Boolean) As Boolean
  3174. If False.Equals(PageSetupSystem.IsLauncherNewest) Then
  3175. If ShowHint Then
  3176. If MyMsgBox($"你的 PCL 不是最新版,因此无法提交反馈。{vbCrLf}请在更新后,确认该问题在最新版中依然存在,然后再提交反馈。", "无法提交反馈", "更新", "取消") = 1 Then
  3177. UpdateCheckByButton()
  3178. End If
  3179. End If
  3180. Return False
  3181. Else
  3182. Return True
  3183. End If
  3184. End Function
  3185. ''' <summary>
  3186. ''' 在日志中输出系统诊断信息。
  3187. ''' </summary>
  3188. Public Sub FeedbackInfo()
  3189. On Error Resume Next
  3190. Log("[System] 诊断信息:" & vbCrLf &
  3191. "操作系统:" & My.Computer.Info.OSFullName & "(32 位:" & Is32BitSystem & ")" & vbCrLf &
  3192. "剩余内存:" & Int(My.Computer.Info.AvailablePhysicalMemory / 1024 / 1024) & " M / " & Int(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024) & " M" & vbCrLf &
  3193. "DPI:" & DPI & "(" & Math.Round(DPI / 96, 2) * 100 & "%)" & vbCrLf &
  3194. "MC 文件夹:" & If(McFolderSelected, "Nothing") & vbCrLf &
  3195. "文件位置:" & Path)
  3196. End Sub
  3197. '遥测
  3198. Public Sub Telemetry([Event] As String, ParamArray Datas As String())
  3199. If Not Settings.Get("SystemSystemTelemetry") Then Return '用户关闭了遥测
  3200. If Not ClsBaseUrl.StartsWithF("http") Then Return '开源版没有设置遥测地址
  3201. If VersionBranchName = "Debug" Then Return '开发版本不上传遥测
  3202. RunInNewThread(
  3203. Sub()
  3204. Try
  3205. Log($"[System] 匿名数据上报:{[Event]}")
  3206. Dim Url As String = $"{ClsBaseUrl}&Event={WebUtility.UrlEncode([Event])}"
  3207. For i = 0 To Datas.Length - 1 Step 2
  3208. Url &= "&" & WebUtility.UrlEncode(Datas(i)) & "=" & WebUtility.UrlEncode(Datas(i + 1).Replace(vbCrLf, vbLf))
  3209. Next
  3210. NetRequestByClient(Url, MakeLog:=False)
  3211. Catch ex As Exception
  3212. Log(ex, "匿名数据上报失败")
  3213. End Try
  3214. End Sub, "Telemetry", ThreadPriority.Lowest)
  3215. End Sub
  3216. '获取当前的堆栈信息
  3217. Public Function GetStackTrace() As String
  3218. Return (New StackTrace).GetFrames().Skip(1).
  3219. Select(Function(f) f.GetMethod).
  3220. Select(Function(f) $"{f.Name}({f.GetParameters.Select(Function(p) p.ToString).Join(", ")}) - {f.Module}").
  3221. Join(vbCrLf).Replace(vbCrLf & vbCrLf, vbCrLf)
  3222. End Function
  3223. #End Region
  3224. #Region "随机"
  3225. Private ReadOnly Random As New Random
  3226. ''' <summary>
  3227. ''' 随机选择其一。
  3228. ''' </summary>
  3229. Public Function RandomOne(Of T)(objects As ICollection(Of T)) As T
  3230. Return objects(RandomInteger(0, objects.Count - 1))
  3231. End Function
  3232. ''' <summary>
  3233. ''' 取随机整数(包含)。
  3234. ''' </summary>
  3235. Public Function RandomInteger(min As Integer, max As Integer) As Integer
  3236. Return Math.Floor((max - min + 1) * Random.NextDouble) + min
  3237. End Function
  3238. ''' <summary>
  3239. ''' 将数组随机打乱。
  3240. ''' </summary>
  3241. <Extension> Public Iterator Function Shuffle(Of T)(Raw As IEnumerable(Of T)) As IEnumerable(Of T)
  3242. Dim RawCopy As New List(Of T)(Raw)
  3243. Do While RawCopy.Any
  3244. Dim i As Integer = RandomInteger(0, RawCopy.Count - 1)
  3245. Yield RawCopy(i)
  3246. RawCopy.RemoveAt(i)
  3247. Loop
  3248. End Function
  3249. #End Region
  3250. End Module
  3251. #Region "WPF"
  3252. ''' <summary>
  3253. ''' 对数据绑定进行加法运算,使用参数决定加数。
  3254. ''' </summary>
  3255. Public Class AdditionConverter
  3256. Implements IValueConverter
  3257. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3258. If value Is Nothing Then Return 0
  3259. Dim before As Double
  3260. If Not Double.TryParse(value.ToString(), before) Then Return 0
  3261. Dim scale As Double = 1
  3262. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3263. Return before + scale
  3264. End Function
  3265. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3266. If value Is Nothing Then Return Binding.DoNothing
  3267. Dim before As Double
  3268. If Not Double.TryParse(value.ToString(), before) Then Return Binding.DoNothing
  3269. Dim scale As Double = 1
  3270. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3271. If scale = 0 Then Return Binding.DoNothing
  3272. Return before - scale
  3273. End Function
  3274. End Class
  3275. ''' <summary>
  3276. ''' 对数据绑定进行乘法运算,使用参数决定乘数。
  3277. ''' </summary>
  3278. Public Class MultiplicationConverter
  3279. Implements IValueConverter
  3280. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3281. If value Is Nothing Then Return 0
  3282. Dim before As Double
  3283. If Not Double.TryParse(value.ToString(), before) Then Return 0
  3284. Dim scale As Double = 1
  3285. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3286. Return before * scale
  3287. End Function
  3288. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3289. If value Is Nothing Then Return Binding.DoNothing
  3290. Dim before As Double
  3291. If Not Double.TryParse(value.ToString(), before) Then Return Binding.DoNothing
  3292. Dim scale As Double = 1
  3293. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3294. If scale = 0 Then Return Binding.DoNothing
  3295. Return before / scale
  3296. End Function
  3297. End Class
  3298. ''' <summary>
  3299. ''' 将取反的 Boolean 绑定到 Visibility。
  3300. ''' </summary>
  3301. Public Class InverseBooleanToVisibilityConverter
  3302. Implements IValueConverter
  3303. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3304. If value Is Nothing Then Return Visibility.Visible
  3305. Dim boolValue As Boolean
  3306. Return If(Boolean.TryParse(value.ToString(), boolValue), If(boolValue, Visibility.Collapsed, Visibility.Visible), Visibility.Visible)
  3307. End Function
  3308. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3309. If value Is Nothing Then Return False
  3310. Return If(TypeOf value Is Visibility, value <> Visibility.Visible, False)
  3311. End Function
  3312. End Class
  3313. ''' <summary>
  3314. ''' 将 Boolean 取反。
  3315. ''' </summary>
  3316. Public Class InverseBooleanConverter
  3317. Implements IValueConverter
  3318. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3319. If value Is Nothing Then Return False
  3320. Dim boolValue As Boolean
  3321. Return If(Boolean.TryParse(value.ToString(), boolValue), Not boolValue, False)
  3322. End Function
  3323. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3324. If value Is Nothing Then Return False
  3325. Return If(Boolean.TryParse(value.ToString(), value), Not value, False)
  3326. End Function
  3327. End Class
  3328. #End Region