ModBase.vb 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733
  1. Imports System.IO.Compression
  2. Imports System.Runtime.CompilerServices
  3. Imports System.Security.Cryptography
  4. Imports System.Security.Principal
  5. Imports System.Text.RegularExpressions
  6. Imports System.Windows.Markup
  7. Imports Newtonsoft.Json
  8. Public Module ModBase
  9. #Region "声明"
  10. '下列版本信息由更新器自动修改
  11. Public Const VersionBaseName As String = "2.8.4" '不含分支前缀的显示用版本名
  12. Public Const VersionStandardCode As String = "2.8.4." & VersionBranchCode '标准格式的四段式版本号
  13. #If BETA Then
  14. Public Const VersionCode As Integer = 332 'Release
  15. #Else
  16. Public Const VersionCode As Integer = 333 'Snapshot
  17. #End If
  18. '自动生成的版本信息
  19. Public Const VersionDisplayName As String = VersionBranchName & " " & VersionBaseName
  20. #If RELEASE Then
  21. Public Const VersionBranchName As String = "Snapshot"
  22. Public Const VersionBranchCode As String = "0"
  23. #ElseIf BETA Then
  24. Public Const VersionBranchName As String = "Release"
  25. Public Const VersionBranchCode As String = "50"
  26. #Else
  27. Public Const VersionBranchName As String = "Debug"
  28. Public Const VersionBranchCode As String = "100"
  29. #End If
  30. ''' <summary>
  31. ''' 主窗口句柄。
  32. ''' </summary>
  33. Public Handle As IntPtr
  34. ''' <summary>
  35. ''' 程序的启动路径,以“\”结尾。
  36. ''' </summary>
  37. Public Path As String = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
  38. ''' <summary>
  39. ''' 包含程序名的完整路径。
  40. ''' </summary>
  41. Public PathWithName As String = Path & AppDomain.CurrentDomain.SetupInformation.ApplicationName
  42. ''' <summary>
  43. ''' 程序内嵌图片文件夹路径,以“/”结尾。
  44. ''' </summary>
  45. Public PathImage As String = "pack://application:,,,/Plain Craft Launcher 2;component/Images/"
  46. ''' <summary>
  47. ''' 当前程序的语言。
  48. ''' </summary>
  49. Public Lang As String = "zh_CN"
  50. ''' <summary>
  51. ''' 设置对象。
  52. ''' </summary>
  53. Public Setup As New ModSetup
  54. ''' <summary>
  55. ''' 程序的打开计时。
  56. ''' </summary>
  57. Public ApplicationStartTick As Long = GetTimeTick()
  58. ''' <summary>
  59. ''' 程序打开时的时间。
  60. ''' </summary>
  61. Public ApplicationOpenTime As Date = Date.Now
  62. ''' <summary>
  63. ''' 设备唯一标识符。
  64. ''' </summary>
  65. Public UniqueAddress As String = SecretGetUniqueAddress()
  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.ToUpper.First & ":\" '#3799
  82. ''' <summary>
  83. ''' 程序的缓存文件夹路径,以 \ 结尾。
  84. ''' </summary>
  85. Public PathTemp As String = If(Setup.Get("SystemSystemCache") = "", IO.Path.GetTempPath() & "PCL\", Setup.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 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"
  173. ''' <summary>
  174. ''' 图标,播放,0.8x
  175. ''' </summary>
  176. 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"
  177. End Class
  178. #End Region
  179. #Region "自定义类"
  180. ''' <summary>
  181. ''' 支持小数与常见类型隐式转换的颜色。
  182. ''' </summary>
  183. Public Class MyColor
  184. Public A As Double = 255
  185. Public R As Double = 0
  186. Public G As Double = 0
  187. Public B As Double = 0
  188. '类型转换
  189. Public Shared Widening Operator CType(str As String) As MyColor
  190. Return New MyColor(str)
  191. End Operator
  192. Public Shared Widening Operator CType(col As Color) As MyColor
  193. Return New MyColor(col)
  194. End Operator
  195. Public Shared Widening Operator CType(conv As MyColor) As Color
  196. Return Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  197. End Operator
  198. Public Shared Widening Operator CType(conv As MyColor) As System.Drawing.Color
  199. Return System.Drawing.Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  200. End Operator
  201. Public Shared Widening Operator CType(bru As SolidColorBrush) As MyColor
  202. Return New MyColor(bru.Color)
  203. End Operator
  204. Public Shared Widening Operator CType(conv As MyColor) As SolidColorBrush
  205. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  206. End Operator
  207. Public Shared Widening Operator CType(bru As Brush) As MyColor
  208. Return New MyColor(bru)
  209. End Operator
  210. Public Shared Widening Operator CType(conv As MyColor) As Brush
  211. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  212. End Operator
  213. '颜色运算
  214. Public Shared Operator +(a As MyColor, b As MyColor) As MyColor
  215. Return New MyColor With {.A = a.A + b.A, .B = a.B + b.B, .G = a.G + b.G, .R = a.R + b.R}
  216. End Operator
  217. Public Shared Operator -(a As MyColor, b As MyColor) As MyColor
  218. Return New MyColor With {.A = a.A - b.A, .B = a.B - b.B, .G = a.G - b.G, .R = a.R - b.R}
  219. End Operator
  220. Public Shared Operator *(a As MyColor, b As Double) As MyColor
  221. Return New MyColor With {.A = a.A * b, .B = a.B * b, .G = a.G * b, .R = a.R * b}
  222. End Operator
  223. Public Shared Operator /(a As MyColor, b As Double) As MyColor
  224. Return New MyColor With {.A = a.A / b, .B = a.B / b, .G = a.G / b, .R = a.R / b}
  225. End Operator
  226. Public Shared Operator =(a As MyColor, b As MyColor) As Boolean
  227. If IsNothing(a) AndAlso IsNothing(b) Then Return True
  228. If IsNothing(a) OrElse IsNothing(b) Then Return False
  229. Return a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B
  230. End Operator
  231. Public Shared Operator <>(a As MyColor, b As MyColor) As Boolean
  232. If IsNothing(a) AndAlso IsNothing(b) Then Return False
  233. If IsNothing(a) OrElse IsNothing(b) Then Return True
  234. Return Not (a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B)
  235. End Operator
  236. '构造函数
  237. Public Sub New()
  238. End Sub
  239. Public Sub New(col As Color)
  240. Me.A = col.A
  241. Me.R = col.R
  242. Me.G = col.G
  243. Me.B = col.B
  244. End Sub
  245. Public Sub New(HexString As String)
  246. Dim StringColor As Media.Color = ColorConverter.ConvertFromString(HexString)
  247. A = StringColor.A
  248. R = StringColor.R
  249. G = StringColor.G
  250. B = StringColor.B
  251. End Sub
  252. Public Sub New(newA As Double, col As MyColor)
  253. Me.A = newA
  254. Me.R = col.R
  255. Me.G = col.G
  256. Me.B = col.B
  257. End Sub
  258. Public Sub New(newR As Double, newG As Double, newB As Double)
  259. Me.A = 255
  260. Me.R = newR
  261. Me.G = newG
  262. Me.B = newB
  263. End Sub
  264. Public Sub New(newA As Double, newR As Double, newG As Double, newB As Double)
  265. Me.A = newA
  266. Me.R = newR
  267. Me.G = newG
  268. Me.B = newB
  269. End Sub
  270. Public Sub New(brush As Brush)
  271. Dim Color As Color = CType(brush, SolidColorBrush).Color
  272. A = Color.A
  273. R = Color.R
  274. G = Color.G
  275. B = Color.B
  276. End Sub
  277. Public Sub New(brush As SolidColorBrush)
  278. Dim Color As Color = brush.Color
  279. A = Color.A
  280. R = Color.R
  281. G = Color.G
  282. B = Color.B
  283. End Sub
  284. Public Sub New(obj As Object)
  285. If obj Is Nothing Then
  286. A = 255 : R = 255 : G = 255 : B = 255
  287. Else
  288. If TypeOf obj Is SolidColorBrush Then
  289. '避免反复获取 Color 对象造成性能下降
  290. Dim Color As Color = CType(obj, SolidColorBrush).Color
  291. A = Color.A
  292. R = Color.R
  293. G = Color.G
  294. B = Color.B
  295. Else
  296. A = obj.A
  297. R = obj.R
  298. G = obj.G
  299. B = obj.B
  300. End If
  301. End If
  302. End Sub
  303. 'HSL
  304. Public Function Hue(v1 As Double, v2 As Double, vH As Double) As Double
  305. If vH < 0 Then vH += 1
  306. If vH > 1 Then vH -= 1
  307. If vH < 0.16667 Then Return v1 + (v2 - v1) * 6 * vH
  308. If vH < 0.5 Then Return v2
  309. If vH < 0.66667 Then Return v1 + (v2 - v1) * (4 - vH * 6)
  310. Return v1
  311. End Function
  312. Public Function FromHSL(sH As Double, sS As Double, sL As Double) As MyColor
  313. If sS = 0 Then
  314. R = sL * 2.55
  315. G = R
  316. B = R
  317. Else
  318. Dim H = sH / 360
  319. Dim S = sS / 100
  320. Dim L = sL / 100
  321. S = If(L < 0.5, S * L + L, S * (1.0 - L) + L)
  322. L = 2 * L - S
  323. R = 255 * Hue(L, S, H + 1 / 3)
  324. G = 255 * Hue(L, S, H)
  325. B = 255 * Hue(L, S, H - 1 / 3)
  326. End If
  327. A = 255
  328. Return Me
  329. End Function
  330. Public Function FromHSL2(sH As Double, sS As Double, sL As Double) As MyColor
  331. If sS = 0 Then
  332. R = sL * 2.55 : G = R : B = R
  333. Else
  334. '初始化
  335. sH = (sH + 3600000) Mod 360
  336. Dim cent As Double() = {
  337. +0.1, -0.06, -0.3, '0, 30, 60
  338. -0.19, -0.15, -0.24, '90, 120, 150
  339. -0.32, -0.09, +0.18, '180, 210, 240
  340. +0.05, -0.12, -0.02, '270, 300, 330
  341. +0.1, -0.06} '最后两位与前两位一致,加是变亮,减是变暗
  342. '计算色调对应的亮度片区
  343. Dim center As Double = sH / 30.0
  344. Dim intCenter As Integer = Math.Floor(center) '亮度片区编号
  345. center = 50 - (
  346. (1 - center + intCenter) * cent(intCenter) + (center - intCenter) * cent(intCenter + 1)
  347. ) * sS
  348. 'center = 50 + (cent(intCenter) + (center - intCenter) * (cent(intCenter + 1) - cent(intCenter))) * sS
  349. sL = If(sL < center, sL / center, 1 + (sL - center) / (100 - center)) * 50
  350. FromHSL(sH, sS, sL)
  351. End If
  352. A = 255
  353. Return Me
  354. End Function
  355. Public Overrides Function ToString() As String
  356. Return "(" & A & "," & R & "," & G & "," & B & ")"
  357. End Function
  358. Public Overrides Function Equals(obj As Object) As Boolean
  359. Return Me = obj
  360. End Function
  361. End Class
  362. ''' <summary>
  363. ''' 支持负数与浮点数的矩形。
  364. ''' </summary>
  365. Public Class MyRect
  366. '属性
  367. Public Property Width As Double = 0
  368. Public Property Height As Double = 0
  369. Public Property Left As Double = 0
  370. Public Property Top As Double = 0
  371. '构造函数
  372. Public Sub New()
  373. End Sub
  374. Public Sub New(left As Double, top As Double, width As Double, height As Double)
  375. Me.Left = left
  376. Me.Top = top
  377. Me.Width = width
  378. Me.Height = height
  379. End Sub
  380. End Class
  381. ''' <summary>
  382. ''' 模块加载状态枚举。
  383. ''' </summary>
  384. Public Enum LoadState
  385. Waiting
  386. Loading
  387. Finished
  388. Failed
  389. Aborted
  390. End Enum
  391. ''' <summary>
  392. ''' 执行返回值。
  393. ''' </summary>
  394. Public Enum Result
  395. ''' <summary>
  396. ''' 执行成功,或进程被中断。
  397. ''' </summary>
  398. Aborted = -1
  399. ''' <summary>
  400. ''' 执行成功。
  401. ''' </summary>
  402. Success = 0
  403. ''' <summary>
  404. ''' 执行失败。
  405. ''' </summary>
  406. Fail
  407. ''' <summary>
  408. ''' 执行时出现未经处理的异常。
  409. ''' </summary>
  410. Exception
  411. ''' <summary>
  412. ''' 执行超时。
  413. ''' </summary>
  414. Timeout
  415. ''' <summary>
  416. ''' 取消执行。可能是由于不满足执行的前置条件。
  417. ''' </summary>
  418. Cancel
  419. End Enum
  420. ''' <summary>
  421. ''' 可以使用 Equals 和等号的 List。
  422. ''' </summary>
  423. Public Class EqualableList(Of T)
  424. Inherits List(Of T)
  425. Public Overrides Function Equals(obj As Object) As Boolean
  426. If TryCast(obj, List(Of T)) Is Nothing Then
  427. '类型不同
  428. Return False
  429. Else
  430. '类型相同
  431. Dim objList As List(Of T) = obj
  432. If objList.Count <> Count Then Return False
  433. For i = 0 To objList.Count - 1
  434. If Not objList(i).Equals(Me(i)) Then Return False
  435. Next
  436. Return True
  437. End If
  438. End Function
  439. Public Shared Operator =(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  440. Return EqualityComparer(Of EqualableList(Of T)).Default.Equals(left, right)
  441. End Operator
  442. Public Shared Operator <>(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  443. Return Not left = right
  444. End Operator
  445. End Class
  446. #End Region
  447. #Region "数学"
  448. ''' <summary>
  449. ''' 2~65 进制的转换。
  450. ''' </summary>
  451. Public Function RadixConvert(Input As String, FromRadix As Integer, ToRadix As Integer) As String
  452. Const Digits As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+="
  453. '零与负数的处理
  454. If String.IsNullOrEmpty(Input) Then Return "0"
  455. Dim IsNegative As Boolean = Input.StartsWithF("-")
  456. If IsNegative Then Input = Input.TrimStart("-")
  457. '转换为十进制
  458. Dim RealNum As Long = 0, Scale As Long = 1
  459. For Each Digit In Input.Reverse.Select(Function(l) Digits.IndexOfF(l))
  460. RealNum += Digit * Scale
  461. Scale *= FromRadix
  462. Next
  463. '转换为指定进制
  464. Dim Result = ""
  465. While RealNum > 0
  466. Dim NewNum As Integer = RealNum Mod ToRadix
  467. RealNum = (RealNum - NewNum) / ToRadix
  468. Result = Digits(NewNum) & Result
  469. End While
  470. '负数的结束处理与返回
  471. Return If(IsNegative, "-", "") & Result
  472. End Function
  473. ''' <summary>
  474. ''' 计算二阶贝塞尔曲线。
  475. ''' </summary>
  476. 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
  477. If x <= 0 OrElse Double.IsNaN(x) Then Return 0
  478. If x >= 1 Then Return 1
  479. Dim a, b
  480. a = x
  481. Do
  482. b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1)
  483. a += (x - b) * 0.5
  484. Loop Until Math.Abs(b - x) < acc '精度
  485. Return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1)
  486. End Function
  487. ''' <summary>
  488. ''' 将一个数字限制为 0~255 的 Byte 值。
  489. ''' </summary>
  490. Public Function MathByte(d As Double) As Byte
  491. If d < 0 Then d = 0
  492. If d > 255 Then d = 255
  493. Return Math.Round(d)
  494. End Function
  495. ''' <summary>
  496. ''' 提供 MyColor 类型支持的 Math.Round。
  497. ''' </summary>
  498. Public Function MathRound(col As MyColor, Optional w As Integer = 0) As MyColor
  499. 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)}
  500. End Function
  501. ''' <summary>
  502. ''' 获取两数间的百分比。小数点精确到 6 位。
  503. ''' </summary>
  504. ''' <returns></returns>
  505. Public Function MathPercent(ValueA As Double, ValueB As Double, Percent As Double) As Double
  506. Return Math.Round(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决 Double 计算错误
  507. End Function
  508. ''' <summary>
  509. ''' 获取两颜色间的百分比,根据 RGB 计算。小数点精确到 6 位。
  510. ''' </summary>
  511. Public Function MathPercent(ValueA As MyColor, ValueB As MyColor, Percent As Double) As MyColor
  512. Return MathRound(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决Double计算错误
  513. End Function
  514. ''' <summary>
  515. ''' 将数值限定在某个范围内。
  516. ''' </summary>
  517. Public Function MathClamp(value As Double, min As Double, max As Double) As Double
  518. Return Math.Max(min, Math.Min(max, value))
  519. End Function
  520. ''' <summary>
  521. ''' 符号函数。
  522. ''' </summary>
  523. Public Function MathSgn(Value As Double) As Integer
  524. If Value = 0 Then
  525. Return 0
  526. ElseIf Value > 0 Then
  527. Return 1
  528. Else
  529. Return -1
  530. End If
  531. End Function
  532. #End Region
  533. #Region "文件"
  534. '注册表
  535. ''' <summary>
  536. ''' 重命名一个注册表子键。不可用于包含子键的子键。
  537. ''' </summary>
  538. Public Sub RenameReg(parentKey As Microsoft.Win32.RegistryKey, subKeyName As String, newSubKeyName As String)
  539. If parentKey.GetSubKeyNames().Contains(newSubKeyName) Then parentKey.DeleteSubKeyTree(newSubKeyName, False)
  540. Dim SourceKey As Microsoft.Win32.RegistryKey = parentKey.OpenSubKey(subKeyName)
  541. If IsNothing(SourceKey) Then Exit Sub '没有目标项
  542. Dim NewKey As Microsoft.Win32.RegistryKey = parentKey.CreateSubKey(newSubKeyName)
  543. If SourceKey.GetSubKeyNames().Length > 0 Then Throw New NotSupportedException("不支持对包含子键的子键进行重命名:" & SourceKey.GetSubKeyNames()(0) & "。")
  544. For Each valueName As String In SourceKey.GetValueNames()
  545. Dim objValue As Object = SourceKey.GetValue(valueName)
  546. Dim valKind As Microsoft.Win32.RegistryValueKind = SourceKey.GetValueKind(valueName)
  547. NewKey.SetValue(valueName, objValue, valKind)
  548. Next
  549. parentKey.DeleteSubKeyTree(subKeyName, False)
  550. End Sub
  551. ''' <summary>
  552. ''' 读取程序所属注册表。
  553. ''' </summary>
  554. Public Function ReadReg(Key As String, Optional DefaultValue As String = "") As String
  555. Try
  556. Dim parentKey As Microsoft.Win32.RegistryKey, softKey As Microsoft.Win32.RegistryKey
  557. parentKey = My.Computer.Registry.CurrentUser
  558. softKey = parentKey.OpenSubKey("Software\" & RegFolder, True)
  559. If softKey Is Nothing Then
  560. ReadReg = DefaultValue '不存在则返回默认值
  561. Else
  562. Dim readValue As New Text.StringBuilder
  563. readValue.AppendLine(softKey.GetValue(Key))
  564. Dim value = readValue.ToString.Replace(vbCrLf, "") '去除莫名的回车
  565. Return If(value = "", DefaultValue, value) '错误则返回默认值
  566. End If
  567. Catch ex As Exception
  568. Log(ex, "读取注册表出错:" & Key, LogLevel.Hint)
  569. Return DefaultValue
  570. End Try
  571. End Function
  572. ''' <summary>
  573. ''' 写入程序所属注册表。
  574. ''' </summary>
  575. Public Sub WriteReg(Key As String, Value As String, Optional ShowException As Boolean = False)
  576. Try
  577. Dim parentKey As Microsoft.Win32.RegistryKey, softKey As Microsoft.Win32.RegistryKey
  578. parentKey = My.Computer.Registry.CurrentUser
  579. softKey = parentKey.OpenSubKey("Software\" & RegFolder, True)
  580. If softKey Is Nothing Then softKey = parentKey.CreateSubKey("Software\" & RegFolder) '如果不存在就创建
  581. softKey.SetValue(Key, Value)
  582. Catch ex As Exception
  583. Log(ex, "写入注册表出错:" & Key, If(ShowException, LogLevel.Hint, LogLevel.Developer))
  584. If ShowException Then Throw '如果显示错误就丢一个
  585. End Try
  586. End Sub
  587. 'Ini 文件
  588. Private ReadOnly IniCache As New Dictionary(Of String, Dictionary(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 Dictionary(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 Dictionary(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. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  637. ''' <param name="Key">键。</param>
  638. ''' <param name="Value">值。</param>
  639. ''' <remarks></remarks>
  640. Public Sub WriteIni(FileName As String, Key As String, Value As String)
  641. Try
  642. '预处理
  643. Key = Key.Replace(vbCr, "").Replace(vbLf, "").Replace(":", "")
  644. Value = Value.Replace(vbCr, "").Replace(vbLf, "") '允许 Value 中包含冒号
  645. '获取目前文件
  646. Dim Content As Dictionary(Of String, String) = IniGetContent(FileName)
  647. If Content Is Nothing Then Content = New Dictionary(Of String, String)
  648. If Content.ContainsKey(Key) AndAlso Content(Key) = Value Then Exit Sub '如果值一样就不处理
  649. '更新缓存
  650. Content(Key) = Value
  651. '写入文件
  652. Dim FileContent As New StringBuilder
  653. For Each Pair In Content
  654. FileContent.Append(Pair.Key)
  655. FileContent.Append(":")
  656. FileContent.Append(Pair.Value)
  657. FileContent.Append(vbCrLf)
  658. Next
  659. If Not FileName.Contains(":\") Then FileName = $"{Path}PCL\{FileName}.ini"
  660. WriteFile(FileName, FileContent.ToString)
  661. Catch ex As Exception
  662. Log(ex, $"写入文件失败({FileName} -> {Key}:{Value})")
  663. End Try
  664. End Sub
  665. '路径处理
  666. ''' <summary>
  667. ''' 从文件路径或者 Url 获取不包含文件名的路径,或获取文件夹的父文件夹路径。
  668. ''' 取决于原路径格式,路径以 / 或 \ 结尾。
  669. ''' 不包含路径将会抛出异常。
  670. ''' </summary>
  671. Public Function GetPathFromFullPath(FilePath As String) As String
  672. If Not (FilePath.Contains("\") OrElse FilePath.Contains("/")) Then Throw New Exception("不包含路径:" & FilePath)
  673. If FilePath.EndsWithF("\") OrElse FilePath.EndsWithF("/") Then
  674. '是文件夹路径
  675. Dim IsRight As Boolean = FilePath.EndsWithF("\")
  676. FilePath = Left(FilePath, Len(FilePath) - 1)
  677. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"})) & If(IsRight, "\", "/")
  678. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  679. Else
  680. '是文件路径
  681. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"}) + 1)
  682. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  683. End If
  684. End Function
  685. ''' <summary>
  686. ''' 从文件路径或者 Url 获取不包含路径的文件名。不包含文件名将会抛出异常。
  687. ''' </summary>
  688. Public Function GetFileNameFromPath(FilePath As String) As String
  689. FilePath = FilePath.Replace("/", "\")
  690. If FilePath.EndsWithF("\") Then Throw New Exception("不包含文件名:" & FilePath)
  691. If FilePath.Contains("?") Then FilePath = FilePath.Substring(0, FilePath.IndexOfF("?")) '去掉网络参数后的 ?
  692. If FilePath.Contains("\") Then FilePath = FilePath.Substring(FilePath.LastIndexOfF("\") + 1)
  693. Dim length As Integer = FilePath.Length
  694. If length = 0 Then Throw New Exception("不包含文件名:" & FilePath)
  695. If length > 250 Then Throw New PathTooLongException("文件名过长:" & FilePath)
  696. Return FilePath
  697. End Function
  698. ''' <summary>
  699. ''' 从文件路径或者 Url 获取不包含路径与扩展名的文件名。不包含文件名将会抛出异常。
  700. ''' </summary>
  701. Public Function GetFileNameWithoutExtentionFromPath(FilePath As String) As String
  702. Dim Name As String = GetFileNameFromPath(FilePath)
  703. If Name.Contains(".") Then
  704. Return Name.Substring(0, Name.LastIndexOfF("."))
  705. Else
  706. Return Name
  707. End If
  708. End Function
  709. ''' <summary>
  710. ''' 从文件夹路径获取文件夹名。
  711. ''' </summary>
  712. Public Function GetFolderNameFromPath(FolderPath As String) As String
  713. If FolderPath.EndsWithF(":\") OrElse FolderPath.EndsWithF(":\\") Then Return FolderPath.Substring(0, 1)
  714. If FolderPath.EndsWithF("\") OrElse FolderPath.EndsWithF("/") Then FolderPath = Left(FolderPath, FolderPath.Length - 1)
  715. Return GetFileNameFromPath(FolderPath)
  716. End Function
  717. '读取、写入、复制文件
  718. Public Sub CopyFile(FromPath As String, ToPath As String)
  719. Try
  720. '还原文件路径
  721. If Not FromPath.Contains(":\") Then FromPath = Path & FromPath
  722. If Not ToPath.Contains(":\") Then ToPath = Path & ToPath
  723. '如果复制同一个文件则跳过
  724. If FromPath = ToPath Then Exit Sub
  725. '确保目录存在
  726. Directory.CreateDirectory(GetPathFromFullPath(ToPath))
  727. '复制文件
  728. File.Copy(FromPath, ToPath, True)
  729. Catch ex As Exception
  730. Throw New Exception("复制文件出错:" & FromPath & " → " & ToPath, ex)
  731. End Try
  732. End Sub
  733. ''' <summary>
  734. ''' 读取文件,如果失败则返回空字符串。
  735. ''' </summary>
  736. ''' <param name="FilePath">文件完整或相对路径。</param>
  737. Public Function ReadFile(FilePath As String, Optional Encoding As Encoding = Nothing) As String
  738. Try
  739. '还原文件路径
  740. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  741. If File.Exists(FilePath) Then
  742. Dim FileBytes As Byte()
  743. Using ReadStream As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) '支持读取使用中的文件
  744. ReDim FileBytes(ReadStream.Length - 1)
  745. ReadStream.Read(FileBytes, 0, ReadStream.Length)
  746. End Using
  747. ReadFile = If(Encoding Is Nothing, DecodeBytes(FileBytes), Encoding.GetString(FileBytes))
  748. Else
  749. Log("[System] 欲读取的文件不存在,已返回空字符串:" & FilePath)
  750. Return ""
  751. End If
  752. Catch ex As Exception
  753. Log(ex, "读取文件出错:" & FilePath)
  754. Return ""
  755. End Try
  756. End Function
  757. ''' <summary>
  758. ''' 读取流中的所有文本。
  759. ''' </summary>
  760. Public Function ReadFile(Stream As Stream, Optional Encoding As Encoding = Nothing) As String
  761. Try
  762. Dim srcBuf As Byte() = New Byte(16384) {}
  763. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  764. Dim Result As New List(Of Byte)
  765. While DataCount > 0
  766. If DataCount > 0 Then Result.AddRange(srcBuf.ToList.GetRange(0, DataCount))
  767. DataCount = Stream.Read(srcBuf, 0, 16384)
  768. End While
  769. Dim Bts = Result.ToArray
  770. Return If(Encoding, GetEncoding(Bts)).GetString(Bts)
  771. Catch ex As Exception
  772. Log(ex, "读取流出错")
  773. Return ""
  774. End Try
  775. End Function
  776. ''' <summary>
  777. ''' 写入文件。
  778. ''' </summary>
  779. ''' <param name="FilePath">文件完整或相对路径。</param>
  780. ''' <param name="Text">文件内容。</param>
  781. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  782. Public Function WriteFile(FilePath As String, Text As String, Optional Append As Boolean = False, Optional Encoding As Encoding = Nothing) As Boolean
  783. Try
  784. '还原文件路径
  785. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  786. '确保目录存在
  787. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  788. '写入文件
  789. If File.Exists(FilePath) Then
  790. '如果文件存在,刷新目前文件
  791. Using writer As New StreamWriter(FilePath, Append, If(Encoding, GetEncoding(FilePath)))
  792. writer.Write(Text)
  793. writer.Flush()
  794. writer.Close()
  795. End Using
  796. Else
  797. '如果文件不存在,则新建并写入
  798. File.WriteAllText(FilePath, Text, If(Encoding, New UTF8Encoding(False)))
  799. End If
  800. Return True
  801. Catch ex As Exception
  802. Log(ex, "写入文件时出错:" & FilePath)
  803. Return False
  804. End Try
  805. End Function
  806. ''' <summary>
  807. ''' 写入文件。
  808. ''' </summary>
  809. ''' <param name="FilePath">文件完整或相对路径。</param>
  810. ''' <param name="Content">文件内容。</param>
  811. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  812. Public Function WriteFile(FilePath As String, Content As Byte(), Optional Append As Boolean = False) As Boolean
  813. Try
  814. '还原文件路径
  815. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  816. '确保目录存在
  817. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  818. '写入文件
  819. File.WriteAllBytes(FilePath, Content)
  820. Return True
  821. Catch ex As Exception
  822. Log(ex, "写入文件时出错:" & FilePath)
  823. Return False
  824. End Try
  825. End Function
  826. ''' <summary>
  827. ''' 将流写入文件。
  828. ''' </summary>
  829. ''' <param name="FilePath">文件完整或相对路径。</param>
  830. Public Function WriteFile(FilePath As String, Stream As Stream) As Boolean
  831. Try
  832. '还原文件路径
  833. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  834. '确保目录存在
  835. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  836. '读取流
  837. Using fs As New FileStream(FilePath, FileMode.Create, FileAccess.Write)
  838. Dim srcBuf As Byte() = New Byte(16384) {}
  839. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  840. While DataCount > 0
  841. If DataCount > 0 Then fs.Write(srcBuf, 0, DataCount)
  842. DataCount = Stream.Read(srcBuf, 0, 16384)
  843. End While
  844. fs.Close()
  845. End Using
  846. Return True
  847. Catch ex As Exception
  848. Log(ex, "保存流出错")
  849. Return False
  850. End Try
  851. End Function
  852. '文件编码
  853. ''' <summary>
  854. ''' 获取文件编码。
  855. ''' </summary>
  856. ''' <param name="FilePath">文件完整或相对路径。</param>
  857. Public Function GetEncoding(FilePath As String) As Encoding
  858. '还原文件路径
  859. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  860. '获取编码
  861. GetEncoding = GetEncoding(File.ReadAllBytes(FilePath))
  862. End Function
  863. ''' <summary>
  864. ''' 获取 Bytes 的编码。
  865. ''' </summary>
  866. Public Function GetEncoding(Bytes As Byte()) As Encoding
  867. Dim Length As Integer = Bytes.Count
  868. If Length <= 2 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 SelectAs(Title As String, FileName As String, Optional FileFilter As String = Nothing, Optional DefaultDir 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 DefaultDir IsNot Nothing Then fileDialog.InitialDirectory = DefaultDir
  934. fileDialog.ShowDialog()
  935. SelectAs = If(fileDialog.FileName.Contains(":\"), fileDialog.FileName, "")
  936. Log("[UI] 选择文件返回:" & SelectAs)
  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) 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. fileDialog.ShowDialog()
  954. SelectFile = fileDialog.FileName
  955. Log("[UI] 选择文件返回:" & SelectFile)
  956. End Using
  957. End Function
  958. ''' <summary>
  959. ''' 弹出选取文件夹对话框并且要求选取文件夹。如果没有选择就返回空字符串。
  960. ''' </summary>
  961. Public Function SelectFolder(Optional Title As String = "选择文件夹") As String
  962. Dim folderDialog As New Ookii.Dialogs.Wpf.VistaFolderBrowserDialog With {.ShowNewFolderButton = True, .RootFolder = Environment.SpecialFolder.Desktop, .Description = Title, .UseDescriptionForTitle = True}
  963. folderDialog.ShowDialog()
  964. SelectFolder = If(String.IsNullOrEmpty(folderDialog.SelectedPath), "", folderDialog.SelectedPath & If(folderDialog.SelectedPath.EndsWithF("\"), "", "\"))
  965. Log("[UI] 选择文件夹返回:" & SelectFolder)
  966. End Function
  967. '文件校验
  968. ''' <summary>
  969. ''' 检查是否拥有某一文件夹的 I/O 权限。如果文件夹不存在,会返回 False。
  970. ''' </summary>
  971. Public Function CheckPermission(Path As String) As Boolean
  972. Try
  973. If String.IsNullOrEmpty(Path) Then Return False
  974. If Not Path.EndsWithF("\") Then Path += "\"
  975. If Path.EndsWithF(":\System Volume Information\") OrElse Path.EndsWithF(":\$RECYCLE.BIN\") Then Return False
  976. If Not Directory.Exists(Path) Then Return False
  977. Dim FileName As String = "CheckPermission" & GetUuid()
  978. If File.Exists(Path & FileName) Then File.Delete(Path & FileName)
  979. File.Create(Path & FileName).Dispose()
  980. File.Delete(Path & FileName)
  981. Return True
  982. Catch ex As Exception
  983. Log(ex, "没有对文件夹 " & Path & " 的权限,请尝试以管理员权限运行 PCL")
  984. Return False
  985. End Try
  986. End Function
  987. ''' <summary>
  988. ''' 检查是否拥有某一文件夹的 I/O 权限。如果出错,则抛出异常。
  989. ''' </summary>
  990. Public Sub CheckPermissionWithException(Path As String)
  991. If String.IsNullOrWhiteSpace(Path) Then Throw New ArgumentNullException("文件夹名不能为空!")
  992. If Not Path.EndsWithF("\") Then Path += "\"
  993. If Not Directory.Exists(Path) Then Throw New DirectoryNotFoundException("文件夹不存在!")
  994. If File.Exists(Path & "CheckPermission") Then File.Delete(Path & "CheckPermission")
  995. File.Create(Path & "CheckPermission").Dispose()
  996. File.Delete(Path & "CheckPermission")
  997. End Sub
  998. ''' <summary>
  999. ''' 获取文件 MD5,若失败则返回空字符串。
  1000. ''' </summary>
  1001. Public Function GetFileMD5(FilePath As String) As String
  1002. Dim Retry As Boolean = False
  1003. Re:
  1004. Try
  1005. '获取 MD5
  1006. Dim Result As New StringBuilder()
  1007. Dim File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1008. Dim MD5 As MD5 = New MD5CryptoServiceProvider()
  1009. Dim Retval As Byte() = MD5.ComputeHash(File)
  1010. File.Close()
  1011. For i = 0 To Retval.Length - 1
  1012. Result.Append(Retval(i).ToString("x2"))
  1013. Next
  1014. Return Result.ToString
  1015. Catch ex As Exception
  1016. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1017. Log(ex, "获取文件 MD5 失败:" & FilePath)
  1018. Return ""
  1019. Else
  1020. Retry = True
  1021. Log(ex, "获取文件 MD5 可重试失败:" & FilePath, LogLevel.Normal)
  1022. Thread.Sleep(RandomInteger(200, 500))
  1023. GoTo Re
  1024. End If
  1025. End Try
  1026. End Function
  1027. ''' <summary>
  1028. ''' 获取文件 SHA256,若失败则返回空字符串。
  1029. ''' </summary>
  1030. Public Function GetFileSHA256(FilePath As String) As String
  1031. Dim Retry As Boolean = False
  1032. Re:
  1033. Try
  1034. ''检测该文件是否在下载中,若在下载则放弃检测
  1035. 'If IgnoreOnDownloading AndAlso NetManage.Files.ContainsKey(FilePath) AndAlso NetManage.Files(FilePath).State <= NetState.Merge Then Return ""
  1036. '获取 SHA256
  1037. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1038. Dim sha1 As SHA256 = New SHA256CryptoServiceProvider()
  1039. Dim retval As Byte() = sha1.ComputeHash(file)
  1040. file.Close()
  1041. Dim Result As New StringBuilder()
  1042. For i As Integer = 0 To retval.Length - 1
  1043. Result.Append(retval(i).ToString("x2"))
  1044. Next
  1045. Return Result.ToString
  1046. Catch ex As Exception
  1047. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1048. Log(ex, "获取文件 SHA256 失败:" & FilePath)
  1049. Return ""
  1050. Else
  1051. Retry = True
  1052. Log(ex, "获取文件 SHA256 可重试失败:" & FilePath, LogLevel.Normal)
  1053. Thread.Sleep(RandomInteger(200, 500))
  1054. GoTo Re
  1055. End If
  1056. End Try
  1057. End Function
  1058. ''' <summary>
  1059. ''' 获取文件 SHA1,若失败则返回空字符串。
  1060. ''' </summary>
  1061. Public Function GetFileSHA1(FilePath As String) As String
  1062. Dim Retry As Boolean = False
  1063. Re:
  1064. Try
  1065. '获取 SHA1
  1066. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1067. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1068. Dim retval As Byte() = sha1.ComputeHash(file)
  1069. file.Close()
  1070. Dim Result As New StringBuilder()
  1071. For i As Integer = 0 To retval.Length - 1
  1072. Result.Append(retval(i).ToString("x2"))
  1073. Next
  1074. Return Result.ToString
  1075. Catch ex As Exception
  1076. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1077. Log(ex, "获取文件 SHA1 失败:" & FilePath)
  1078. Return ""
  1079. Else
  1080. Retry = True
  1081. Log(ex, "获取文件 SHA1 可重试失败:" & FilePath, LogLevel.Normal)
  1082. Thread.Sleep(RandomInteger(200, 500))
  1083. GoTo Re
  1084. End If
  1085. End Try
  1086. End Function
  1087. ''' <summary>
  1088. ''' 获取流 SHA1,若失败则返回空字符串。
  1089. ''' </summary>
  1090. Public Function GetAuthSHA1(Stream As Stream) As String
  1091. Try
  1092. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1093. Dim retval As Byte() = sha1.ComputeHash(Stream)
  1094. Dim Result As New StringBuilder()
  1095. For i As Integer = 0 To retval.Length - 1
  1096. Result.Append(retval(i).ToString("x2"))
  1097. Next
  1098. Return Result.ToString
  1099. Catch ex As Exception
  1100. Log(ex, "获取流 SHA1 失败")
  1101. Return ""
  1102. End Try
  1103. End Function
  1104. ''' <summary>
  1105. ''' 文件的校验规则。
  1106. ''' </summary>
  1107. Public Class FileChecker
  1108. ''' <summary>
  1109. ''' 文件的准确大小。
  1110. ''' </summary>
  1111. Public ActualSize As Long = -1
  1112. ''' <summary>
  1113. ''' 文件的最小大小。
  1114. ''' </summary>
  1115. Public MinSize As Long = -1
  1116. ''' <summary>
  1117. ''' 文件的 MD5、SHA1 或 SHA256。会根据输入字符串的长度自动判断种类。
  1118. ''' </summary>
  1119. Public Hash As String = Nothing
  1120. ''' <summary>
  1121. ''' 是否可以使用已经存在的文件。
  1122. ''' </summary>
  1123. Public CanUseExistsFile As Boolean = True
  1124. ''' <summary>
  1125. ''' 是否为 Json 文件。
  1126. ''' </summary>
  1127. Public IsJson As Boolean = False
  1128. 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)
  1129. Me.ActualSize = ActualSize
  1130. Me.MinSize = MinSize
  1131. Me.Hash = Hash
  1132. Me.CanUseExistsFile = CanUseExistsFile
  1133. Me.IsJson = IsJson
  1134. End Sub
  1135. ''' <summary>
  1136. ''' 检查文件。若成功则返回 Nothing,失败则返回错误的描述文本,描述文本不以句号结尾。不会抛出错误。
  1137. ''' </summary>
  1138. Public Function Check(LocalPath As String) As String
  1139. Try
  1140. Dim Info As New FileInfo(LocalPath)
  1141. If Not Info.Exists Then Return "文件不存在:" & LocalPath
  1142. Dim FileSize As Long = Info.Length
  1143. If ActualSize >= 0 AndAlso ActualSize <> FileSize Then Return "文件大小应为 " & ActualSize & " B,实际为 " & FileSize & " B"
  1144. If MinSize >= 0 AndAlso MinSize > FileSize Then Return "文件大小应大于 " & MinSize & " B,实际为 " & FileSize & " B"
  1145. If Not String.IsNullOrEmpty(Hash) Then
  1146. If Hash.Length < 35 Then 'MD5
  1147. If Hash.ToLowerInvariant <> GetFileMD5(LocalPath) Then Return "文件 MD5 应为 " & Hash & ",实际为 " & GetFileMD5(LocalPath)
  1148. ElseIf Hash.Length = 64 Then 'SHA256
  1149. If Hash.ToLowerInvariant <> GetFileSHA256(LocalPath) Then Return "文件 SHA256 应为 " & Hash & ",实际为 " & GetFileSHA256(LocalPath)
  1150. Else 'SHA1 (40)
  1151. If Hash.ToLowerInvariant <> GetFileSHA1(LocalPath) Then Return "文件 SHA1 应为 " & Hash & ",实际为 " & GetFileSHA1(LocalPath)
  1152. End If
  1153. End If
  1154. If IsJson Then
  1155. Dim Content As String = ReadFile(LocalPath)
  1156. If Content = "" Then Throw New Exception("读取到的文件为空")
  1157. Try
  1158. GetJson(Content)
  1159. Catch ex As Exception
  1160. Throw New Exception("不是有效的 json 文件", ex)
  1161. End Try
  1162. End If
  1163. Return Nothing
  1164. Catch ex As Exception
  1165. Log(ex, "检查文件出错")
  1166. Return GetExceptionSummary(ex)
  1167. End Try
  1168. End Function
  1169. End Class
  1170. ''' <summary>
  1171. ''' 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  1172. ''' 会尝试创建,但不会清空目标文件夹。
  1173. ''' </summary>
  1174. Public Sub ExtractFile(CompressFilePath As String, DestDirectory As String, Optional Encode As Encoding = Nothing)
  1175. Directory.CreateDirectory(DestDirectory)
  1176. If CompressFilePath.EndsWithF(".gz", True) Then
  1177. '以 gz 方式解压
  1178. Dim stream As New GZipStream(New FileStream(CompressFilePath, FileMode.Open, FileAccess.ReadWrite), CompressionMode.Decompress)
  1179. Dim decompressedFile As New FileStream(DestDirectory & GetFileNameFromPath(CompressFilePath).ToLower.Replace(".tar", "").Replace(".gz", ""), FileMode.OpenOrCreate, FileAccess.Write)
  1180. Dim data As Integer = stream.ReadByte()
  1181. While data <> -1
  1182. decompressedFile.WriteByte(data)
  1183. data = stream.ReadByte()
  1184. End While
  1185. decompressedFile.Close()
  1186. stream.Close()
  1187. Else
  1188. '以 zip 方式解压
  1189. Using Archive = ZipFile.Open(CompressFilePath, ZipArchiveMode.Read, If(Encode, Encoding.GetEncoding("GB18030")))
  1190. For Each Entry As ZipArchiveEntry In Archive.Entries
  1191. Dim DestinationPath As String = IO.Path.Combine(DestDirectory, Entry.FullName)
  1192. If DestinationPath.EndsWithF("\") OrElse DestinationPath.EndsWithF("/") Then
  1193. Continue For '不创建空文件夹
  1194. Else
  1195. Directory.CreateDirectory(GetPathFromFullPath(DestinationPath))
  1196. Entry.ExtractToFile(DestinationPath, True)
  1197. End If
  1198. Next
  1199. End Using
  1200. End If
  1201. End Sub
  1202. ''' <summary>
  1203. ''' 删除文件夹,返回删除的文件个数。通过参数选择是否抛出异常。
  1204. ''' </summary>
  1205. Public Function DeleteDirectory(Path As String, Optional IgnoreIssue As Boolean = False) As Integer
  1206. If Not Directory.Exists(Path) Then Return 0
  1207. Dim DeletedCount As Integer = 0
  1208. Dim Temp As String()
  1209. Temp = Directory.GetFiles(Path)
  1210. For Each FilePath As String In Temp
  1211. Dim RetriedFile As Boolean = False
  1212. RetryFile:
  1213. Try
  1214. File.Delete(FilePath)
  1215. DeletedCount += 1
  1216. Catch ex As Exception
  1217. If Not RetriedFile Then
  1218. RetriedFile = True
  1219. Log(ex, $"删除文件失败,将在 0.3s 后重试({FilePath})")
  1220. Thread.Sleep(300)
  1221. GoTo RetryFile
  1222. ElseIf IgnoreIssue Then
  1223. Log(ex, "删除单个文件可忽略地失败")
  1224. Else
  1225. Throw
  1226. End If
  1227. End Try
  1228. Next
  1229. Temp = Directory.GetDirectories(Path)
  1230. For Each str As String In Temp
  1231. DeleteDirectory(str, IgnoreIssue)
  1232. Next
  1233. Dim RetriedDir As Boolean = False
  1234. RetryDir:
  1235. Try
  1236. Directory.Delete(Path, True)
  1237. Catch ex As Exception
  1238. If Not RetriedDir Then
  1239. RetriedDir = True
  1240. Log(ex, $"删除文件夹失败,将在 0.3s 后重试({Path})")
  1241. Thread.Sleep(300)
  1242. GoTo RetryDir
  1243. ElseIf IgnoreIssue Then
  1244. Log(ex, "删除单个文件夹可忽略地失败")
  1245. Else
  1246. Throw
  1247. End If
  1248. End Try
  1249. Return DeletedCount
  1250. End Function
  1251. ''' <summary>
  1252. ''' 复制文件夹,失败会抛出异常。
  1253. ''' </summary>
  1254. Public Sub CopyDirectory(FromPath As String, ToPath As String)
  1255. FromPath = FromPath.Replace("/", "\")
  1256. If Not FromPath.EndsWithF("\") Then FromPath &= "\"
  1257. ToPath = ToPath.Replace("/", "\")
  1258. If Not ToPath.EndsWithF("\") Then ToPath &= "\"
  1259. For Each File In EnumerateFiles(FromPath)
  1260. CopyFile(File.FullName, File.FullName.Replace(FromPath, ToPath))
  1261. Next
  1262. End Sub
  1263. ''' <summary>
  1264. ''' 遍历文件夹中的所有文件。
  1265. ''' </summary>
  1266. Public Function EnumerateFiles(Directory As String) As IEnumerable(Of FileInfo)
  1267. Dim Info As New DirectoryInfo(Directory)
  1268. If Not Info.Exists Then Return New List(Of FileInfo)
  1269. Return Info.EnumerateFiles("*", SearchOption.AllDirectories)
  1270. End Function
  1271. #End Region
  1272. #Region "文本"
  1273. Public vbLQ As Char = Convert.ToChar(8220)
  1274. Public vbRQ As Char = Convert.ToChar(8221)
  1275. ''' <summary>
  1276. ''' 提取 Exception 的具体描述与堆栈。
  1277. ''' </summary>
  1278. ''' <param name="ShowAllTrace">是否必须显示所有堆栈。通常用于判定堆栈信息。</param>
  1279. Public Function GetExceptionDetail(Ex As Exception, Optional ShowAllTrace As Boolean = False) As String
  1280. If Ex Is Nothing Then Return "无可用错误信息!"
  1281. '获取最底层的异常
  1282. Dim InnerEx As Exception = Ex
  1283. Do Until InnerEx.InnerException Is Nothing
  1284. InnerEx = InnerEx.InnerException
  1285. Loop
  1286. '获取各级错误的描述与堆栈信息
  1287. Dim DescList As New List(Of String)
  1288. Dim StackList As New List(Of String)
  1289. Do Until Ex Is Nothing
  1290. DescList.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, vbCrLf))
  1291. If Ex.StackTrace IsNot Nothing Then
  1292. For Each St As String In Ex.StackTrace.Split(vbCrLf)
  1293. If ShowAllTrace OrElse St.ToLower.Contains("pcl") Then StackList.Add(St.Replace(vbCr, String.Empty).Replace(vbLf, String.Empty))
  1294. Next
  1295. End If
  1296. Ex = Ex.InnerException
  1297. Loop
  1298. DescList = DescList.Distinct.ToList
  1299. Dim Desc As String = Join(DescList, vbCrLf & "→ ")
  1300. Dim Stack As String = If(StackList.Any, vbCrLf & Join(StackList, vbCrLf), "")
  1301. '常见错误(记得同时修改下面的)
  1302. Dim CommonReason As String = Nothing
  1303. If TypeOf InnerEx Is TypeLoadException OrElse TypeOf InnerEx Is MissingMethodException OrElse TypeOf InnerEx Is NotImplementedException OrElse TypeOf InnerEx Is TypeInitializationException Then
  1304. CommonReason = "PCL 的运行环境存在问题。请尝试重新安装 .NET Framework 4.6.2 然后再试。"
  1305. ElseIf TypeOf InnerEx Is UnauthorizedAccessException Then
  1306. CommonReason = "PCL 的权限不足。请尝试右键 PCL,选择以管理员身份运行。"
  1307. ElseIf TypeOf InnerEx Is OutOfMemoryException Then
  1308. CommonReason = "你的电脑运行内存不足,导致 PCL 无法继续运行。请在关闭一部分不需要的程序后再试。"
  1309. ElseIf TypeOf InnerEx Is Runtime.InteropServices.COMException Then
  1310. CommonReason = "由于操作系统或显卡存在问题,导致出现错误。请尝试重启 PCL。"
  1311. ElseIf {"远程主机强迫关闭了", "远程方已关闭传输流", "未能解析此远程名称", "由于目标计算机积极拒绝",
  1312. "操作已超时", "操作超时", "服务器超时", "连接超时"}.Any(Function(s) Desc.Contains(s)) Then
  1313. CommonReason = "你的网络环境不佳,导致难以连接到服务器。请检查网络,多重试几次,或尝试使用 VPN。"
  1314. End If
  1315. '获取错误类型
  1316. Dim TypeDesc As String = If(InnerEx.GetType.FullName = "System.Exception", "", vbCrLf & "错误类型:" & InnerEx.GetType.FullName)
  1317. '构造输出信息
  1318. If CommonReason Is Nothing Then
  1319. Return Desc & Stack & TypeDesc
  1320. Else
  1321. Dim Result As String = DescList.First & vbCrLf & CommonReason & vbCrLf & "————————————" & vbCrLf
  1322. DescList(0) = "详细错误信息:"
  1323. Return Result & Join(DescList, vbCrLf & "→ ") & Stack & TypeDesc
  1324. End If
  1325. End Function
  1326. ''' <summary>
  1327. ''' 提取 Exception 描述,汇总到一行。
  1328. ''' </summary>
  1329. Public Function GetExceptionSummary(Ex As Exception) As String
  1330. If Ex Is Nothing Then Return "无可用错误信息!"
  1331. '获取最底层的异常
  1332. Dim InnerEx As Exception = Ex
  1333. Do Until InnerEx.InnerException Is Nothing
  1334. InnerEx = InnerEx.InnerException
  1335. Loop
  1336. '获取各级错误的描述
  1337. Dim DescList As New List(Of String)
  1338. Do Until Ex Is Nothing
  1339. DescList.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, " "))
  1340. Ex = Ex.InnerException
  1341. Loop
  1342. DescList = DescList.Distinct.ToList
  1343. Dim Desc As String = Join(DescList, vbCrLf & "→ ")
  1344. '常见错误(记得同时修改上面的)
  1345. Dim CommonReason As String = Nothing
  1346. If TypeOf InnerEx Is TypeLoadException OrElse TypeOf InnerEx Is MissingMethodException OrElse TypeOf InnerEx Is NotImplementedException OrElse TypeOf InnerEx Is TypeInitializationException Then
  1347. CommonReason = "PCL 的运行环境存在问题。请尝试重新安装 .NET Framework 4.6.2 然后再试。"
  1348. ElseIf TypeOf InnerEx Is UnauthorizedAccessException Then
  1349. CommonReason = "PCL 的权限不足。请尝试右键 PCL,选择以管理员身份运行。"
  1350. ElseIf TypeOf InnerEx Is OutOfMemoryException Then
  1351. CommonReason = "你的电脑运行内存不足,导致 PCL 无法继续运行。请在关闭一部分不需要的程序后再试。"
  1352. ElseIf TypeOf InnerEx Is Runtime.InteropServices.COMException Then
  1353. CommonReason = "由于操作系统或显卡存在问题,导致出现错误。请尝试重启 PCL。"
  1354. ElseIf {"远程主机强迫关闭了", "远程方已关闭传输流", "未能解析此远程名称", "由于目标计算机积极拒绝",
  1355. "操作已超时", "操作超时", "服务器超时", "连接超时"}.Any(Function(s) Desc.Contains(s)) Then
  1356. CommonReason = "你的网络环境不佳,导致难以连接到服务器。请检查网络,多重试几次,或尝试使用 VPN。"
  1357. End If
  1358. '构造输出信息
  1359. If CommonReason IsNot Nothing Then
  1360. Return DescList.First & ":" & CommonReason
  1361. Else
  1362. DescList.Reverse() '让最深层错误在最左边
  1363. Return Join(DescList, " → ")
  1364. End If
  1365. End Function
  1366. ''' <summary>
  1367. ''' 返回一个枚举对应的字符串。
  1368. ''' </summary>
  1369. ''' <param name="EnumData">一个已经实例化的枚举类型。</param>
  1370. Public Function GetStringFromEnum(EnumData As [Enum]) As String
  1371. Return [Enum].GetName(EnumData.GetType, EnumData)
  1372. End Function
  1373. ''' <summary>
  1374. ''' 将文件大小转化为适合的文本形式,如“1.28 M”。
  1375. ''' </summary>
  1376. ''' <param name="FileSize">以字节为单位的大小表示。</param>
  1377. Public Function GetString(FileSize As Long) As String
  1378. Dim IsNegative = FileSize < 0
  1379. If IsNegative Then FileSize *= -1
  1380. If FileSize < 1000 Then
  1381. 'B 级
  1382. Return If(IsNegative, "-", "") & FileSize & " B"
  1383. ElseIf FileSize < 1024 * 1000 Then
  1384. 'K 级
  1385. Dim RoundResult As String = Math.Round(FileSize / 1024)
  1386. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " K"
  1387. ElseIf FileSize < 1024 * 1024 * 1000 Then
  1388. 'M 级
  1389. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024)
  1390. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024 / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " M"
  1391. Else
  1392. 'G 级
  1393. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024 / 1024)
  1394. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024 / 1024 / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " G"
  1395. End If
  1396. End Function
  1397. ''' <summary>
  1398. ''' 获取 Json 对象。
  1399. ''' </summary>
  1400. Public Function GetJson(Data As String)
  1401. Try
  1402. Return JsonConvert.DeserializeObject(Data, New JsonSerializerSettings With {.DateTimeZoneHandling = DateTimeZoneHandling.Local})
  1403. Catch ex As Exception
  1404. Dim Length As Integer = If(Data, "").Length
  1405. Throw New Exception("格式化 json 对象失败:" & If(Length > 10000, Data.Substring(0, 100) & $"...(全长 {Length} 个字符)..." & Right(Data, 100), Data))
  1406. End Try
  1407. End Function
  1408. ''' <summary>
  1409. ''' 将第一个字符转换为大写,其余字符转换为小写。
  1410. ''' </summary>
  1411. <Extension> Public Function Capitalize(word As String) As String
  1412. If String.IsNullOrEmpty(word) Then Return word
  1413. Return word.Substring(0, 1).ToUpperInvariant() & word.Substring(1).ToLowerInvariant()
  1414. End Function
  1415. ''' <summary>
  1416. ''' 将字符串统一至某个长度,过短则以 Code 将其右侧填充,过长则截取靠左的指定长度。
  1417. ''' </summary>
  1418. Public Function StrFill(Str As String, Code As String, Length As Byte) As String
  1419. If Str.Length > Length Then Return Mid(Str, 1, Length)
  1420. Return Mid(Str.PadRight(Length, Code), Str.Length + 1) & Str
  1421. End Function
  1422. ''' <summary>
  1423. ''' 将一个小数显示为固定的小数点后位数形式,将向零取整。
  1424. ''' 如 12 保留 2 位则输出 12.00,而 95.678 保留 2 位则输出 95.67。
  1425. ''' </summary>
  1426. Public Function StrFillNum(Num As Double, Length As Integer) As String
  1427. Num = Math.Round(Num, Length, MidpointRounding.AwayFromZero)
  1428. StrFillNum = Num
  1429. If Not StrFillNum.Contains(".") Then Return (StrFillNum & ".").PadRight(StrFillNum.Length + 1 + Length, "0")
  1430. Return StrFillNum.PadRight(StrFillNum.Split(".")(0).Length + 1 + Length, "0")
  1431. End Function
  1432. ''' <summary>
  1433. ''' 移除字符串首尾的标点符号、回车,以及括号中、冒号后的补充说明内容。
  1434. ''' </summary>
  1435. Public Function StrTrim(Str As String, Optional RemoveQuote As Boolean = True)
  1436. If RemoveQuote Then Str = Str.Split("(")(0).Split(":")(0).Split("(")(0).Split(":")(0)
  1437. Return Str.Trim(".", "。", "!", " ", "!", "?", "?", vbCr, vbLf)
  1438. End Function
  1439. ''' <summary>
  1440. ''' 连接字符串。
  1441. ''' </summary>
  1442. <Extension> Public Function Join(List As IEnumerable, Split As String) As String
  1443. Dim Builder As New StringBuilder
  1444. Dim IsFirst As Boolean = True
  1445. For Each Element In List
  1446. If IsFirst Then
  1447. IsFirst = False
  1448. Else
  1449. Builder.Append(Split)
  1450. End If
  1451. If Element IsNot Nothing Then Builder.Append(Element)
  1452. Next
  1453. Return Builder.ToString
  1454. End Function
  1455. ''' <summary>
  1456. ''' 分割字符串。
  1457. ''' </summary>
  1458. <Extension> Public Function Split(FullStr As String, SplitStr As String) As String()
  1459. If SplitStr.Length = 1 Then
  1460. Return FullStr.Split(SplitStr(0))
  1461. Else
  1462. Return FullStr.Split({SplitStr}, StringSplitOptions.None)
  1463. End If
  1464. End Function
  1465. ''' <summary>
  1466. ''' 获取字符串哈希值。
  1467. ''' </summary>
  1468. Public Function GetHash(Str As String) As ULong
  1469. GetHash = 5381
  1470. For i = 0 To Str.Length - 1
  1471. GetHash = (GetHash << 5) Xor GetHash Xor CType(AscW(Str(i)), ULong)
  1472. Next
  1473. Return GetHash Xor &HA98F501BC684032FUL
  1474. End Function
  1475. ''' <summary>
  1476. ''' 获取字符串 MD5。
  1477. ''' </summary>
  1478. Public Function GetStringMD5(Str As String) As String
  1479. Dim md5Hasher As New MD5CryptoServiceProvider
  1480. Dim hashedDataBytes As Byte()
  1481. hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(Str))
  1482. Dim tmp As New StringBuilder()
  1483. For Each i As Byte In hashedDataBytes
  1484. tmp.Append(i.ToString("x2"))
  1485. Next
  1486. Return tmp.ToString()
  1487. End Function
  1488. ''' <summary>
  1489. ''' 检查字符串中的字符是否均为 ASCII 字符。
  1490. ''' </summary>
  1491. <Extension> Public Function IsASCII(Input As String) As Boolean
  1492. Return Input.All(Function(c) AscW(c) < 128)
  1493. End Function
  1494. ''' <summary>
  1495. ''' 获取在子字符串之前的部分。
  1496. ''' 会裁切尽可能多的内容,但如果未找到子字符串则不裁切。
  1497. ''' </summary>
  1498. <Extension> Public Function Before(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1499. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.IndexOfF(Text, IgnoreCase))
  1500. If Pos >= 0 Then
  1501. Return Str.Substring(0, Pos)
  1502. Else
  1503. Return Str
  1504. End If
  1505. End Function
  1506. ''' <summary>
  1507. ''' 获取在子字符串之后的部分。
  1508. ''' 会裁切尽可能多的内容,但如果未找到子字符串则不裁切。
  1509. ''' </summary>
  1510. <Extension> Public Function After(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1511. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.LastIndexOfF(Text, IgnoreCase))
  1512. If Pos >= 0 Then
  1513. Return Str.Substring(Pos + Text.Length)
  1514. Else
  1515. Return Str
  1516. End If
  1517. End Function
  1518. ''' <summary>
  1519. ''' 获取处于两个子字符串之间的部分。
  1520. ''' 会裁切尽可能多的内容:匹配开始使用 LastIndexOf,匹配结束使用 IndexOf,但如果未找到子字符串则不裁切。
  1521. ''' </summary>
  1522. <Extension> Public Function Between(Str As String, After As String, Before As String, Optional IgnoreCase As Boolean = False) As String
  1523. Dim StartPos As Integer = If(String.IsNullOrEmpty(After), -1, Str.LastIndexOfF(After, IgnoreCase))
  1524. If StartPos >= 0 Then
  1525. StartPos += After.Length
  1526. Else
  1527. StartPos = 0
  1528. End If
  1529. Dim EndPos As Integer = If(String.IsNullOrEmpty(Before), -1, Str.IndexOfF(Before, StartPos, IgnoreCase))
  1530. If EndPos >= 0 Then
  1531. Return Str.Substring(StartPos, EndPos - StartPos)
  1532. ElseIf StartPos > 0 Then
  1533. Return Str.Substring(StartPos)
  1534. Else
  1535. Return Str
  1536. End If
  1537. End Function
  1538. ''' <summary>
  1539. ''' 高速的 StartsWith。
  1540. ''' </summary>
  1541. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1542. Public Function StartsWithF(Str As String, Prefix As String, Optional IgnoreCase As Boolean = False) As Boolean
  1543. Return Str.StartsWith(Prefix, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1544. End Function
  1545. ''' <summary>
  1546. ''' 高速的 EndsWith。
  1547. ''' </summary>
  1548. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1549. Public Function EndsWithF(Str As String, Suffix As String, Optional IgnoreCase As Boolean = False) As Boolean
  1550. Return Str.EndsWith(Suffix, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1551. End Function
  1552. ''' <summary>
  1553. ''' 支持可变大小写判断的 Contains。
  1554. ''' </summary>
  1555. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1556. Public Function ContainsF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Boolean
  1557. Return Str.IndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal)) >= 0
  1558. End Function
  1559. ''' <summary>
  1560. ''' 高速的 IndexOf。
  1561. ''' </summary>
  1562. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1563. Public Function IndexOfF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Integer
  1564. Return Str.IndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1565. End Function
  1566. ''' <summary>
  1567. ''' 高速的 IndexOf。
  1568. ''' </summary>
  1569. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1570. Public Function IndexOfF(Str As String, SubStr As String, StartIndex As Integer, Optional IgnoreCase As Boolean = False) As Integer
  1571. Return Str.IndexOf(SubStr, StartIndex, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1572. End Function
  1573. ''' <summary>
  1574. ''' 高速的 LastIndexOf。
  1575. ''' </summary>
  1576. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1577. Public Function LastIndexOfF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Integer
  1578. Return Str.LastIndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1579. End Function
  1580. ''' <summary>
  1581. ''' 高速的 LastIndexOf。
  1582. ''' </summary>
  1583. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1584. Public Function LastIndexOfF(Str As String, SubStr As String, StartIndex As Integer, Optional IgnoreCase As Boolean = False) As Integer
  1585. Return Str.LastIndexOf(SubStr, StartIndex, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1586. End Function
  1587. ''' <summary>
  1588. ''' 输入 And 字符不会报错的 Val。
  1589. ''' </summary>
  1590. Public Function Val(Str As Object) As Double
  1591. Return If(TypeOf Str Is String AndAlso Str = "&", 0, Conversion.Val(Str))
  1592. End Function
  1593. '转义
  1594. ''' <summary>
  1595. ''' 为字符串进行 XML 转义。
  1596. ''' </summary>
  1597. Public Function EscapeXML(Str As String) As String
  1598. If Str.StartsWithF("{") Then Str = "{}" & Str '#4187
  1599. Return Str.
  1600. Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;").
  1601. Replace("""", "&quot;").Replace(vbCrLf, "&#xa;")
  1602. End Function
  1603. '正则
  1604. ''' <summary>
  1605. ''' 搜索字符串中的所有正则匹配项。
  1606. ''' </summary>
  1607. Public Function RegexSearch(str As String, regex As String, Optional options As RegexOptions = RegularExpressions.RegexOptions.None) As List(Of String)
  1608. Try
  1609. RegexSearch = New List(Of String)
  1610. Dim RegexSearchRes = New Regex(regex, options).Matches(str)
  1611. If RegexSearchRes Is Nothing Then Return RegexSearch
  1612. For Each item As Match In RegexSearchRes
  1613. RegexSearch.Add(item.Value)
  1614. Next
  1615. Catch ex As Exception
  1616. Log(ex, "正则匹配全部项出错")
  1617. Return New List(Of String)
  1618. End Try
  1619. End Function
  1620. ''' <summary>
  1621. ''' 获取字符串中的第一个正则匹配项,若无匹配则返回 Nothing。
  1622. ''' </summary>
  1623. Public Function RegexSeek(str As String, regex As String, Optional options As RegexOptions = RegularExpressions.RegexOptions.None) As String
  1624. Try
  1625. Dim Result = RegularExpressions.Regex.Match(str, regex, options).Value
  1626. Return If(Result = "", Nothing, Result)
  1627. Catch ex As Exception
  1628. Log(ex, "正则匹配第一项出错")
  1629. Return Nothing
  1630. End Try
  1631. End Function
  1632. ''' <summary>
  1633. ''' 检查字符串是否匹配某正则模式。
  1634. ''' </summary>
  1635. Public Function RegexCheck(str As String, regex As String, Optional options As RegexOptions = RegularExpressions.RegexOptions.None) As Boolean
  1636. Try
  1637. Return RegularExpressions.Regex.IsMatch(str, regex, options)
  1638. Catch ex As Exception
  1639. Log(ex, "正则检查出错")
  1640. Return False
  1641. End Try
  1642. End Function
  1643. ''' <summary>
  1644. ''' 进行正则替换,会抛出错误。
  1645. ''' </summary>
  1646. Public Function RegexReplace(Input As String, Replacement As String, Regex As String, Optional options As RegexOptions = RegularExpressions.RegexOptions.None) As String
  1647. Return RegularExpressions.Regex.Replace(Input, Regex, Replacement, options)
  1648. End Function
  1649. ''' <summary>
  1650. ''' 对每个正则匹配分别进行替换,会抛出错误。
  1651. ''' </summary>
  1652. Public Function RegexReplaceEach(Input As String, Replacement As MatchEvaluator, Regex As String, Optional options As RegexOptions = RegularExpressions.RegexOptions.None) As String
  1653. Return RegularExpressions.Regex.Replace(Input, Regex, Replacement, options)
  1654. End Function
  1655. #End Region
  1656. #Region "搜索"
  1657. ''' <summary>
  1658. ''' 获取搜索文本的相似度。
  1659. ''' </summary>
  1660. ''' <param name="Source">被搜索的长内容。</param>
  1661. ''' <param name="Query">用户输入的搜索文本。</param>
  1662. Private Function SearchSimilarity(Source As String, Query As String) As Double
  1663. Dim qp As Integer = 0, lenSum As Double = 0
  1664. Source = Source.ToLower.Replace(" ", "")
  1665. Query = Query.ToLower.Replace(" ", "")
  1666. Dim sourceLength As Integer = Source.Length, queryLength As Integer = Query.Length '用于计算最后因数的长度缓存
  1667. Do While qp < queryLength
  1668. '对 qp 作为开始位置计算
  1669. Dim sp As Integer = 0, lenMax As Integer = 0, spMax As Integer = 0
  1670. '查找以 qp 为头的最大子串
  1671. Do While sp < Source.Length
  1672. '对每个 sp 作为开始位置计算最大子串
  1673. Dim len As Integer = 0
  1674. Do While (qp + len) < queryLength AndAlso (sp + len) < Source.Length AndAlso Source(sp + len) = Query(qp + len)
  1675. len += 1
  1676. Loop
  1677. '存储 len
  1678. If len > lenMax Then
  1679. lenMax = len
  1680. spMax = sp
  1681. End If
  1682. '根据结果增加 sp
  1683. sp += Math.Max(1, len)
  1684. Loop
  1685. If lenMax > 0 Then
  1686. Source = Source.Substring(0, spMax) & If(Source.Count > spMax + lenMax, Source.Substring(spMax + lenMax), String.Empty) '将源中的对应字段替换空
  1687. '存储 lenSum
  1688. Dim IncWeight = (Math.Pow(1.4, 3 + lenMax) - 3.6) '根据长度加成
  1689. IncWeight *= 1 + 0.3 * Math.Max(0, 3 - Math.Abs(qp - spMax)) '根据位置加成
  1690. lenSum += IncWeight
  1691. End If
  1692. '根据结果增加 qp
  1693. qp += Math.Max(1, lenMax)
  1694. Loop
  1695. '计算结果:重复字段量 × 源长度影响比例
  1696. Return (lenSum / queryLength) * (3 / Math.Pow(sourceLength + 15, 0.5)) * If(queryLength <= 2, 3 - queryLength, 1)
  1697. End Function
  1698. ''' <summary>
  1699. ''' 获取多段文本加权后的相似度。
  1700. ''' </summary>
  1701. Private Function SearchSimilarityWeighted(Source As List(Of KeyValuePair(Of String, Double)), Query As String) As Double
  1702. Dim TotalWeight As Double = 0
  1703. Dim Sum As Double = 0
  1704. For Each Pair In Source
  1705. Sum += SearchSimilarity(Pair.Key, Query) * Pair.Value
  1706. TotalWeight += Pair.Value
  1707. Next
  1708. Return Sum / TotalWeight
  1709. End Function
  1710. ''' <summary>
  1711. ''' 用于搜索的项目。
  1712. ''' </summary>
  1713. Public Class SearchEntry(Of T)
  1714. ''' <summary>
  1715. ''' 该项目对应的源数据。
  1716. ''' </summary>
  1717. Public Item As T
  1718. ''' <summary>
  1719. ''' 该项目用于搜索的源。
  1720. ''' </summary>
  1721. Public SearchSource As List(Of KeyValuePair(Of String, Double))
  1722. ''' <summary>
  1723. ''' 相似度。
  1724. ''' </summary>
  1725. Public Similarity As Double
  1726. ''' <summary>
  1727. ''' 是否完全匹配。
  1728. ''' </summary>
  1729. Public AbsoluteRight As Boolean
  1730. End Class
  1731. ''' <summary>
  1732. ''' 进行多段文本加权搜索,获取相似度较高的数项结果。
  1733. ''' </summary>
  1734. ''' <param name="MaxBlurCount">返回的最大模糊结果数。</param>
  1735. ''' <param name="MinBlurSimilarity">返回结果要求的最低相似度。</param>
  1736. 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))
  1737. '初始化
  1738. Dim ResultList As New List(Of SearchEntry(Of T))
  1739. If Not Entries.Any() Then Return ResultList
  1740. '进行搜索,获取相似信息
  1741. For Each Entry In Entries
  1742. Entry.Similarity = SearchSimilarityWeighted(Entry.SearchSource, Query)
  1743. Entry.AbsoluteRight = False
  1744. For Each Pair In Entry.SearchSource
  1745. If Pair.Key.Replace(" ", "").ContainsF(Query.Replace(" ", ""), True) Then Entry.AbsoluteRight = True
  1746. Next
  1747. Next
  1748. '按照相似度进行排序
  1749. Entries = Sort(Entries,
  1750. Function(Left, Right) As Boolean
  1751. If Left.AbsoluteRight Xor Right.AbsoluteRight Then
  1752. Return Left.AbsoluteRight
  1753. Else
  1754. Return Left.Similarity > Right.Similarity
  1755. End If
  1756. End Function)
  1757. '返回结果
  1758. Dim BlurCount As Integer = 0
  1759. For Each Entry In Entries
  1760. If Entry.AbsoluteRight Then
  1761. ResultList.Add(Entry) '完全匹配,直接加入
  1762. Else
  1763. If Entry.Similarity < MinBlurSimilarity OrElse BlurCount = MaxBlurCount Then Exit For '模糊结果边界条件
  1764. ResultList.Add(Entry)
  1765. BlurCount += 1 '模糊结果计数
  1766. End If
  1767. Next
  1768. Return ResultList
  1769. End Function
  1770. #End Region
  1771. #Region "系统"
  1772. ''' <summary>
  1773. ''' 当前程序是否拥有管理员权限。
  1774. ''' </summary>
  1775. Public Function IsAdmin() As Boolean
  1776. Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
  1777. Dim principal As New WindowsPrincipal(id)
  1778. Return principal.IsInRole(WindowsBuiltInRole.Administrator)
  1779. End Function
  1780. ''' <summary>
  1781. ''' 以管理员权限运行当前程序,并等待程序运行结束。
  1782. ''' 返回程序的返回代码,如果运行失败将抛出异常。
  1783. ''' </summary>
  1784. Public Function RunAsAdmin(Argument As String) As Integer
  1785. Dim NewProcess = Process.Start(New ProcessStartInfo(PathWithName) With {.Verb = "runas", .Arguments = Argument})
  1786. NewProcess.WaitForExit()
  1787. Return NewProcess.ExitCode
  1788. End Function
  1789. Private Uuid As Integer = 1
  1790. Private UuidLock As Object
  1791. ''' <summary>
  1792. ''' 获取一个全程序内不会重复的数字(伪 Uuid)。
  1793. ''' </summary>
  1794. Public Function GetUuid() As Integer
  1795. If UuidLock Is Nothing Then UuidLock = New Object
  1796. SyncLock UuidLock
  1797. Uuid += 1
  1798. Return Uuid
  1799. End SyncLock
  1800. End Function
  1801. ''' <summary>
  1802. ''' 将元素与 List 的混合体拆分为元素组。
  1803. ''' </summary>
  1804. Public Function GetFullList(Of T)(data As IList) As List(Of T)
  1805. GetFullList = New List(Of T)
  1806. For i = 0 To data.Count - 1
  1807. If TypeOf data(i) Is ICollection Then
  1808. GetFullList.AddRange(data(i))
  1809. Else
  1810. GetFullList.Add(data(i))
  1811. End If
  1812. Next i
  1813. End Function
  1814. ''' <summary>
  1815. ''' 数组去重。
  1816. ''' </summary>
  1817. <Extension> Public Function Distinct(Of T)(Arr As ICollection(Of T), IsEqual As CompareThreadStart(Of T)) As List(Of T)
  1818. Dim ResultArray As New List(Of T)
  1819. For i = 0 To Arr.Count - 1
  1820. For ii = i + 1 To Arr.Count - 1
  1821. If IsEqual(Arr(i), Arr(ii)) Then GoTo NextElement
  1822. Next
  1823. ResultArray.Add(Arr(i))
  1824. NextElement:
  1825. Next i
  1826. Return ResultArray
  1827. End Function
  1828. ''' <summary>
  1829. ''' 获取格式类似于“11:08:52.037”的当前时间的字符串。
  1830. ''' </summary>
  1831. Public Function GetTimeNow() As String
  1832. Return Date.Now.ToString("HH':'mm':'ss'.'fff")
  1833. End Function
  1834. ''' <summary>
  1835. ''' 获取系统运行时间(毫秒),保证为正 Long 且大于 1,但可能突变减小。
  1836. ''' </summary>
  1837. Public Function GetTimeTick() As Long
  1838. Return My.Computer.Clock.TickCount + 2147483651L
  1839. End Function
  1840. ''' <summary>
  1841. ''' 将时间间隔转换为类似“5 分 10 秒前”的易于阅读的形式。
  1842. ''' </summary>
  1843. Public Function GetTimeSpanString(Span As TimeSpan, IsShortForm As Boolean) As String
  1844. Dim EndFix = If(Span.TotalMilliseconds > 0, "后", "前")
  1845. If Span.TotalMilliseconds < 0 Then Span = -Span
  1846. Dim TotalMonthes = Math.Floor(Span.Days / 30)
  1847. If IsShortForm Then
  1848. If TotalMonthes >= 12 Then
  1849. '1+ 年,“3 年”
  1850. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  1851. ElseIf TotalMonthes >= 2 Then
  1852. '2~11 月,“5 个月”
  1853. GetTimeSpanString = TotalMonthes & " 个月"
  1854. ElseIf Span.TotalDays >= 2 Then
  1855. '2 天 ~ 2 月,“23 天”
  1856. GetTimeSpanString = Span.Days & " 天"
  1857. ElseIf Span.TotalHours >= 1 Then
  1858. '1 小时 ~ 2 天,“15 小时”
  1859. GetTimeSpanString = Span.Hours & " 小时"
  1860. ElseIf Span.TotalMinutes >= 1 Then
  1861. '1 分钟 ~ 1 小时,“49 分钟”
  1862. GetTimeSpanString = Span.Minutes & " 分钟"
  1863. ElseIf Span.TotalSeconds >= 1 Then
  1864. '1 秒 ~ 1 分钟,“23 秒”
  1865. GetTimeSpanString = Span.Seconds & " 秒"
  1866. Else
  1867. '不到 1 秒
  1868. GetTimeSpanString = "1 秒"
  1869. End If
  1870. Else
  1871. If TotalMonthes >= 61 Then
  1872. '5+ 年,“5 年”
  1873. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  1874. ElseIf TotalMonthes >= 12 Then
  1875. '12~60 月,“1 年 2 个月”
  1876. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年" & If((TotalMonthes Mod 12) > 0, " " & (TotalMonthes Mod 12) & " 个月", "")
  1877. ElseIf TotalMonthes >= 4 Then
  1878. '4~11 月,“5 月”
  1879. GetTimeSpanString = TotalMonthes & " 月"
  1880. ElseIf TotalMonthes >= 1 Then
  1881. '1~4 月,“2 月 13 天”
  1882. GetTimeSpanString = TotalMonthes & " 月" & If((Span.Days Mod 30) > 0, " " & (Span.Days Mod 30) & " 天", "")
  1883. ElseIf Span.TotalDays >= 4 Then
  1884. '4~30 天,“23 天”
  1885. GetTimeSpanString = Span.Days & " 天"
  1886. ElseIf Span.TotalDays >= 1 Then
  1887. '1~3 天,“2 天 20 小时”
  1888. GetTimeSpanString = Span.Days & " 天" & If(Span.Hours > 0, " " & Span.Hours & " 小时", "")
  1889. ElseIf Span.TotalHours >= 10 Then
  1890. '10 小时 ~ 1 天,“15 小时”
  1891. GetTimeSpanString = Span.Hours & " 小时"
  1892. ElseIf Span.TotalHours >= 1 Then
  1893. '1~10 小时,“1 小时 20 分钟”
  1894. GetTimeSpanString = Span.Hours & " 小时" & If(Span.Minutes > 0, " " & Span.Minutes & " 分钟", "")
  1895. ElseIf Span.TotalMinutes >= 10 Then
  1896. '10 分钟 ~ 1 小时,“49 分钟”
  1897. GetTimeSpanString = Span.Minutes & " 分钟"
  1898. ElseIf Span.TotalMinutes >= 1 Then
  1899. '1~10 分钟,“9 分 23 秒”
  1900. GetTimeSpanString = Span.Minutes & " 分" & If(Span.Seconds > 0, " " & Span.Seconds & " 秒", "")
  1901. ElseIf Span.TotalSeconds >= 1 Then
  1902. '1 秒 ~ 1 分钟,“23 秒”
  1903. GetTimeSpanString = Span.Seconds & " 秒"
  1904. Else
  1905. '不到 1 秒
  1906. GetTimeSpanString = "1 秒"
  1907. End If
  1908. End If
  1909. GetTimeSpanString += EndFix
  1910. End Function
  1911. ''' <summary>
  1912. ''' 获取十进制 Unix 时间戳。
  1913. ''' </summary>
  1914. Public Function GetUnixTimestamp() As Long
  1915. Return (Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000
  1916. End Function
  1917. ''' <summary>
  1918. ''' 用于储存 RaiseByMouse 的 EventArgs。
  1919. ''' </summary>
  1920. Public NotInheritable Class RouteEventArgs
  1921. Inherits EventArgs
  1922. Public RaiseByMouse As Boolean
  1923. Public Handled As Boolean = False
  1924. Public Sub New(Optional RaiseByMouse As Boolean = False)
  1925. Me.RaiseByMouse = RaiseByMouse
  1926. End Sub
  1927. End Class
  1928. ''' <summary>
  1929. ''' 前台运行文件。
  1930. ''' </summary>
  1931. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1932. ''' <param name="Arguments">运行参数。</param>
  1933. Public Sub ShellOnly(FileName As String, Optional Arguments As String = "")
  1934. Using Program As New Process
  1935. Program.StartInfo.Arguments = Arguments
  1936. Program.StartInfo.FileName = FileName
  1937. Log("[System] 执行外部命令:" & FileName & " " & Arguments)
  1938. Program.Start()
  1939. End Using
  1940. End Sub
  1941. ''' <summary>
  1942. ''' 前台运行文件并返回返回值。
  1943. ''' </summary>
  1944. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1945. ''' <param name="Arguments">运行参数。</param>
  1946. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会返回 Result.Timeout。</param>
  1947. Public Function ShellAndGetExitCode(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000) As Result
  1948. Try
  1949. Using Program As New Process
  1950. Program.StartInfo.Arguments = Arguments
  1951. Program.StartInfo.FileName = FileName
  1952. Log("[System] 执行外部命令并等待返回码:" & FileName & " " & Arguments)
  1953. Program.Start()
  1954. If Program.WaitForExit(Timeout) Then
  1955. Return Program.ExitCode
  1956. Else
  1957. Return Result.Timeout
  1958. End If
  1959. End Using
  1960. Catch ex As Exception
  1961. Log(ex, "执行命令失败:" & FileName, LogLevel.Msgbox)
  1962. Return Result.Fail
  1963. End Try
  1964. End Function
  1965. ''' <summary>
  1966. ''' 静默运行文件并返回输出流字符串。执行失败会抛出异常。
  1967. ''' </summary>
  1968. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  1969. ''' <param name="Arguments">运行参数。</param>
  1970. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会抛出错误。</param>
  1971. Public Function ShellAndGetOutput(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000, Optional WorkingDirectory As String = Nothing) As String
  1972. Dim Info = New ProcessStartInfo With {
  1973. .Arguments = Arguments,
  1974. .FileName = FileName,
  1975. .UseShellExecute = False,
  1976. .CreateNoWindow = True,
  1977. .RedirectStandardError = True,
  1978. .RedirectStandardOutput = True,
  1979. .WorkingDirectory = If(WorkingDirectory, Path.TrimEnd("\"c))
  1980. }
  1981. If WorkingDirectory IsNot Nothing Then
  1982. If Info.EnvironmentVariables.ContainsKey("appdata") Then
  1983. Info.EnvironmentVariables("appdata") = WorkingDirectory
  1984. Else
  1985. Info.EnvironmentVariables.Add("appdata", WorkingDirectory)
  1986. End If
  1987. End If
  1988. Log("[System] 执行外部命令并等待返回结果:" & FileName & " " & Arguments)
  1989. Using Program As New Process() With {.StartInfo = Info}
  1990. Program.Start()
  1991. Dim Result As String = Program.StandardOutput.ReadToEnd & Program.StandardError.ReadToEnd
  1992. Program.WaitForExit(Timeout)
  1993. If Not Program.HasExited Then Program.Kill()
  1994. Return Result
  1995. End Using
  1996. End Function
  1997. ''' <summary>
  1998. ''' 在新的工作线程中执行代码。
  1999. ''' </summary>
  2000. Public Function RunInNewThread(Action As Action, Name As String, Optional Priority As ThreadPriority = ThreadPriority.Normal) As Thread
  2001. Dim th As New Thread(
  2002. Sub()
  2003. Try
  2004. Action()
  2005. Catch ex As ThreadInterruptedException
  2006. Log(Name & ":线程已中止")
  2007. Catch ex As Exception
  2008. Log(ex, Name & ":线程执行失败", LogLevel.Feedback)
  2009. End Try
  2010. End Sub) With {.Name = Name, .Priority = Priority}
  2011. th.Start()
  2012. Return th
  2013. End Function
  2014. ''' <summary>
  2015. ''' 确保在 UI 线程中执行代码。
  2016. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  2017. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  2018. ''' </summary>
  2019. Public Function RunInUiWait(Of Output)(Action As Func(Of Output)) As Output
  2020. If RunInUi() Then
  2021. Return Action()
  2022. Else
  2023. Return Application.Current.Dispatcher.Invoke(Action)
  2024. End If
  2025. End Function
  2026. ''' <summary>
  2027. ''' 确保在 UI 线程中执行代码。
  2028. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  2029. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  2030. ''' </summary>
  2031. Public Sub RunInUiWait(Action As Action)
  2032. If RunInUi() Then
  2033. Action()
  2034. Else
  2035. Application.Current.Dispatcher.Invoke(Action)
  2036. End If
  2037. End Sub
  2038. ''' <summary>
  2039. ''' 确保在 UI 线程中执行代码,代码按触发顺序执行。
  2040. ''' 如果当前并非 UI 线程,也不阻断当前线程的执行。
  2041. ''' </summary>
  2042. Public Sub RunInUi(Action As Action, Optional ForceWaitUntilLoaded As Boolean = False)
  2043. If ForceWaitUntilLoaded Then
  2044. Application.Current.Dispatcher.InvokeAsync(Action, Threading.DispatcherPriority.Loaded)
  2045. ElseIf RunInUi() Then
  2046. Action()
  2047. Else
  2048. Application.Current.Dispatcher.InvokeAsync(Action)
  2049. End If
  2050. End Sub
  2051. ''' <summary>
  2052. ''' 确保在工作线程中执行代码。
  2053. ''' </summary>
  2054. Public Sub RunInThread(Action As Action)
  2055. If RunInUi() Then
  2056. RunInNewThread(Action, "Runtime Invoke " & GetUuid() & "#")
  2057. Else
  2058. Action()
  2059. End If
  2060. End Sub
  2061. ''' <summary>
  2062. ''' 按照既定的函数进行选择排序。
  2063. ''' </summary>
  2064. ''' <param name="SortRule">传入两个对象,若第一个对象应该排在前面,则返回 True。</param>
  2065. <Extension> Public Function Sort(Of T)(List As IList(Of T), SortRule As CompareThreadStart(Of T)) As List(Of T)
  2066. Dim NewList As New List(Of T)
  2067. While List.Any
  2068. Dim Highest = List(0)
  2069. For i = 1 To List.Count - 1
  2070. If SortRule(List(i), Highest) Then Highest = List(i)
  2071. Next
  2072. List.Remove(Highest)
  2073. NewList.Add(Highest)
  2074. End While
  2075. Return NewList
  2076. End Function
  2077. Public Delegate Function CompareThreadStart(Of T)(Left As T, Right As T) As Boolean
  2078. ''' <summary>
  2079. ''' 返回列表的浅表副本。
  2080. ''' </summary>
  2081. <Extension> Public Function Clone(Of T)(list As IList(Of T)) As IList(Of T)
  2082. Return New List(Of T)(list)
  2083. End Function
  2084. ''' <summary>
  2085. ''' 获取程序启动参数。
  2086. ''' </summary>
  2087. ''' <param name="Name">参数名。</param>
  2088. ''' <param name="DefaultValue">默认值。</param>
  2089. Public Function GetProgramArgument(Name As String, Optional DefaultValue As Object = "")
  2090. Dim AllArguments() As String = Command.Split(" ")
  2091. For i = 0 To AllArguments.Length - 1
  2092. If AllArguments(i) = "-" & Name Then
  2093. If AllArguments.Length = i + 1 OrElse AllArguments(i + 1).StartsWithF("-") Then Return True
  2094. Return AllArguments(i + 1)
  2095. End If
  2096. Next
  2097. Return DefaultValue
  2098. End Function
  2099. ''' <summary>
  2100. ''' 时间戳转化为日期。
  2101. ''' </summary>
  2102. Public Function GetDate(timeStamp As Integer) As Date
  2103. Dim dtStart As Date = TimeZone.CurrentTimeZone.ToLocalTime(New Date(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
  2104. Dim lTime As Long = (CLng(timeStamp) * 10000000)
  2105. Return dtStart.Add(New TimeSpan(lTime))
  2106. End Function
  2107. ''' <summary>
  2108. ''' 将 UTC 时间转化为当前时区的时间。
  2109. ''' </summary>
  2110. Public Function GetLocalTime(UtcDate As Date) As Date
  2111. Return DateTime.SpecifyKind(UtcDate, DateTimeKind.Utc).ToLocalTime
  2112. End Function
  2113. ''' <summary>
  2114. ''' 打开网页。
  2115. ''' </summary>
  2116. Public Sub OpenWebsite(Url As String)
  2117. Try
  2118. If Not Url.StartsWithF("http", True) AndAlso Not Url.StartsWithF("minecraft://", True) Then
  2119. Throw New Exception(Url & " 不是一个有效的网址,它必须以 http 开头!")
  2120. End If
  2121. Log("[System] 正在打开网页:" & Url)
  2122. Process.Start(Url)
  2123. Catch ex As Exception
  2124. Log(ex, "无法打开网页(" & Url & ")")
  2125. ClipboardSet(Url, False)
  2126. MyMsgBox("可能由于浏览器未正确配置,PCL 无法为你打开网页。" & vbCrLf & "网址已经复制到剪贴板,若有需要可以手动粘贴访问。" & vbCrLf &
  2127. $"网址:{Url}", "无法打开网页")
  2128. End Try
  2129. End Sub
  2130. ''' <summary>
  2131. ''' 打开 explorer。注意参数中的路径要尽量加上双引号!
  2132. ''' </summary>
  2133. Public Sub OpenExplorer(Argument As String)
  2134. Try
  2135. ShellOnly("explorer.exe", Argument)
  2136. Catch ex As Exception
  2137. Log(ex, "打开资源管理器失败,请尝试关闭安全软件(如 360 安全卫士)", LogLevel.Msgbox)
  2138. End Try
  2139. End Sub
  2140. ''' <summary>
  2141. ''' 设置剪贴板。将在另一线程运行,且不会抛出异常。
  2142. ''' </summary>
  2143. Public Sub ClipboardSet(Text As String, Optional ShowSuccessHint As Boolean = True)
  2144. RunInThread(
  2145. Sub()
  2146. Dim RetryCount As Integer = 0
  2147. Retry:
  2148. Try
  2149. RunInUi(
  2150. Sub()
  2151. My.Computer.Clipboard.Clear()
  2152. My.Computer.Clipboard.SetText(Text)
  2153. End Sub)
  2154. Catch ex As Exception
  2155. RetryCount += 1
  2156. If RetryCount <= 5 Then
  2157. Thread.Sleep(20)
  2158. GoTo Retry
  2159. Else
  2160. Log(ex, "可能由于剪贴板被其他程序占用,文本复制失败", LogLevel.Hint)
  2161. End If
  2162. End Try
  2163. If ShowSuccessHint Then Hint("已成功复制!", HintType.Finish)
  2164. End Sub)
  2165. End Sub
  2166. ''' <summary>
  2167. ''' 以 Byte() 形式获取程序中的资源。
  2168. ''' </summary>
  2169. Public Function GetResources(ResourceName As String) As Byte()
  2170. Log("[System] 获取资源:" & ResourceName)
  2171. Dim Raw As Byte() = My.Resources.ResourceManager.GetObject(ResourceName)
  2172. Return Raw
  2173. End Function
  2174. #End Region
  2175. #Region "UI"
  2176. '边距改变
  2177. ''' <summary>
  2178. ''' 相对增减控件的左边距。
  2179. ''' </summary>
  2180. Public Sub DeltaLeft(control As FrameworkElement, newValue As Double)
  2181. '安全性检查
  2182. DebugAssert(Not Double.IsNaN(newValue))
  2183. DebugAssert(Not Double.IsInfinity(newValue))
  2184. If TypeOf control Is Window Then
  2185. '窗口改变
  2186. CType(control, Window).Left += newValue
  2187. Else
  2188. '根据 HorizontalAlignment 改变数值
  2189. Select Case control.HorizontalAlignment
  2190. Case HorizontalAlignment.Left, HorizontalAlignment.Stretch
  2191. control.Margin = New Thickness(control.Margin.Left + newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2192. Case HorizontalAlignment.Right
  2193. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right - newValue, control.Margin.Bottom)
  2194. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2195. Case Else
  2196. DebugAssert(False)
  2197. End Select
  2198. End If
  2199. End Sub
  2200. ''' <summary>
  2201. ''' 设置控件的左边距。(仅针对置左控件)
  2202. ''' </summary>
  2203. Public Sub SetLeft(control As FrameworkElement, newValue As Double)
  2204. DebugAssert(control.HorizontalAlignment = HorizontalAlignment.Left)
  2205. control.Margin = New Thickness(newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2206. End Sub
  2207. ''' <summary>
  2208. ''' 相对增减控件的上边距。
  2209. ''' </summary>
  2210. Public Sub DeltaTop(control As FrameworkElement, newValue As Double)
  2211. '安全性检查
  2212. DebugAssert(Not Double.IsNaN(newValue))
  2213. DebugAssert(Not Double.IsInfinity(newValue))
  2214. If TypeOf control Is Window Then
  2215. '窗口改变
  2216. CType(control, Window).Top += newValue
  2217. Else
  2218. '根据 VerticalAlignment 改变数值
  2219. Select Case control.VerticalAlignment
  2220. Case VerticalAlignment.Top
  2221. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top + newValue, control.Margin.Right, control.Margin.Bottom)
  2222. Case VerticalAlignment.Bottom
  2223. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, control.Margin.Bottom - newValue)
  2224. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2225. Case Else
  2226. DebugAssert(False)
  2227. End Select
  2228. End If
  2229. 'If Double.IsNaN(newValue) OrElse Double.IsInfinity(newValue) Then Exit Sub '安全性检查
  2230. 'Select Case control.VerticalAlignment
  2231. ' Case VerticalAlignment.Top, VerticalAlignment.Stretch, VerticalAlignment.Center
  2232. ' control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2233. ' Case VerticalAlignment.Bottom
  2234. ' control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, -newValue)
  2235. ' 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, CType(control.Parent, Object).ActualHeight - control.ActualHeight - newValue)
  2236. 'End Select
  2237. End Sub
  2238. ''' <summary>
  2239. ''' 设置控件的顶边距。(仅针对置上控件)
  2240. ''' </summary>
  2241. Public Sub SetTop(control As FrameworkElement, newValue As Double)
  2242. DebugAssert(control.VerticalAlignment = VerticalAlignment.Top)
  2243. control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2244. End Sub
  2245. 'DPI 转换
  2246. Public ReadOnly DPI As Integer = System.Drawing.Graphics.FromHwnd(IntPtr.Zero).DpiX
  2247. ''' <summary>
  2248. ''' 将经过 DPI 缩放的 WPF 尺寸转化为实际的像素尺寸。
  2249. ''' </summary>
  2250. Public Function GetPixelSize(WPFSize As Double) As Double
  2251. Return WPFSize / 96 * DPI
  2252. End Function
  2253. ''' <summary>
  2254. ''' 将实际的像素尺寸转化为经过 DPI 缩放的 WPF 尺寸。
  2255. ''' </summary>
  2256. Public Function GetWPFSize(PixelSize As Double) As Double
  2257. Return PixelSize * 96 / DPI
  2258. End Function
  2259. 'UI 截图
  2260. ''' <summary>
  2261. ''' 将某个控件的呈现转换为图片。
  2262. ''' </summary>
  2263. Public Function ControlBrush(UI As FrameworkElement) As ImageBrush
  2264. Dim Width = UI.ActualWidth, Height = UI.ActualHeight
  2265. If Width < 1 OrElse Height < 1 Then Return New ImageBrush
  2266. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Pbgra32)
  2267. bmp.Render(UI)
  2268. Return New ImageBrush(bmp)
  2269. End Function
  2270. ''' <summary>
  2271. ''' 将某个控件的模拟呈现转换为图片。
  2272. ''' </summary>
  2273. Public Function ControlBrush(UI As FrameworkElement, Width As Double, Height As Double, Optional Left As Double = 0, Optional Top As Double = 0) As ImageBrush
  2274. UI.Measure(New Size(Width, Height))
  2275. UI.Arrange(New Rect(0, 0, Width, Height))
  2276. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Default)
  2277. bmp.Render(UI)
  2278. If Not (Left = 0 AndAlso Top = 0) Then UI.Arrange(New Rect(Left, Top, Width, Height))
  2279. Return New ImageBrush(bmp)
  2280. End Function
  2281. ''' <summary>
  2282. ''' 将 UI 内容固定为图片并进行 Clear。
  2283. ''' </summary>
  2284. Public Sub ControlFreeze(UI As Panel)
  2285. UI.Background = ControlBrush(UI)
  2286. UI.Children.Clear()
  2287. End Sub
  2288. ''' <summary>
  2289. ''' 将 UI 内容固定为图片并进行 Clear。
  2290. ''' </summary>
  2291. Public Sub ControlFreeze(UI As Border)
  2292. UI.Background = ControlBrush(UI)
  2293. UI.Child = Nothing
  2294. End Sub
  2295. ''' <summary>
  2296. ''' 将 XML 转换为对应 UI 对象。
  2297. ''' </summary>
  2298. Public Function GetObjectFromXML(Str As XElement)
  2299. Return GetObjectFromXML(Str.ToString)
  2300. End Function
  2301. ''' <summary>
  2302. ''' 将 XML 转换为对应 UI 对象。
  2303. ''' </summary>
  2304. Public Function GetObjectFromXML(Str As String)
  2305. Using Stream As New MemoryStream
  2306. Using Writer As New StreamWriter(Stream)
  2307. Writer.Write(Str)
  2308. Writer.Flush()
  2309. Stream.Position = 0
  2310. Return XamlReader.Load(Stream)
  2311. End Using
  2312. End Using
  2313. End Function
  2314. Private ReadOnly UiThreadId As Integer = Thread.CurrentThread.ManagedThreadId
  2315. ''' <summary>
  2316. ''' 当前线程是否为主线程。
  2317. ''' </summary>
  2318. Public Function RunInUi() As Boolean
  2319. Return Thread.CurrentThread.ManagedThreadId = UiThreadId
  2320. End Function
  2321. ''' <summary>
  2322. ''' 检查某个控件是否位于主窗口可视区域内,且控件本身可见。
  2323. ''' </summary>
  2324. <Extension> Public Function IsVisibleInForm(element As FrameworkElement) As Boolean
  2325. If Not element.IsVisible Then Return False
  2326. Dim bounds As Rect = element.TransformToAncestor(FrmMain).TransformBounds(New Rect(0, 0, element.ActualWidth, element.ActualHeight))
  2327. Dim rect As New Rect(0, 0, FrmMain.ActualWidth, FrmMain.ActualHeight)
  2328. Return rect.Contains(bounds.TopLeft) OrElse rect.Contains(bounds.BottomRight)
  2329. End Function
  2330. #End Region
  2331. #Region "Debug"
  2332. Public ModeDebug As Boolean = False
  2333. 'Log
  2334. Public Enum LogLevel
  2335. ''' <summary>
  2336. ''' 不提示,只记录日志。
  2337. ''' </summary>
  2338. Normal = 0
  2339. ''' <summary>
  2340. ''' 只提示开发者。
  2341. ''' </summary>
  2342. Developer = 1
  2343. ''' <summary>
  2344. ''' 只提示开发者与调试模式用户。
  2345. ''' </summary>
  2346. Debug = 2
  2347. ''' <summary>
  2348. ''' 弹出提示所有用户。
  2349. ''' </summary>
  2350. Hint = 3
  2351. ''' <summary>
  2352. ''' 弹窗,不要求反馈。
  2353. ''' </summary>
  2354. Msgbox = 4
  2355. ''' <summary>
  2356. ''' 弹窗,要求反馈。
  2357. ''' </summary>
  2358. Feedback = 5
  2359. ''' <summary>
  2360. ''' 弹窗,结束程序。
  2361. ''' </summary>
  2362. Assert = 6
  2363. End Enum
  2364. Private LogList As New StringBuilder
  2365. Private LogWritter As StreamWriter
  2366. Public Sub LogStart()
  2367. RunInNewThread(
  2368. Sub()
  2369. Dim IsInitSuccess As Boolean = True
  2370. Try
  2371. For i = 4 To 1 Step -1
  2372. If File.Exists(Path & "PCL\Log" & i & ".txt") Then
  2373. If File.Exists(Path & "PCL\Log" & (i + 1) & ".txt") Then File.Delete(Path & "PCL\Log" & (i + 1) & ".txt")
  2374. CopyFile(Path & "PCL\Log" & i & ".txt", Path & "PCL\Log" & (i + 1) & ".txt")
  2375. End If
  2376. Next
  2377. File.Create(Path & "PCL\Log1.txt").Dispose()
  2378. Catch ex As IOException
  2379. IsInitSuccess = False
  2380. Hint("可能同时开启了多个 PCL,程序可能会出现未知问题!", HintType.Critical)
  2381. Log(ex, "日志初始化失败(疑似文件占用问题)")
  2382. Catch ex As Exception
  2383. IsInitSuccess = False
  2384. Log(ex, "日志初始化失败", LogLevel.Hint)
  2385. End Try
  2386. Try
  2387. LogWritter = New StreamWriter(Path & "PCL\Log1.txt", True) With {.AutoFlush = True}
  2388. Catch ex As Exception
  2389. LogWritter = Nothing
  2390. Log(ex, "日志写入失败", LogLevel.Hint)
  2391. End Try
  2392. While True
  2393. If IsInitSuccess Then
  2394. LogFlush()
  2395. Else
  2396. LogList = New StringBuilder '清空 LogList 避免内存爆炸
  2397. End If
  2398. Thread.Sleep(50)
  2399. End While
  2400. End Sub, "Log Writer", ThreadPriority.Lowest)
  2401. End Sub
  2402. Private ReadOnly LogFlushLock As New Object '防止外部调用 LogFlush 时同时输出多次日志
  2403. Public Sub LogFlush()
  2404. On Error Resume Next
  2405. If LogWritter Is Nothing Then Exit Sub
  2406. Dim Log As String = Nothing
  2407. SyncLock LogFlushLock
  2408. If LogList.Length > 0 Then
  2409. Dim LogListCache As StringBuilder
  2410. LogListCache = LogList
  2411. LogList = New StringBuilder
  2412. Log = LogListCache.ToString
  2413. End If
  2414. End SyncLock
  2415. If Log IsNot Nothing Then
  2416. LogWritter.Write(Log)
  2417. End If
  2418. End Sub
  2419. Private ReadOnly LogListLock As New Object '防止日志乱码,只在调试模式下启用
  2420. ''' <summary>
  2421. ''' 输出 Log。
  2422. ''' </summary>
  2423. ''' <param name="Title">如果要求弹窗,指定弹窗的标题。</param>
  2424. Public Sub Log(Text As String, Optional Level As LogLevel = LogLevel.Normal, Optional Title As String = "出现错误")
  2425. On Error Resume Next
  2426. '放在最后会导致无法显示极端错误下的弹窗(如无法写入日志文件)
  2427. '处理错误会导致再次调用 Log() 导致无限循环
  2428. '输出日志
  2429. Dim AppendText As String = "[" & GetTimeNow() & "] " & Text & vbCrLf '减轻同步锁占用
  2430. If ModeDebug Then
  2431. SyncLock LogListLock
  2432. LogList.Append(AppendText)
  2433. End SyncLock
  2434. Else
  2435. LogList.Append(AppendText)
  2436. End If
  2437. #If DEBUG Then
  2438. Console.Write(AppendText)
  2439. #End If
  2440. If IsProgramEnded OrElse Level = LogLevel.Normal Then Exit Sub
  2441. '去除前缀
  2442. Text = RegexReplace(Text, "", "\[[^\]]+?\] ")
  2443. '输出提示
  2444. Select Case Level
  2445. #If DEBUG Then
  2446. Case LogLevel.Developer
  2447. Hint("[开发者模式] " & Text, HintType.Info, False)
  2448. Case LogLevel.Debug
  2449. Hint("[调试模式] " & Text, HintType.Info, False)
  2450. #Else
  2451. Case LogLevel.Developer
  2452. Case LogLevel.Debug
  2453. If ModeDebug Then Hint("[调试模式] " & Text, HintType.Info, False)
  2454. #End If
  2455. Case LogLevel.Hint
  2456. Hint(Text, HintType.Critical, False)
  2457. Case LogLevel.Msgbox
  2458. MyMsgBox(Text, Title, IsWarn:=True)
  2459. Case LogLevel.Feedback
  2460. If CanFeedback(False) Then
  2461. If MyMsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  2462. Else
  2463. MyMsgBox(Text & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  2464. End If
  2465. Case LogLevel.Assert
  2466. Dim Time As Long = GetTimeTick()
  2467. If CanFeedback(False) Then
  2468. If MsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  2469. Else
  2470. MsgBox(Text & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  2471. End If
  2472. If GetTimeTick() - Time < 1500 Then
  2473. '弹窗无法保留
  2474. Log("[System] PCL 已崩溃:" & vbCrLf & Text)
  2475. FormMain.EndProgramForce(Result.Exception)
  2476. Else
  2477. FormMain.EndProgramForce(Result.Fail)
  2478. End If
  2479. End Select
  2480. End Sub
  2481. ''' <summary>
  2482. ''' 输出错误信息。
  2483. ''' </summary>
  2484. ''' <param name="Desc">错误描述。会在处理时在末尾加入冒号。</param>
  2485. Public Sub Log(Ex As Exception, Desc As String, Optional Level As LogLevel = LogLevel.Debug, Optional Title As String = "出现错误")
  2486. On Error Resume Next
  2487. If TypeOf Ex Is ThreadInterruptedException Then Exit Sub
  2488. '获取错误信息
  2489. Dim ExFull As String = Desc & ":" & GetExceptionDetail(Ex)
  2490. '输出日志
  2491. Dim AppendText As String = "[" & GetTimeNow() & "] " & Desc & ":" & GetExceptionDetail(Ex, True) & vbCrLf '减轻同步锁占用
  2492. If ModeDebug Then
  2493. SyncLock LogListLock
  2494. LogList.Append(AppendText)
  2495. End SyncLock
  2496. Else
  2497. LogList.Append(AppendText)
  2498. End If
  2499. #If DEBUG Then
  2500. Console.Write(AppendText)
  2501. #End If
  2502. If IsProgramEnded Then Exit Sub
  2503. '输出提示
  2504. Select Case Level
  2505. Case LogLevel.Normal
  2506. #If DEBUG Then
  2507. Case LogLevel.Developer
  2508. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2509. Hint("[开发者模式] " & ExLine, HintType.Info, False)
  2510. Case LogLevel.Debug
  2511. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2512. Hint("[调试模式] " & ExLine, HintType.Info, False)
  2513. #Else
  2514. Case LogLevel.Developer
  2515. Case LogLevel.Debug
  2516. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2517. If ModeDebug Then Hint("[调试模式] " & ExLine, HintType.Info, False)
  2518. #End If
  2519. Case LogLevel.Hint
  2520. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2521. Hint(ExLine, HintType.Critical, False)
  2522. Case LogLevel.Msgbox
  2523. MyMsgBox(ExFull, Title, IsWarn:=True)
  2524. Case LogLevel.Feedback
  2525. If CanFeedback(False) Then
  2526. If MyMsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  2527. Else
  2528. MyMsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  2529. End If
  2530. Case LogLevel.Assert
  2531. Dim Time As Long = GetTimeTick()
  2532. If CanFeedback(False) Then
  2533. If MsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  2534. Else
  2535. MsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  2536. End If
  2537. If GetTimeTick() - Time < 1500 Then
  2538. '弹窗无法保留
  2539. Log("[System] PCL 已崩溃:" & vbCrLf & ExFull)
  2540. FormMain.EndProgramForce(Result.Exception)
  2541. Else
  2542. FormMain.EndProgramForce(Result.Fail)
  2543. End If
  2544. End Select
  2545. End Sub
  2546. '反馈
  2547. Public Sub Feedback(Optional ShowMsgbox As Boolean = True, Optional ForceOpenLog As Boolean = False)
  2548. On Error Resume Next
  2549. FeedbackInfo()
  2550. If ForceOpenLog OrElse (ShowMsgbox AndAlso MyMsgBox("若你在汇报一个 Bug,请点击 打开文件夹 按钮,并上传 Log(1~5).txt 中包含错误信息的文件。" & vbCrLf & "游戏崩溃一般与启动器无关,请不要因为游戏崩溃而提交反馈。", "反馈提交提醒", "打开文件夹", "不需要") = 1) Then
  2551. OpenExplorer("""" & Path & "PCL\""")
  2552. End If
  2553. OpenWebsite("https://github.com/Hex-Dragon/PCL2/issues/")
  2554. End Sub
  2555. Public Function CanFeedback(ShowHint As Boolean) As Boolean
  2556. If False.Equals(PageSetupSystem.IsLauncherNewest) Then
  2557. If ShowHint Then MyMsgBox("你的 PCL 不是最新版,因此无法提交反馈。" & vbCrLf & "请先在 设置 → 启动器 中更新启动器,确认该问题在最新版中依然存在,然后再提交反馈。", "无法提交反馈")
  2558. Return False
  2559. Else
  2560. Return True
  2561. End If
  2562. End Function
  2563. ''' <summary>
  2564. ''' 在日志中输出系统诊断信息。
  2565. ''' </summary>
  2566. Public Sub FeedbackInfo()
  2567. On Error Resume Next
  2568. Log("[System] 诊断信息:" & vbCrLf &
  2569. "操作系统:" & My.Computer.Info.OSFullName & "(32 位:" & Is32BitSystem & ")" & vbCrLf &
  2570. "剩余内存:" & Int(My.Computer.Info.AvailablePhysicalMemory / 1024 / 1024) & " M / " & Int(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024) & " M" & vbCrLf &
  2571. "DPI:" & DPI & "(" & Math.Round(DPI / 96, 2) * 100 & "%)" & vbCrLf &
  2572. "MC 文件夹:" & If(PathMcFolder, "Nothing") & vbCrLf &
  2573. "文件位置:" & Path)
  2574. End Sub
  2575. '断言
  2576. Public Sub DebugAssert(Exp As Boolean)
  2577. If Not Exp Then Throw New Exception("断言命中")
  2578. End Sub
  2579. '获取当前的堆栈信息
  2580. Public Function GetStackTrace() As String
  2581. Dim Stack As New StackTrace()
  2582. Return Join(Stack.GetFrames().Skip(1).Select(Function(f) f.GetMethod).
  2583. Select(Function(f) f.Name & "(" & Join(f.GetParameters.Select(Function(p) p.ToString).ToList, ", ") & ") - " & f.Module.ToString).ToList,
  2584. vbCrLf).Replace(vbCrLf & vbCrLf, vbCrLf)
  2585. End Function
  2586. #End Region
  2587. #Region "随机"
  2588. Private ReadOnly Random As New Random
  2589. ''' <summary>
  2590. ''' 随机选择其一。
  2591. ''' </summary>
  2592. Public Function RandomOne(Of T)(objects As ICollection(Of T)) As T
  2593. Return objects(RandomInteger(0, objects.Count - 1))
  2594. End Function
  2595. ''' <summary>
  2596. ''' 取随机整数。
  2597. ''' </summary>
  2598. Public Function RandomInteger(min As Integer, max As Integer) As Integer
  2599. Return Math.Floor((max - min + 1) * Random.NextDouble) + min
  2600. End Function
  2601. ''' <summary>
  2602. ''' 将数组随机打乱。
  2603. ''' </summary>
  2604. Public Function Shuffle(Of T)(array As IList(Of T)) As IList(Of T)
  2605. Shuffle = New List(Of T)
  2606. Do While array.Any
  2607. Dim i As Integer = RandomInteger(0, array.Count - 1)
  2608. Shuffle.Add(array(i))
  2609. array.RemoveAt(i)
  2610. Loop
  2611. End Function
  2612. #End Region
  2613. End Module