ModBase.vb 155 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211
  1. Imports System.Globalization
  2. Imports System.IO.Compression
  3. Imports System.Reflection
  4. Imports System.Runtime.CompilerServices
  5. Imports System.Security.Cryptography
  6. Imports System.Security.Principal
  7. Imports System.Text.RegularExpressions
  8. Imports System.Xaml
  9. Imports Newtonsoft.Json
  10. Public Module ModBase
  11. #Region "声明"
  12. '下列版本信息由更新器自动修改
  13. Public Const VersionBaseName As String = "2.10.0" '不含分支前缀的显示用版本名
  14. Public Const VersionStandardCode As String = "2.10.0." & VersionBranchCode '标准格式的四段式版本号
  15. Public Const CommitHash As String = "" 'Commit Hash,由 GitHub Workflow 自动替换
  16. #If BETA Then
  17. Public Const VersionCode As Integer = 357 'Release
  18. #Else
  19. Public Const VersionCode As Integer = 356 'Snapshot
  20. #End If
  21. '自动生成的版本信息
  22. Public Const VersionDisplayName As String = VersionBranchName & " " & VersionBaseName
  23. #If RELEASE Then
  24. Public Const VersionBranchName As String = "Snapshot"
  25. Public Const VersionBranchCode As String = "0"
  26. #ElseIf BETA Then
  27. Public Const VersionBranchName As String = "Release"
  28. Public Const VersionBranchCode As String = "50"
  29. #Else
  30. Public Const VersionBranchName As String = "Debug"
  31. Public Const VersionBranchCode As String = "100"
  32. #End If
  33. ''' <summary>
  34. ''' 主窗口句柄。
  35. ''' </summary>
  36. Public Handle As IntPtr
  37. ''' <summary>
  38. ''' 程序的启动路径,以“\”结尾。
  39. ''' </summary>
  40. Public Path As String = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
  41. ''' <summary>
  42. ''' 包含程序名的完整路径。
  43. ''' </summary>
  44. Public PathWithName As String = Path & AppDomain.CurrentDomain.SetupInformation.ApplicationName
  45. ''' <summary>
  46. ''' 程序内嵌图片文件夹路径,以“/”结尾。
  47. ''' </summary>
  48. Public PathImage As String = "pack://application:,,,/Plain Craft Launcher 2;component/Images/"
  49. ''' <summary>
  50. ''' 当前程序的语言。
  51. ''' </summary>
  52. Public Lang As String = "zh_CN"
  53. ''' <summary>
  54. ''' 设置对象。
  55. ''' </summary>
  56. Public Setup As New ModSetup
  57. ''' <summary>
  58. ''' 程序的打开计时。
  59. ''' </summary>
  60. Public ApplicationStartTick As Long = GetTimeTick()
  61. ''' <summary>
  62. ''' 程序打开时的时间。
  63. ''' </summary>
  64. Public ApplicationOpenTime As Date = Date.Now
  65. ''' <summary>
  66. ''' 识别码。
  67. ''' </summary>
  68. Public UniqueAddress As String = SecretGetUniqueAddress()
  69. ''' <summary>
  70. ''' 程序是否已结束。
  71. ''' </summary>
  72. Public IsProgramEnded As Boolean = False
  73. ''' <summary>
  74. ''' 是否为 32 位系统。
  75. ''' </summary>
  76. Public Is32BitSystem As Boolean = Not Environment.Is64BitOperatingSystem
  77. ''' <summary>
  78. ''' 是否使用 GBK 编码。
  79. ''' </summary>
  80. Public IsGBKEncoding As Boolean = Encoding.Default.CodePage = 936
  81. ''' <summary>
  82. ''' 系统盘盘符,以 \ 结尾。例如 “C:\”。
  83. ''' </summary>
  84. Public OsDrive As String = Environment.GetLogicalDrives().Where(Function(p) Directory.Exists(p)).First.ToUpper.First & ":\" '#3799
  85. ''' <summary>
  86. ''' 程序的缓存文件夹路径,以 \ 结尾。
  87. ''' </summary>
  88. Public PathTemp As String = If(Setup.Get("SystemSystemCache") = "", IO.Path.GetTempPath() & "PCL\", Setup.Get("SystemSystemCache")).ToString.Replace("/", "\").TrimEnd("\") & "\"
  89. ''' <summary>
  90. ''' AppData 中的 PCL 文件夹路径,以 \ 结尾。
  91. ''' </summary>
  92. Public PathAppdata As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\PCL\"
  93. #End Region
  94. #Region "矢量图标"
  95. Public Class Logo
  96. ''' <summary>
  97. ''' 图标按钮,心(空心),1.1x
  98. ''' </summary>
  99. 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"
  100. ''' <summary>
  101. ''' 图标按钮,心(实心),1.1x
  102. ''' </summary>
  103. 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"
  104. ''' <summary>
  105. ''' 图标按钮,垃圾桶,1.1x
  106. ''' </summary>
  107. 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"
  108. ''' <summary>
  109. ''' 图标按钮,禁止,1x
  110. ''' </summary>
  111. 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"
  112. ''' <summary>
  113. ''' 图标按钮,勾选,1x
  114. ''' </summary>
  115. 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"
  116. ''' <summary>
  117. ''' 图标按钮,笔,1x
  118. ''' </summary>
  119. 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"
  120. ''' <summary>
  121. ''' 图标按钮,齿轮,1.1x
  122. ''' </summary>
  123. 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"
  124. ''' <summary>
  125. ''' 图标按钮,重置,0.9x
  126. ''' </summary>
  127. 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"
  128. ''' <summary>
  129. ''' 图标按钮,刷新,0.85x
  130. ''' </summary>
  131. 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"
  132. ''' <summary>
  133. ''' 图标按钮,软盘,1x
  134. ''' </summary>
  135. 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"
  136. ''' <summary>
  137. ''' 图标按钮,信息,1.05x
  138. ''' </summary>
  139. 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"
  140. ''' <summary>
  141. ''' 图标按钮,列表,1x
  142. ''' </summary>
  143. 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"
  144. ''' <summary>
  145. ''' 图标按钮,文件夹,1.15x
  146. ''' </summary>
  147. 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"
  148. ''' <summary>
  149. ''' 图标按钮,名片,1.1x
  150. ''' </summary>
  151. 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"
  152. ''' <summary>
  153. ''' 图标按钮,×,0.85x
  154. ''' </summary>
  155. 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"
  156. ''' <summary>
  157. ''' 图标按钮,Mojang,1.1x
  158. ''' </summary>
  159. 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"
  160. ''' <summary>
  161. ''' 图标按钮,用户,0.95x
  162. ''' </summary>
  163. 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"
  164. ''' <summary>
  165. ''' 图标按钮,盾牌,1x
  166. ''' </summary>
  167. 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"
  168. ''' <summary>
  169. ''' 图标按钮,离线,0.85x
  170. ''' </summary>
  171. 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"
  172. ''' <summary>
  173. ''' 图标,服务端,1x
  174. ''' </summary>
  175. Public Const IconButtonServer As String = "M224 160a64 64 0 0 0-64 64v576a64 64 0 0 0 64 64h576a64 64 0 0 0 64-64V224a64 64 0 0 0-64-64H224z m0 384h576v256H224v-256z m192 96v64h320v-64H416z m-128 0v64h64v-64H288zM224 224h576v256H224V224z m192 96v64h320v-64H416z m-128 0v64h64v-64H288z"
  176. ''' <summary>
  177. ''' 图标,音符,1x
  178. ''' </summary>
  179. 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"
  180. ''' <summary>
  181. ''' 图标,播放,0.8x
  182. ''' </summary>
  183. 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"
  184. End Class
  185. #End Region
  186. #Region "自定义类"
  187. ''' <summary>
  188. ''' 支持小数与常见类型隐式转换的颜色。
  189. ''' </summary>
  190. Public Class MyColor
  191. Public A As Double = 255
  192. Public R As Double = 0
  193. Public G As Double = 0
  194. Public B As Double = 0
  195. '类型转换
  196. Public Shared Widening Operator CType(str As String) As MyColor
  197. Return New MyColor(str)
  198. End Operator
  199. Public Shared Widening Operator CType(col As Color) As MyColor
  200. Return New MyColor(col)
  201. End Operator
  202. Public Shared Widening Operator CType(conv As MyColor) As Color
  203. Return Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  204. End Operator
  205. Public Shared Widening Operator CType(conv As MyColor) As System.Drawing.Color
  206. Return System.Drawing.Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B))
  207. End Operator
  208. Public Shared Widening Operator CType(bru As SolidColorBrush) As MyColor
  209. Return New MyColor(bru.Color)
  210. End Operator
  211. Public Shared Widening Operator CType(conv As MyColor) As SolidColorBrush
  212. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  213. End Operator
  214. Public Shared Widening Operator CType(bru As Brush) As MyColor
  215. Return New MyColor(bru)
  216. End Operator
  217. Public Shared Widening Operator CType(conv As MyColor) As Brush
  218. Return New SolidColorBrush(Color.FromArgb(MathByte(conv.A), MathByte(conv.R), MathByte(conv.G), MathByte(conv.B)))
  219. End Operator
  220. '颜色运算
  221. Public Shared Operator +(a As MyColor, b As MyColor) As MyColor
  222. Return New MyColor With {.A = a.A + b.A, .B = a.B + b.B, .G = a.G + b.G, .R = a.R + b.R}
  223. End Operator
  224. Public Shared Operator -(a As MyColor, b As MyColor) As MyColor
  225. Return New MyColor With {.A = a.A - b.A, .B = a.B - b.B, .G = a.G - b.G, .R = a.R - b.R}
  226. End Operator
  227. Public Shared Operator *(a As MyColor, b As Double) As MyColor
  228. Return New MyColor With {.A = a.A * b, .B = a.B * b, .G = a.G * b, .R = a.R * b}
  229. End Operator
  230. Public Shared Operator /(a As MyColor, b As Double) As MyColor
  231. Return New MyColor With {.A = a.A / b, .B = a.B / b, .G = a.G / b, .R = a.R / b}
  232. End Operator
  233. Public Shared Operator =(a As MyColor, b As MyColor) As Boolean
  234. If IsNothing(a) AndAlso IsNothing(b) Then Return True
  235. If IsNothing(a) OrElse IsNothing(b) Then Return False
  236. Return a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B
  237. End Operator
  238. Public Shared Operator <>(a As MyColor, b As MyColor) As Boolean
  239. If IsNothing(a) AndAlso IsNothing(b) Then Return False
  240. If IsNothing(a) OrElse IsNothing(b) Then Return True
  241. Return Not (a.A = b.A AndAlso a.R = b.R AndAlso a.G = b.G AndAlso a.B = b.B)
  242. End Operator
  243. '构造函数
  244. Public Sub New()
  245. End Sub
  246. Public Sub New(col As Color)
  247. Me.A = col.A
  248. Me.R = col.R
  249. Me.G = col.G
  250. Me.B = col.B
  251. End Sub
  252. Public Sub New(HexString As String)
  253. Dim StringColor As Media.Color = ColorConverter.ConvertFromString(HexString)
  254. A = StringColor.A
  255. R = StringColor.R
  256. G = StringColor.G
  257. B = StringColor.B
  258. End Sub
  259. Public Sub New(newA As Double, col As MyColor)
  260. Me.A = newA
  261. Me.R = col.R
  262. Me.G = col.G
  263. Me.B = col.B
  264. End Sub
  265. Public Sub New(newR As Double, newG As Double, newB As Double)
  266. Me.A = 255
  267. Me.R = newR
  268. Me.G = newG
  269. Me.B = newB
  270. End Sub
  271. Public Sub New(newA As Double, newR As Double, newG As Double, newB As Double)
  272. Me.A = newA
  273. Me.R = newR
  274. Me.G = newG
  275. Me.B = newB
  276. End Sub
  277. Public Sub New(brush As Brush)
  278. Dim Color As Color = CType(brush, SolidColorBrush).Color
  279. A = Color.A
  280. R = Color.R
  281. G = Color.G
  282. B = Color.B
  283. End Sub
  284. Public Sub New(brush As SolidColorBrush)
  285. Dim Color As Color = brush.Color
  286. A = Color.A
  287. R = Color.R
  288. G = Color.G
  289. B = Color.B
  290. End Sub
  291. Public Sub New(obj As Object)
  292. If obj Is Nothing Then
  293. A = 255 : R = 255 : G = 255 : B = 255
  294. Else
  295. If TypeOf obj Is SolidColorBrush Then
  296. '避免反复获取 Color 对象造成性能下降
  297. Dim Color As Color = CType(obj, SolidColorBrush).Color
  298. A = Color.A
  299. R = Color.R
  300. G = Color.G
  301. B = Color.B
  302. Else
  303. A = obj.A
  304. R = obj.R
  305. G = obj.G
  306. B = obj.B
  307. End If
  308. End If
  309. End Sub
  310. 'HSL
  311. Public Function Hue(v1 As Double, v2 As Double, vH As Double) As Double
  312. If vH < 0 Then vH += 1
  313. If vH > 1 Then vH -= 1
  314. If vH < 0.16667 Then Return v1 + (v2 - v1) * 6 * vH
  315. If vH < 0.5 Then Return v2
  316. If vH < 0.66667 Then Return v1 + (v2 - v1) * (4 - vH * 6)
  317. Return v1
  318. End Function
  319. Public Function FromHSL(sH As Double, sS As Double, sL As Double) As MyColor
  320. If sS = 0 Then
  321. R = sL * 2.55
  322. G = R
  323. B = R
  324. Else
  325. Dim H = sH / 360
  326. Dim S = sS / 100
  327. Dim L = sL / 100
  328. S = If(L < 0.5, S * L + L, S * (1.0 - L) + L)
  329. L = 2 * L - S
  330. R = 255 * Hue(L, S, H + 1 / 3)
  331. G = 255 * Hue(L, S, H)
  332. B = 255 * Hue(L, S, H - 1 / 3)
  333. End If
  334. A = 255
  335. Return Me
  336. End Function
  337. Public Function FromHSL2(sH As Double, sS As Double, sL As Double) As MyColor
  338. If sS = 0 Then
  339. R = sL * 2.55 : G = R : B = R
  340. Else
  341. '初始化
  342. sH = (sH + 3600000) Mod 360
  343. Dim cent As Double() = {
  344. +0.1, -0.06, -0.3, '0, 30, 60
  345. -0.19, -0.15, -0.24, '90, 120, 150
  346. -0.32, -0.09, +0.18, '180, 210, 240
  347. +0.05, -0.12, -0.02, '270, 300, 330
  348. +0.1, -0.06} '最后两位与前两位一致,加是变亮,减是变暗
  349. '计算色调对应的亮度片区
  350. Dim center As Double = sH / 30.0
  351. Dim intCenter As Integer = Math.Floor(center) '亮度片区编号
  352. center = 50 - (
  353. (1 - center + intCenter) * cent(intCenter) + (center - intCenter) * cent(intCenter + 1)
  354. ) * sS
  355. 'center = 50 + (cent(intCenter) + (center - intCenter) * (cent(intCenter + 1) - cent(intCenter))) * sS
  356. sL = If(sL < center, sL / center, 1 + (sL - center) / (100 - center)) * 50
  357. FromHSL(sH, sS, sL)
  358. End If
  359. A = 255
  360. Return Me
  361. End Function
  362. Public Overrides Function ToString() As String
  363. Return "(" & A & "," & R & "," & G & "," & B & ")"
  364. End Function
  365. Public Overrides Function Equals(obj As Object) As Boolean
  366. Return Me = obj
  367. End Function
  368. End Class
  369. ''' <summary>
  370. ''' 支持负数与浮点数的矩形。
  371. ''' </summary>
  372. Public Class MyRect
  373. '属性
  374. Public Property Width As Double = 0
  375. Public Property Height As Double = 0
  376. Public Property Left As Double = 0
  377. Public Property Top As Double = 0
  378. '构造函数
  379. Public Sub New()
  380. End Sub
  381. Public Sub New(left As Double, top As Double, width As Double, height As Double)
  382. Me.Left = left
  383. Me.Top = top
  384. Me.Width = width
  385. Me.Height = height
  386. End Sub
  387. End Class
  388. ''' <summary>
  389. ''' 模块加载状态枚举。
  390. ''' </summary>
  391. Public Enum LoadState
  392. Waiting
  393. Loading
  394. Finished
  395. Failed
  396. Aborted
  397. End Enum
  398. ''' <summary>
  399. ''' 执行返回值。
  400. ''' </summary>
  401. Public Enum ProcessReturnValues
  402. ''' <summary>
  403. ''' 执行成功,或进程被中断。
  404. ''' </summary>
  405. Aborted = -1
  406. ''' <summary>
  407. ''' 执行成功。
  408. ''' </summary>
  409. Success = 0
  410. ''' <summary>
  411. ''' 执行失败。
  412. ''' </summary>
  413. Fail = 1
  414. ''' <summary>
  415. ''' 执行时出现未经处理的异常。
  416. ''' </summary>
  417. Exception = 2
  418. ''' <summary>
  419. ''' 执行超时。
  420. ''' </summary>
  421. Timeout = 3
  422. ''' <summary>
  423. ''' 取消执行。可能是由于不满足执行的前置条件。
  424. ''' </summary>
  425. Cancel = 4
  426. ''' <summary>
  427. ''' 任务成功完成。
  428. ''' </summary>
  429. TaskDone = 5
  430. End Enum
  431. ''' <summary>
  432. ''' 可以使用 Equals 和等号的 List。
  433. ''' </summary>
  434. Public Class EqualableList(Of T)
  435. Inherits List(Of T)
  436. Public Overrides Function Equals(obj As Object) As Boolean
  437. If TryCast(obj, List(Of T)) Is Nothing Then
  438. '类型不同
  439. Return False
  440. Else
  441. '类型相同
  442. Dim objList As List(Of T) = obj
  443. If objList.Count <> Count Then Return False
  444. For i = 0 To objList.Count - 1
  445. If Not objList(i).Equals(Me(i)) Then Return False
  446. Next
  447. Return True
  448. End If
  449. End Function
  450. Public Shared Operator =(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  451. Return EqualityComparer(Of EqualableList(Of T)).Default.Equals(left, right)
  452. End Operator
  453. Public Shared Operator <>(left As EqualableList(Of T), right As EqualableList(Of T)) As Boolean
  454. Return Not left = right
  455. End Operator
  456. End Class
  457. #End Region
  458. #Region "数学"
  459. ''' <summary>
  460. ''' 2~65 进制的转换。
  461. ''' </summary>
  462. Public Function RadixConvert(Input As String, FromRadix As Integer, ToRadix As Integer) As String
  463. Const Digits As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+="
  464. '零与负数的处理
  465. If String.IsNullOrEmpty(Input) Then Return "0"
  466. Dim IsNegative As Boolean = Input.StartsWithF("-")
  467. If IsNegative Then Input = Input.TrimStart("-")
  468. '转换为十进制
  469. Dim RealNum As Long = 0, Scale As Long = 1
  470. For Each Digit In Input.Reverse.Select(Function(l) Digits.IndexOfF(l))
  471. RealNum += Digit * Scale
  472. Scale *= FromRadix
  473. Next
  474. '转换为指定进制
  475. Dim Result = ""
  476. While RealNum > 0
  477. Dim NewNum As Integer = RealNum Mod ToRadix
  478. RealNum = (RealNum - NewNum) / ToRadix
  479. Result = Digits(NewNum) & Result
  480. End While
  481. '负数的结束处理与返回
  482. Return If(IsNegative, "-", "") & Result
  483. End Function
  484. ''' <summary>
  485. ''' 计算二阶贝塞尔曲线。
  486. ''' </summary>
  487. 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
  488. If x <= 0 OrElse Double.IsNaN(x) Then Return 0
  489. If x >= 1 Then Return 1
  490. Dim a, b
  491. a = x
  492. Do
  493. b = 3 * a * ((0.33333333 + x1 - x2) * a * a + (x2 - 2 * x1) * a + x1)
  494. a += (x - b) * 0.5
  495. Loop Until Math.Abs(b - x) < acc '精度
  496. Return 3 * a * ((0.33333333 + y1 - y2) * a * a + (y2 - 2 * y1) * a + y1)
  497. End Function
  498. ''' <summary>
  499. ''' 将一个数字限制为 0~255 的 Byte 值。
  500. ''' </summary>
  501. Public Function MathByte(d As Double) As Byte
  502. If d < 0 Then d = 0
  503. If d > 255 Then d = 255
  504. Return Math.Round(d)
  505. End Function
  506. ''' <summary>
  507. ''' 提供 MyColor 类型支持的 Math.Round。
  508. ''' </summary>
  509. Public Function MathRound(col As MyColor, Optional w As Integer = 0) As MyColor
  510. 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)}
  511. End Function
  512. ''' <summary>
  513. ''' 获取两数间的百分比。小数点精确到 6 位。
  514. ''' </summary>
  515. ''' <returns></returns>
  516. Public Function MathPercent(ValueA As Double, ValueB As Double, Percent As Double) As Double
  517. Return Math.Round(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决 Double 计算错误
  518. End Function
  519. ''' <summary>
  520. ''' 获取两颜色间的百分比,根据 RGB 计算。小数点精确到 6 位。
  521. ''' </summary>
  522. Public Function MathPercent(ValueA As MyColor, ValueB As MyColor, Percent As Double) As MyColor
  523. Return MathRound(ValueA * (1 - Percent) + ValueB * Percent, 6) '解决Double计算错误
  524. End Function
  525. ''' <summary>
  526. ''' 将数值限定在某个范围内。
  527. ''' </summary>
  528. Public Function MathClamp(value As Double, min As Double, max As Double) As Double
  529. Return Math.Max(min, Math.Min(max, value))
  530. End Function
  531. ''' <summary>
  532. ''' 符号函数。
  533. ''' </summary>
  534. Public Function MathSgn(Value As Double) As Integer
  535. If Value = 0 Then
  536. Return 0
  537. ElseIf Value > 0 Then
  538. Return 1
  539. Else
  540. Return -1
  541. End If
  542. End Function
  543. #End Region
  544. #Region "文件"
  545. '=============================
  546. ' 注册表
  547. '=============================
  548. ''' <summary>
  549. ''' 读取注册表键。如果失败则返回默认值。
  550. ''' </summary>
  551. Public Function ReadReg(Key As String, Optional DefaultValue As String = "") As String
  552. Try
  553. Dim SubKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\" & RegFolder, False)
  554. Return If(SubKey?.GetValue(Key), DefaultValue)
  555. Catch ex As Exception
  556. Log(ex, "读取注册表出错:" & Key, LogLevel.Hint)
  557. Return DefaultValue
  558. End Try
  559. End Function
  560. ''' <summary>
  561. ''' 写入注册表键。
  562. ''' </summary>
  563. Public Sub WriteReg(Key As String, Value As String, Optional ThrowException As Boolean = False)
  564. Try
  565. Dim SubKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\" & RegFolder, True)
  566. If SubKey Is Nothing Then SubKey = My.Computer.Registry.CurrentUser.CreateSubKey("Software\" & RegFolder) '如果不存在就创建
  567. SubKey.SetValue(Key, Value)
  568. Catch ex As Exception
  569. Log(ex, "写入注册表出错:" & Key, If(ThrowException, LogLevel.Hint, LogLevel.Developer))
  570. If ThrowException Then Throw
  571. End Try
  572. End Sub
  573. ''' <summary>
  574. ''' 是否存在某个注册表键。
  575. ''' </summary>
  576. Public Function HasReg(Key As String) As Boolean
  577. Return ReadReg(Key, Nothing) IsNot Nothing
  578. End Function
  579. ''' <summary>
  580. ''' 删除注册表键。
  581. ''' </summary>
  582. Public Sub DeleteReg(Key As String, Optional ThrowException As Boolean = False)
  583. Try
  584. Dim SubKey As Microsoft.Win32.RegistryKey = My.Computer.Registry.CurrentUser.OpenSubKey("Software\" & RegFolder, True)
  585. SubKey?.DeleteValue(Key)
  586. Catch ex As Exception
  587. Log(ex, "删除注册表出错:" & Key, If(ThrowException, LogLevel.Hint, LogLevel.Developer))
  588. If ThrowException Then Throw
  589. End Try
  590. End Sub
  591. '=============================
  592. ' ini
  593. '=============================
  594. Private ReadOnly IniCache As New SafeDictionary(Of String, SafeDictionary(Of String, String))
  595. ''' <summary>
  596. ''' 清除某 ini 文件的运行时缓存。
  597. ''' </summary>
  598. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  599. Public Sub IniClearCache(FileName As String)
  600. If Not FileName.Contains(":\") Then FileName = $"{Path}PCL\{FileName}.ini"
  601. If IniCache.ContainsKey(FileName) Then IniCache.Remove(FileName)
  602. End Sub
  603. ''' <summary>
  604. ''' 获取 ini 文件缓存。如果没有,则新读取 ini 文件内容。
  605. ''' 在文件不存在或读取失败时返回 Nothing。
  606. ''' </summary>
  607. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  608. Private Function IniGetContent(FileName As String) As SafeDictionary(Of String, String)
  609. Try
  610. '还原文件路径
  611. If Not FileName.Contains(":\") Then FileName = $"{Path}PCL\{FileName}.ini"
  612. '检索缓存
  613. If IniCache.ContainsKey(FileName) Then Return IniCache(FileName)
  614. '读取文件
  615. If Not File.Exists(FileName) Then Return Nothing
  616. Dim Ini As New SafeDictionary(Of String, String)
  617. For Each Line In ReadFile(FileName).Split(vbCrLf.ToArray(), StringSplitOptions.RemoveEmptyEntries)
  618. Dim Index As Integer = Line.IndexOfF(":")
  619. If Index > 0 Then Ini(Line.Substring(0, Index)) = Line.Substring(Index + 1) '可能会有重复键,见 #3616
  620. Next
  621. IniCache(FileName) = Ini
  622. Return Ini
  623. Catch ex As Exception
  624. Log(ex, $"生成 ini 文件缓存失败({FileName})", LogLevel.Hint)
  625. Return Nothing
  626. End Try
  627. End Function
  628. ''' <summary>
  629. ''' 读取 ini 文件。这可能会使用到缓存。
  630. ''' </summary>
  631. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  632. ''' <param name="Key">键。</param>
  633. ''' <param name="DefaultValue">没有找到键时返回的默认值。</param>
  634. Public Function ReadIni(FileName As String, Key As String, Optional DefaultValue As String = "") As String
  635. Dim Content = IniGetContent(FileName)
  636. If Content Is Nothing OrElse Not Content.ContainsKey(Key) Then Return DefaultValue
  637. Return Content(Key)
  638. End Function
  639. ''' <summary>
  640. ''' 判断 ini 文件中是否包含某个键。这可能会使用到缓存。
  641. ''' </summary>
  642. Public Function HasIniKey(FileName As String, Key As String) As Boolean
  643. Dim Content = IniGetContent(FileName)
  644. Return Content IsNot Nothing AndAlso Content.ContainsKey(Key)
  645. End Function
  646. ''' <summary>
  647. ''' 从 ini 文件中移除某个键。这会更新缓存。
  648. ''' </summary>
  649. Public Sub DeleteIniKey(FileName As String, Key As String)
  650. WriteIni(FileName, Key, Nothing)
  651. End Sub
  652. ''' <summary>
  653. ''' 写入 ini 文件,这会更新缓存。
  654. ''' 若 Value 为 Nothing,则删除该键。
  655. ''' </summary>
  656. ''' <param name="FileName">文件完整路径或简写文件名。简写将会使用“ApplicationName\文件名.ini”作为路径。</param>
  657. ''' <param name="Key">键。</param>
  658. ''' <param name="Value">值。</param>
  659. ''' <remarks></remarks>
  660. Public Sub WriteIni(FileName As String, Key As String, Value As String)
  661. Try
  662. '预处理
  663. If Key.Contains(":") Then Throw New Exception($"尝试写入 ini 文件 {FileName} 的键名中包含了冒号:{Key}")
  664. Key = Key.Replace(vbCr, "").Replace(vbLf, "")
  665. Value = Value?.Replace(vbCr, "").Replace(vbLf, "")
  666. '防止争用
  667. SyncLock WriteIniLock
  668. '获取目前文件
  669. Dim Content As SafeDictionary(Of String, String) = IniGetContent(FileName)
  670. If Content Is Nothing Then Content = New SafeDictionary(Of String, String)
  671. '更新值
  672. If Value Is Nothing Then
  673. If Not Content.ContainsKey(Key) Then Return '无需处理
  674. Content.Remove(Key)
  675. Else
  676. If Content.ContainsKey(Key) AndAlso Content(Key) = Value Then Return '无需处理
  677. Content(Key) = Value
  678. End If
  679. '写入文件
  680. Dim FileContent As New StringBuilder
  681. For Each Pair In Content
  682. FileContent.Append(Pair.Key)
  683. FileContent.Append(":")
  684. FileContent.Append(Pair.Value)
  685. FileContent.Append(vbCrLf)
  686. Next
  687. If Not FileName.Contains(":\") Then FileName = $"{Path}PCL\{FileName}.ini"
  688. WriteFile(FileName, FileContent.ToString)
  689. End SyncLock
  690. Catch ex As Exception
  691. Log(ex, $"写入文件失败({FileName} → {Key}:{Value})", LogLevel.Hint)
  692. End Try
  693. End Sub
  694. Private WriteIniLock As New Object
  695. '路径处理
  696. ''' <summary>
  697. ''' 从文件路径或者 Url 获取不包含文件名的路径,或获取文件夹的父文件夹路径。
  698. ''' 取决于原路径格式,路径以 / 或 \ 结尾。
  699. ''' 不包含路径将会抛出异常。
  700. ''' </summary>
  701. Public Function GetPathFromFullPath(FilePath As String) As String
  702. If Not (FilePath.Contains("\") OrElse FilePath.Contains("/")) Then Throw New Exception("不包含路径:" & FilePath)
  703. If FilePath.EndsWithF("\") OrElse FilePath.EndsWithF("/") Then
  704. '是文件夹路径
  705. Dim IsRight As Boolean = FilePath.EndsWithF("\")
  706. FilePath = Left(FilePath, Len(FilePath) - 1)
  707. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"})) & If(IsRight, "\", "/")
  708. Else
  709. '是文件路径
  710. GetPathFromFullPath = Left(FilePath, FilePath.LastIndexOfAny({"\", "/"}) + 1)
  711. If GetPathFromFullPath = "" Then Throw New Exception("不包含路径:" & FilePath)
  712. End If
  713. End Function
  714. ''' <summary>
  715. ''' 从文件路径或者 Url 获取不包含路径的文件名。不包含文件名将会抛出异常。
  716. ''' </summary>
  717. Public Function GetFileNameFromPath(FilePath As String) As String
  718. FilePath = FilePath.Replace("/", "\")
  719. If FilePath.EndsWithF("\") Then Throw New Exception("不包含文件名:" & FilePath)
  720. If FilePath.Contains("?") Then FilePath = FilePath.Substring(0, FilePath.IndexOfF("?")) '去掉网络参数后的 ?
  721. If FilePath.Contains("\") Then FilePath = FilePath.Substring(FilePath.LastIndexOfF("\") + 1)
  722. Dim length As Integer = FilePath.Length
  723. If length = 0 Then Throw New Exception("不包含文件名:" & FilePath)
  724. If length > 250 Then Throw New PathTooLongException("文件名过长:" & FilePath)
  725. Return FilePath
  726. End Function
  727. ''' <summary>
  728. ''' 从文件路径或者 Url 获取不包含路径与扩展名的文件名。不包含文件名将会抛出异常。
  729. ''' </summary>
  730. Public Function GetFileNameWithoutExtentionFromPath(FilePath As String) As String
  731. Dim Name As String = GetFileNameFromPath(FilePath)
  732. If Name.Contains(".") Then
  733. Return Name.Substring(0, Name.LastIndexOfF("."))
  734. Else
  735. Return Name
  736. End If
  737. End Function
  738. ''' <summary>
  739. ''' 从文件夹路径获取文件夹名。
  740. ''' </summary>
  741. Public Function GetFolderNameFromPath(FolderPath As String) As String
  742. If FolderPath.EndsWithF(":\") OrElse FolderPath.EndsWithF(":\\") Then Return FolderPath.Substring(0, 1)
  743. If FolderPath.EndsWithF("\") OrElse FolderPath.EndsWithF("/") Then FolderPath = Left(FolderPath, FolderPath.Length - 1)
  744. Return GetFileNameFromPath(FolderPath)
  745. End Function
  746. '读取、写入、复制文件
  747. Public Sub CopyFile(FromPath As String, ToPath As String)
  748. Try
  749. '还原文件路径
  750. If Not FromPath.Contains(":\") Then FromPath = Path & FromPath
  751. If Not ToPath.Contains(":\") Then ToPath = Path & ToPath
  752. '如果复制同一个文件则跳过
  753. If FromPath = ToPath Then Exit Sub
  754. '确保目录存在
  755. Directory.CreateDirectory(GetPathFromFullPath(ToPath))
  756. '复制文件
  757. File.Copy(FromPath, ToPath, True)
  758. Catch ex As Exception
  759. Throw New Exception("复制文件出错:" & FromPath & " → " & ToPath, ex)
  760. End Try
  761. End Sub
  762. ''' <summary>
  763. ''' 读取文件,如果失败则返回空数组。
  764. ''' </summary>
  765. ''' <param name="FilePath">文件完整或相对路径。</param>
  766. Public Function ReadFileBytes(FilePath As String, Optional Encoding As Encoding = Nothing) As Byte()
  767. Try
  768. '还原文件路径
  769. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  770. If File.Exists(FilePath) Then
  771. Dim FileBytes As Byte()
  772. Using ReadStream As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) '支持读取使用中的文件
  773. ReDim FileBytes(ReadStream.Length - 1)
  774. ReadStream.Read(FileBytes, 0, ReadStream.Length)
  775. End Using
  776. Return FileBytes
  777. Else
  778. Log("[System] 欲读取的文件不存在,已返回空内容:" & FilePath)
  779. Return {}
  780. End If
  781. Catch ex As Exception
  782. Log(ex, "读取文件出错:" & FilePath)
  783. Return {}
  784. End Try
  785. End Function
  786. ''' <summary>
  787. ''' 读取文件,如果失败则返回空字符串。
  788. ''' </summary>
  789. ''' <param name="FilePath">文件完整或相对路径。</param>
  790. Public Function ReadFile(FilePath As String, Optional Encoding As Encoding = Nothing) As String
  791. Dim FileBytes = ReadFileBytes(FilePath)
  792. ReadFile = If(Encoding Is Nothing, DecodeBytes(FileBytes), Encoding.GetString(FileBytes))
  793. End Function
  794. ''' <summary>
  795. ''' 读取流中的所有文本。
  796. ''' </summary>
  797. Public Function ReadFile(Stream As Stream, Optional Encoding As Encoding = Nothing) As String
  798. Try
  799. Dim srcBuf As Byte() = New Byte(16384) {}
  800. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  801. Dim Result As New List(Of Byte)
  802. While DataCount > 0
  803. If DataCount > 0 Then Result.AddRange(srcBuf.ToList.GetRange(0, DataCount))
  804. DataCount = Stream.Read(srcBuf, 0, 16384)
  805. End While
  806. Dim Bts = Result.ToArray
  807. Return If(Encoding, GetEncoding(Bts)).GetString(Bts)
  808. Catch ex As Exception
  809. Log(ex, "读取流出错")
  810. Return ""
  811. End Try
  812. End Function
  813. ''' <summary>
  814. ''' 写入文件。
  815. ''' </summary>
  816. ''' <param name="FilePath">文件完整或相对路径。</param>
  817. ''' <param name="Text">文件内容。</param>
  818. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  819. Public Sub WriteFile(FilePath As String, Text As String, Optional Append As Boolean = False, Optional Encoding As Encoding = Nothing)
  820. '处理相对路径
  821. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  822. '确保目录存在
  823. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  824. '写入文件
  825. If Append Then
  826. '追加目前文件
  827. Using writer As New StreamWriter(FilePath, True, If(Encoding, GetEncoding(ReadFileBytes(FilePath))))
  828. writer.Write(Text)
  829. writer.Flush()
  830. writer.Close()
  831. End Using
  832. Else
  833. '直接写入字节
  834. File.WriteAllBytes(FilePath, If(Encoding Is Nothing, New UTF8Encoding(False).GetBytes(Text), Encoding.GetBytes(Text)))
  835. End If
  836. End Sub
  837. ''' <summary>
  838. ''' 写入文件。
  839. ''' 如果 CanThrow 设置为 False,返回是否写入成功。
  840. ''' </summary>
  841. ''' <param name="FilePath">文件完整或相对路径。</param>
  842. ''' <param name="Content">文件内容。</param>
  843. ''' <param name="Append">是否将文件内容追加到当前文件,而不是覆盖它。</param>
  844. Public Sub WriteFile(FilePath As String, Content As Byte(), Optional Append As Boolean = False)
  845. '处理相对路径
  846. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  847. '确保目录存在
  848. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  849. '写入文件
  850. File.WriteAllBytes(FilePath, Content)
  851. End Sub
  852. ''' <summary>
  853. ''' 将流写入文件。
  854. ''' </summary>
  855. ''' <param name="FilePath">文件完整或相对路径。</param>
  856. Public Function WriteFile(FilePath As String, Stream As Stream) As Boolean
  857. Try
  858. '还原文件路径
  859. If Not FilePath.Contains(":\") Then FilePath = Path & FilePath
  860. '确保目录存在
  861. Directory.CreateDirectory(GetPathFromFullPath(FilePath))
  862. '读取流
  863. Using fs As New FileStream(FilePath, FileMode.Create, FileAccess.Write)
  864. Dim srcBuf As Byte() = New Byte(16384) {}
  865. Dim DataCount As Integer = Stream.Read(srcBuf, 0, 16384)
  866. While DataCount > 0
  867. If DataCount > 0 Then fs.Write(srcBuf, 0, DataCount)
  868. DataCount = Stream.Read(srcBuf, 0, 16384)
  869. End While
  870. fs.Close()
  871. End Using
  872. Return True
  873. Catch ex As Exception
  874. Log(ex, "保存流出错")
  875. Return False
  876. End Try
  877. End Function
  878. '文件编码
  879. ''' <summary>
  880. ''' 根据字节数组分析其编码。
  881. ''' </summary>
  882. Public Function GetEncoding(Bytes As Byte()) As Encoding
  883. Dim Length As Integer = Bytes.Count
  884. If Length < 3 Then Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  885. '根据 BOM 判断编码
  886. If Bytes(0) >= &HEF Then
  887. '有 BOM 类型
  888. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  889. Return New UTF8Encoding(True) '带 BOM 的 UTF8
  890. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  891. Return Encoding.BigEndianUnicode
  892. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  893. Return Encoding.Unicode
  894. Else
  895. Return Encoding.GetEncoding("GB18030")
  896. End If
  897. End If
  898. '无 BOM 文件:GB18030(ANSI)或 UTF8
  899. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  900. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  901. If UTF8.Contains(ErrorChar) Then
  902. Return Encoding.GetEncoding("GB18030")
  903. Else
  904. Return New UTF8Encoding(False) '不带 BOM 的 UTF8
  905. End If
  906. End Function
  907. ''' <summary>
  908. ''' 解码 Bytes。
  909. ''' </summary>
  910. Public Function DecodeBytes(Bytes As Byte()) As String
  911. Dim Length As Integer = Bytes.Length
  912. If Length < 3 Then Return Encoding.UTF8.GetString(Bytes)
  913. '根据 BOM 判断编码
  914. If Bytes(0) >= &HEF Then
  915. '有 BOM 类型
  916. If Bytes(0) = &HEF AndAlso Bytes(1) = &HBB Then
  917. Return Encoding.UTF8.GetString(Bytes, 3, Length - 3)
  918. ElseIf Bytes(0) = &HFE AndAlso Bytes(1) = &HFF Then
  919. Return Encoding.BigEndianUnicode.GetString(Bytes, 3, Length - 3)
  920. ElseIf Bytes(0) = &HFF AndAlso Bytes(1) = &HFE Then
  921. Return Encoding.Unicode.GetString(Bytes, 3, Length - 3)
  922. Else
  923. Return Encoding.GetEncoding("GB18030").GetString(Bytes, 3, Length - 3)
  924. End If
  925. End If
  926. '无 BOM 文件:GB18030(ANSI)或 UTF8
  927. Dim UTF8 = Encoding.UTF8.GetString(Bytes)
  928. Dim ErrorChar As Char = Encoding.UTF8.GetString({239, 191, 189}).ToCharArray()(0)
  929. If UTF8.Contains(ErrorChar) Then
  930. Return Encoding.GetEncoding("GB18030").GetString(Bytes)
  931. Else
  932. Return UTF8
  933. End If
  934. End Function
  935. '对话框
  936. ''' <summary>
  937. ''' 弹出保存对话框并且要求保存位置,返回用户输入的完整路径。
  938. ''' </summary>
  939. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  940. ''' <param name="Title">弹窗的标题。</param>
  941. ''' <param name="FileName">默认的文件名。</param>
  942. Public Function SelectSaveFile(Title As String, FileName As String, Optional FileFilter As String = Nothing, Optional InitialDirectory As String = Nothing) As String
  943. Using fileDialog As New Forms.SaveFileDialog
  944. fileDialog.AddExtension = True
  945. fileDialog.AutoUpgradeEnabled = True
  946. fileDialog.Title = Title
  947. fileDialog.FileName = FileName
  948. If FileFilter IsNot Nothing Then fileDialog.Filter = FileFilter
  949. If Not String.IsNullOrEmpty(InitialDirectory) AndAlso Directory.Exists(InitialDirectory) Then fileDialog.InitialDirectory = InitialDirectory
  950. fileDialog.ShowDialog()
  951. SelectSaveFile = If(fileDialog.FileName.Contains(":\"), fileDialog.FileName, "")
  952. Log("[UI] 选择文件返回:" & SelectSaveFile)
  953. End Using
  954. End Function
  955. ''' <summary>
  956. ''' 弹出选取文件对话框,要求选择一个文件。
  957. ''' </summary>
  958. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  959. ''' <param name="Title">弹窗的标题。</param>
  960. Public Function SelectFile(FileFilter As String, Title As String, Optional InitialDirectory As String = Nothing) As String
  961. Using fileDialog As New Forms.OpenFileDialog
  962. fileDialog.AddExtension = True
  963. fileDialog.AutoUpgradeEnabled = True
  964. fileDialog.CheckFileExists = True
  965. fileDialog.Filter = FileFilter
  966. fileDialog.Multiselect = False
  967. fileDialog.Title = Title
  968. fileDialog.ValidateNames = True
  969. If Not String.IsNullOrEmpty(InitialDirectory) AndAlso Directory.Exists(InitialDirectory) Then fileDialog.InitialDirectory = InitialDirectory
  970. fileDialog.ShowDialog()
  971. Log("[UI] 选择单个文件返回:" & fileDialog.FileName)
  972. Return fileDialog.FileName
  973. End Using
  974. End Function
  975. ''' <summary>
  976. ''' 弹出选取文件对话框,要求选择多个文件。
  977. ''' </summary>
  978. ''' <param name="FileFilter">要求的格式。如:“常用图片文件(*.png;*.jpg)|*.png;*.jpg”。</param>
  979. ''' <param name="Title">弹窗的标题。</param>
  980. Public Function SelectFiles(FileFilter As String, Title As String) As String()
  981. Using fileDialog As New Forms.OpenFileDialog
  982. fileDialog.AddExtension = True
  983. fileDialog.AutoUpgradeEnabled = True
  984. fileDialog.CheckFileExists = True
  985. fileDialog.Filter = FileFilter
  986. fileDialog.Multiselect = True
  987. fileDialog.Title = Title
  988. fileDialog.ValidateNames = True
  989. fileDialog.ShowDialog()
  990. Log("[UI] 选择多个文件返回:" & fileDialog.FileNames.Join(","))
  991. Return fileDialog.FileNames
  992. End Using
  993. End Function
  994. ''' <summary>
  995. ''' 弹出选取文件夹对话框,要求选取文件夹。
  996. ''' 返回以 \ 结尾的完整路径,如果没有选择则返回空字符串。
  997. ''' </summary>
  998. Public Function SelectFolder(Optional Title As String = "选择文件夹") As String
  999. Dim folderDialog As New Ookii.Dialogs.Wpf.VistaFolderBrowserDialog With {.ShowNewFolderButton = True, .RootFolder = Environment.SpecialFolder.Desktop, .Description = Title, .UseDescriptionForTitle = True}
  1000. folderDialog.ShowDialog()
  1001. SelectFolder = If(String.IsNullOrEmpty(folderDialog.SelectedPath), "", folderDialog.SelectedPath & If(folderDialog.SelectedPath.EndsWithF("\"), "", "\"))
  1002. Log("[UI] 选择文件夹返回:" & SelectFolder)
  1003. End Function
  1004. '文件校验
  1005. ''' <summary>
  1006. ''' 检查是否拥有某一文件夹的 I/O 权限。如果文件夹不存在,会返回 False。
  1007. ''' </summary>
  1008. Public Function CheckPermission(Path As String) As Boolean
  1009. Try
  1010. If String.IsNullOrEmpty(Path) Then Return False
  1011. If Not Path.EndsWithF("\") Then Path += "\"
  1012. If Path.EndsWithF(":\System Volume Information\") OrElse Path.EndsWithF(":\$RECYCLE.BIN\") Then Return False
  1013. If Not Directory.Exists(Path) Then Return False
  1014. Dim FileName As String = "CheckPermission" & GetUuid()
  1015. If File.Exists(Path & FileName) Then File.Delete(Path & FileName)
  1016. File.Create(Path & FileName).Dispose()
  1017. File.Delete(Path & FileName)
  1018. Return True
  1019. Catch ex As Exception
  1020. Log(ex, "没有对文件夹 " & Path & " 的权限,请尝试以管理员权限运行 PCL")
  1021. Return False
  1022. End Try
  1023. End Function
  1024. ''' <summary>
  1025. ''' 检查是否拥有某一文件夹的 I/O 权限。如果出错,则抛出异常。
  1026. ''' </summary>
  1027. Public Sub CheckPermissionWithException(Path As String)
  1028. If String.IsNullOrWhiteSpace(Path) Then Throw New ArgumentNullException("文件夹名不能为空!")
  1029. If Not Path.EndsWithF("\") Then Path += "\"
  1030. If Not Directory.Exists(Path) Then Throw New DirectoryNotFoundException("文件夹不存在!")
  1031. If File.Exists(Path & "CheckPermission") Then File.Delete(Path & "CheckPermission")
  1032. File.Create(Path & "CheckPermission").Dispose()
  1033. File.Delete(Path & "CheckPermission")
  1034. End Sub
  1035. ''' <summary>
  1036. ''' 获取文件 MD5,若失败则返回空字符串。
  1037. ''' </summary>
  1038. Public Function GetFileMD5(FilePath As String) As String
  1039. Dim Retry As Boolean = False
  1040. Re:
  1041. Try
  1042. '获取 MD5
  1043. Dim Result As New StringBuilder()
  1044. Dim File As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1045. Dim MD5 As MD5 = New MD5CryptoServiceProvider()
  1046. Dim Retval As Byte() = MD5.ComputeHash(File)
  1047. File.Close()
  1048. For i = 0 To Retval.Length - 1
  1049. Result.Append(Retval(i).ToString("x2"))
  1050. Next
  1051. Return Result.ToString
  1052. Catch ex As Exception
  1053. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1054. Log(ex, "获取文件 MD5 失败:" & FilePath)
  1055. Return ""
  1056. Else
  1057. Retry = True
  1058. Log(ex, "获取文件 MD5 可重试失败:" & FilePath, LogLevel.Normal)
  1059. Thread.Sleep(RandomInteger(200, 500))
  1060. GoTo Re
  1061. End If
  1062. End Try
  1063. End Function
  1064. ''' <summary>
  1065. ''' 获取文件 SHA512,若失败则返回空字符串。
  1066. ''' </summary>
  1067. Public Function GetFileSHA512(FilePath As String) As String
  1068. Dim Retry As Boolean = False
  1069. Re:
  1070. Try
  1071. ''检测该文件是否在下载中,若在下载则放弃检测
  1072. 'If IgnoreOnDownloading AndAlso NetManage.Files.ContainsKey(FilePath) AndAlso NetManage.Files(FilePath).State <= NetState.Merge Then Return ""
  1073. '获取 SHA512
  1074. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1075. Dim sha512 As SHA512 = New SHA512CryptoServiceProvider()
  1076. Dim retval As Byte() = sha512.ComputeHash(file)
  1077. file.Close()
  1078. Dim Result As New StringBuilder()
  1079. For i As Integer = 0 To retval.Length - 1
  1080. Result.Append(retval(i).ToString("x2"))
  1081. Next
  1082. Return Result.ToString
  1083. Catch ex As Exception
  1084. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1085. Log(ex, "获取文件 SHA512 失败:" & FilePath)
  1086. Return ""
  1087. Else
  1088. Retry = True
  1089. Log(ex, "获取文件 SHA512 可重试失败:" & FilePath, LogLevel.Normal)
  1090. Thread.Sleep(RandomInteger(200, 500))
  1091. GoTo Re
  1092. End If
  1093. End Try
  1094. End Function
  1095. ''' <summary>
  1096. ''' 获取文件 SHA256,若失败则返回空字符串。
  1097. ''' </summary>
  1098. Public Function GetFileSHA256(FilePath As String) As String
  1099. Dim Retry As Boolean = False
  1100. Re:
  1101. Try
  1102. ''检测该文件是否在下载中,若在下载则放弃检测
  1103. 'If IgnoreOnDownloading AndAlso NetManage.Files.ContainsKey(FilePath) AndAlso NetManage.Files(FilePath).State <= NetState.Merge Then Return ""
  1104. '获取 SHA256
  1105. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1106. Dim sha256 As SHA256 = New SHA256CryptoServiceProvider()
  1107. Dim retval As Byte() = sha256.ComputeHash(file)
  1108. file.Close()
  1109. Dim Result As New StringBuilder()
  1110. For i As Integer = 0 To retval.Length - 1
  1111. Result.Append(retval(i).ToString("x2"))
  1112. Next
  1113. Return Result.ToString
  1114. Catch ex As Exception
  1115. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1116. Log(ex, "获取文件 SHA256 失败:" & FilePath)
  1117. Return ""
  1118. Else
  1119. Retry = True
  1120. Log(ex, "获取文件 SHA256 可重试失败:" & FilePath, LogLevel.Normal)
  1121. Thread.Sleep(RandomInteger(200, 500))
  1122. GoTo Re
  1123. End If
  1124. End Try
  1125. End Function
  1126. ''' <summary>
  1127. ''' 获取文件 SHA1,若失败则返回空字符串。
  1128. ''' </summary>
  1129. Public Function GetFileSHA1(FilePath As String) As String
  1130. Dim Retry As Boolean = False
  1131. Re:
  1132. Try
  1133. '获取 SHA1
  1134. Dim file As New FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
  1135. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1136. Dim retval As Byte() = sha1.ComputeHash(file)
  1137. file.Close()
  1138. Dim Result As New StringBuilder()
  1139. For i As Integer = 0 To retval.Length - 1
  1140. Result.Append(retval(i).ToString("x2"))
  1141. Next
  1142. Return Result.ToString
  1143. Catch ex As Exception
  1144. If Retry OrElse TypeOf ex Is FileNotFoundException Then
  1145. Log(ex, "获取文件 SHA1 失败:" & FilePath)
  1146. Return ""
  1147. Else
  1148. Retry = True
  1149. Log(ex, "获取文件 SHA1 可重试失败:" & FilePath, LogLevel.Normal)
  1150. Thread.Sleep(RandomInteger(200, 500))
  1151. GoTo Re
  1152. End If
  1153. End Try
  1154. End Function
  1155. ''' <summary>
  1156. ''' 获取流的 SHA1,若失败则返回空字符串。
  1157. ''' </summary>
  1158. Public Function GetAuthSHA1(Stream As Stream) As String
  1159. Try
  1160. Dim sha1 As SHA1 = New SHA1CryptoServiceProvider()
  1161. Dim retval As Byte() = sha1.ComputeHash(Stream)
  1162. Dim Result As New StringBuilder()
  1163. For i As Integer = 0 To retval.Length - 1
  1164. Result.Append(retval(i).ToString("x2"))
  1165. Next
  1166. Return Result.ToString
  1167. Catch ex As Exception
  1168. Log(ex, "获取流 SHA1 失败")
  1169. Return ""
  1170. End Try
  1171. End Function
  1172. ''' <summary>
  1173. ''' 文件的校验规则。
  1174. ''' </summary>
  1175. Public Class FileChecker
  1176. ''' <summary>
  1177. ''' 文件的准确大小。
  1178. ''' </summary>
  1179. Public ActualSize As Long = -1
  1180. ''' <summary>
  1181. ''' 文件的最小大小。
  1182. ''' </summary>
  1183. Public MinSize As Long = -1
  1184. ''' <summary>
  1185. ''' 文件的 MD5、SHA1 或 SHA256。会根据输入字符串的长度自动判断种类。
  1186. ''' </summary>
  1187. Public Hash As String = Nothing
  1188. ''' <summary>
  1189. ''' 是否可以使用已经存在的文件。
  1190. ''' </summary>
  1191. Public CanUseExistsFile As Boolean = True
  1192. ''' <summary>
  1193. ''' 是否为 Json 文件。
  1194. ''' </summary>
  1195. Public IsJson As Boolean = False
  1196. 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)
  1197. Me.ActualSize = ActualSize
  1198. Me.MinSize = MinSize
  1199. Me.Hash = Hash
  1200. Me.CanUseExistsFile = CanUseExistsFile
  1201. Me.IsJson = IsJson
  1202. End Sub
  1203. ''' <summary>
  1204. ''' 检查文件。若成功则返回 Nothing,失败则返回错误的描述文本,描述文本不以句号结尾。不会抛出错误。
  1205. ''' </summary>
  1206. Public Function Check(LocalPath As String) As String
  1207. Try
  1208. Dim Info As New FileInfo(LocalPath)
  1209. If Not Info.Exists Then Return "文件不存在:" & LocalPath
  1210. Dim FileSize As Long = Info.Length
  1211. If ActualSize >= 0 AndAlso ActualSize <> FileSize Then
  1212. Return $"文件大小应为 {ActualSize} B,实际为 {FileSize} B" &
  1213. If(FileSize < 2000, ",内容为:" & ReadFile(LocalPath), "")
  1214. End If
  1215. If MinSize >= 0 AndAlso MinSize > FileSize Then
  1216. Return $"文件大小应大于 {MinSize} B,实际为 {FileSize} B" &
  1217. If(FileSize < 2000, ",内容为:" & ReadFile(LocalPath), "")
  1218. End If
  1219. If Not String.IsNullOrEmpty(Hash) Then
  1220. If Hash.Length < 35 Then 'MD5
  1221. If Hash.ToLowerInvariant <> GetFileMD5(LocalPath) Then Return "文件 MD5 应为 " & Hash & ",实际为 " & GetFileMD5(LocalPath)
  1222. ElseIf Hash.Length = 64 Then 'SHA256
  1223. If Hash.ToLowerInvariant <> GetFileSHA256(LocalPath) Then Return "文件 SHA256 应为 " & Hash & ",实际为 " & GetFileSHA256(LocalPath)
  1224. Else 'SHA1 (40)
  1225. If Hash.ToLowerInvariant <> GetFileSHA1(LocalPath) Then Return "文件 SHA1 应为 " & Hash & ",实际为 " & GetFileSHA1(LocalPath)
  1226. End If
  1227. End If
  1228. If IsJson Then
  1229. Dim Content As String = ReadFile(LocalPath)
  1230. If Content = "" Then Throw New Exception("读取到的文件为空")
  1231. Try
  1232. GetJson(Content)
  1233. Catch ex As Exception
  1234. Throw New Exception("不是有效的 json 文件", ex)
  1235. End Try
  1236. End If
  1237. Return Nothing
  1238. Catch ex As Exception
  1239. Log(ex, "检查文件出错")
  1240. Return GetExceptionSummary(ex)
  1241. End Try
  1242. End Function
  1243. End Class
  1244. ''' <summary>
  1245. ''' 尝试根据后缀名判断文件种类并解压文件,支持 gz 与 zip,会尝试将 jar 以 zip 方式解压。
  1246. ''' 会尝试创建,但不会清空目标文件夹。
  1247. ''' </summary>
  1248. Public Sub ExtractFile(CompressFilePath As String, DestDirectory As String, Optional Encode As Encoding = Nothing,
  1249. Optional ProgressIncrementHandler As Action(Of Double) = Nothing)
  1250. Directory.CreateDirectory(DestDirectory)
  1251. If CompressFilePath.EndsWithF(".gz", True) Then
  1252. '以 gz 方式解压
  1253. Dim stream As New GZipStream(New FileStream(CompressFilePath, FileMode.Open, FileAccess.ReadWrite), CompressionMode.Decompress)
  1254. Dim decompressedFile As New FileStream(DestDirectory & GetFileNameFromPath(CompressFilePath).ToLower.Replace(".tar", "").Replace(".gz", ""), FileMode.OpenOrCreate, FileAccess.Write)
  1255. Dim data As Integer = stream.ReadByte()
  1256. While data <> -1
  1257. decompressedFile.WriteByte(data)
  1258. data = stream.ReadByte()
  1259. End While
  1260. decompressedFile.Close()
  1261. stream.Close()
  1262. Else
  1263. '以 zip 方式解压
  1264. Using Archive = ZipFile.Open(CompressFilePath, ZipArchiveMode.Read, If(Encode, Encoding.GetEncoding("GB18030")))
  1265. Dim TotalCount As Integer = Archive.Entries.Count
  1266. For Each Entry As ZipArchiveEntry In Archive.Entries
  1267. If ProgressIncrementHandler IsNot Nothing Then ProgressIncrementHandler(1 / TotalCount)
  1268. Dim DestinationPath As String = IO.Path.Combine(DestDirectory, Entry.FullName)
  1269. If DestinationPath.EndsWithF("\") OrElse DestinationPath.EndsWithF("/") Then
  1270. Continue For '不创建空文件夹
  1271. Else
  1272. Directory.CreateDirectory(GetPathFromFullPath(DestinationPath))
  1273. Entry.ExtractToFile(DestinationPath, True)
  1274. End If
  1275. Next
  1276. End Using
  1277. End If
  1278. End Sub
  1279. ''' <summary>
  1280. ''' 删除文件夹,返回删除的文件个数。通过参数选择是否抛出异常。
  1281. ''' </summary>
  1282. Public Function DeleteDirectory(Path As String, Optional IgnoreIssue As Boolean = False) As Integer
  1283. If Not Directory.Exists(Path) Then Return 0
  1284. Dim DeletedCount As Integer = 0
  1285. Dim Files As String()
  1286. Try
  1287. Files = Directory.GetFiles(Path)
  1288. Catch ex As DirectoryNotFoundException '#4549
  1289. Log(ex, $"疑似为孤立符号链接,尝试直接删除({Path})", LogLevel.Developer)
  1290. Directory.Delete(Path)
  1291. Return 0
  1292. End Try
  1293. For Each FilePath As String In Files
  1294. Dim RetriedFile As Boolean = False
  1295. RetryFile:
  1296. Try
  1297. File.Delete(FilePath)
  1298. DeletedCount += 1
  1299. Catch ex As Exception
  1300. If Not RetriedFile Then
  1301. RetriedFile = True
  1302. Log(ex, $"删除文件失败,将在 0.3s 后重试({FilePath})")
  1303. Thread.Sleep(300)
  1304. GoTo RetryFile
  1305. ElseIf IgnoreIssue Then
  1306. Log(ex, "删除单个文件可忽略地失败")
  1307. Else
  1308. Throw
  1309. End If
  1310. End Try
  1311. Next
  1312. For Each str As String In Directory.GetDirectories(Path)
  1313. DeleteDirectory(str, IgnoreIssue)
  1314. Next
  1315. Dim RetriedDir As Boolean = False
  1316. RetryDir:
  1317. Try
  1318. Directory.Delete(Path, True)
  1319. Catch ex As Exception
  1320. If Not RetriedDir Then
  1321. RetriedDir = True
  1322. Log(ex, $"删除文件夹失败,将在 0.3s 后重试({Path})")
  1323. Thread.Sleep(300)
  1324. GoTo RetryDir
  1325. ElseIf IgnoreIssue Then
  1326. Log(ex, "删除单个文件夹可忽略地失败")
  1327. Else
  1328. Throw
  1329. End If
  1330. End Try
  1331. Return DeletedCount
  1332. End Function
  1333. ''' <summary>
  1334. ''' 复制文件夹,失败会抛出异常。
  1335. ''' </summary>
  1336. Public Sub CopyDirectory(FromPath As String, ToPath As String, Optional ProgressIncrementHandler As Action(Of Double) = Nothing)
  1337. FromPath = FromPath.Replace("/", "\")
  1338. If Not FromPath.EndsWithF("\") Then FromPath &= "\"
  1339. ToPath = ToPath.Replace("/", "\")
  1340. If Not ToPath.EndsWithF("\") Then ToPath &= "\"
  1341. Dim AllFiles = EnumerateFiles(FromPath).ToList
  1342. Dim FileCount As Integer = AllFiles.Count
  1343. For Each File In AllFiles
  1344. CopyFile(File.FullName, File.FullName.Replace(FromPath, ToPath))
  1345. If ProgressIncrementHandler IsNot Nothing Then ProgressIncrementHandler(1 / FileCount)
  1346. Next
  1347. End Sub
  1348. ''' <summary>
  1349. ''' 遍历文件夹中的所有文件。
  1350. ''' </summary>
  1351. Public Function EnumerateFiles(Directory As String) As IEnumerable(Of FileInfo)
  1352. Dim Info As New DirectoryInfo(ShortenPath(Directory))
  1353. If Not Info.Exists Then Return New List(Of FileInfo)
  1354. Return Info.EnumerateFiles("*", SearchOption.AllDirectories)
  1355. End Function
  1356. ''' <summary>
  1357. ''' 若路径长度大于指定值,则将长路径转换为短路径。
  1358. ''' </summary>
  1359. Public Function ShortenPath(LongPath As String, Optional ShortenThreshold As Integer = 247) As String
  1360. If LongPath.Length <= ShortenThreshold Then Return LongPath
  1361. Dim ShortPath As New StringBuilder(260)
  1362. GetShortPathName(LongPath, ShortPath, 260)
  1363. Return ShortPath.ToString
  1364. End Function
  1365. Private Declare Function GetShortPathName Lib "kernel32" Alias "GetShortPathNameA" (ByVal lpszLongPath As String, ByVal lpszShortPath As StringBuilder, ByVal cchBuffer As Integer) As Integer
  1366. #End Region
  1367. #Region "文本"
  1368. Public vbLQ As Char = Convert.ToChar(8220)
  1369. Public vbRQ As Char = Convert.ToChar(8221)
  1370. ''' <summary>
  1371. ''' 提取 Exception 的具体描述与堆栈。
  1372. ''' </summary>
  1373. ''' <param name="ShowAllStacks">是否必须显示所有堆栈。通常用于判定堆栈信息。</param>
  1374. Public Function GetExceptionDetail(Ex As Exception, Optional ShowAllStacks As Boolean = False) As String
  1375. If Ex Is Nothing Then Return "无可用错误信息!"
  1376. '获取最底层的异常
  1377. Dim InnerEx As Exception = Ex
  1378. Do Until InnerEx.InnerException Is Nothing
  1379. InnerEx = InnerEx.InnerException
  1380. Loop
  1381. '获取各级错误的描述与堆栈信息
  1382. Dim DescList As New List(Of String)
  1383. Dim IsInner As Boolean = False
  1384. Do Until Ex Is Nothing
  1385. DescList.Add(If(IsInner, "→ ", "") & Ex.Message.Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, vbCrLf))
  1386. If Ex.StackTrace IsNot Nothing Then
  1387. For Each Stack As String In Ex.StackTrace.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
  1388. If ShowAllStacks OrElse Stack.ContainsF("pcl", True) Then
  1389. DescList.Add(Stack.Replace(vbCr, String.Empty).Replace(vbLf, String.Empty))
  1390. End If
  1391. Next
  1392. End If
  1393. If Ex.GetType.FullName <> "System.Exception" Then DescList.Add(" 错误类型:" & Ex.GetType.FullName)
  1394. Ex = Ex.InnerException
  1395. IsInner = True
  1396. Loop
  1397. '常见错误(记得同时修改下面的)
  1398. Dim CommonReason As String = Nothing
  1399. If TypeOf InnerEx Is TypeLoadException OrElse TypeOf InnerEx Is BadImageFormatException OrElse TypeOf InnerEx Is MissingMethodException OrElse TypeOf InnerEx Is NotImplementedException OrElse TypeOf InnerEx Is TypeInitializationException Then
  1400. CommonReason = "PCL 的运行环境存在问题。请尝试重新安装 .NET Framework 4.6.2 然后再试。若无法安装,请先卸载较新版本的 .NET Framework,然后再尝试安装。"
  1401. ElseIf TypeOf InnerEx Is UnauthorizedAccessException Then
  1402. CommonReason = "PCL 的权限不足。请尝试右键 PCL,选择以管理员身份运行。"
  1403. ElseIf TypeOf InnerEx Is OutOfMemoryException Then
  1404. CommonReason = "你的电脑运行内存不足,导致 PCL 无法继续运行。请在关闭一部分不需要的程序后再试。"
  1405. ElseIf TypeOf InnerEx Is Runtime.InteropServices.COMException Then
  1406. CommonReason = "由于操作系统或显卡存在问题,导致出现错误。请尝试重启 PCL。"
  1407. ElseIf {"远程主机强迫关闭了", "远程方已关闭传输流", "未能解析此远程名称", "由于目标计算机积极拒绝",
  1408. "操作已超时", "操作超时", "服务器超时", "连接超时"}.Any(Function(s) DescList.Any(Function(l) l.Contains(s))) Then
  1409. CommonReason = "你的网络环境不佳,导致难以连接到服务器。请检查网络,多重试几次,或尝试使用 VPN。"
  1410. End If
  1411. '构造输出信息
  1412. If CommonReason Is Nothing Then
  1413. Return DescList.Join(vbCrLf)
  1414. Else
  1415. Return CommonReason & vbCrLf & vbCrLf & "————————————" & vbCrLf & "详细错误信息:" & vbCrLf & DescList.Join(vbCrLf)
  1416. End If
  1417. End Function
  1418. ''' <summary>
  1419. ''' 提取 Exception 描述,汇总到一行。
  1420. ''' </summary>
  1421. Public Function GetExceptionSummary(Ex As Exception) As String
  1422. If Ex Is Nothing Then Return "无可用错误信息!"
  1423. '获取最底层的异常
  1424. Dim InnerEx As Exception = Ex
  1425. Do Until InnerEx.InnerException Is Nothing
  1426. InnerEx = InnerEx.InnerException
  1427. Loop
  1428. '获取各级错误的描述
  1429. Dim DescList As New List(Of String)
  1430. Do Until Ex Is Nothing
  1431. DescList.Add(Ex.Message.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr & vbCr, vbCr).Replace(vbCr, " "))
  1432. Ex = Ex.InnerException
  1433. Loop
  1434. DescList = DescList.Distinct.ToList
  1435. Dim Desc As String = Join(DescList, vbCrLf & "→ ")
  1436. '常见错误(记得同时修改上面的)
  1437. Dim CommonReason As String = Nothing
  1438. If TypeOf InnerEx Is TypeLoadException OrElse TypeOf InnerEx Is BadImageFormatException OrElse TypeOf InnerEx Is MissingMethodException OrElse TypeOf InnerEx Is NotImplementedException OrElse TypeOf InnerEx Is TypeInitializationException Then
  1439. CommonReason = "PCL 的运行环境存在问题。请尝试重新安装 .NET Framework 4.6.2 然后再试。若无法安装,请先卸载较新版本的 .NET Framework,然后再尝试安装。"
  1440. ElseIf TypeOf InnerEx Is UnauthorizedAccessException Then
  1441. CommonReason = "PCL 的权限不足。请尝试右键 PCL,选择以管理员身份运行。"
  1442. ElseIf TypeOf InnerEx Is OutOfMemoryException Then
  1443. CommonReason = "你的电脑运行内存不足,导致 PCL 无法继续运行。请在关闭一部分不需要的程序后再试。"
  1444. ElseIf TypeOf InnerEx Is Runtime.InteropServices.COMException Then
  1445. CommonReason = "由于操作系统或显卡存在问题,导致出现错误。请尝试重启 PCL。"
  1446. ElseIf {"远程主机强迫关闭了", "远程方已关闭传输流", "未能解析此远程名称", "由于目标计算机积极拒绝",
  1447. "操作已超时", "操作超时", "服务器超时", "连接超时"}.Any(Function(s) Desc.Contains(s)) Then
  1448. CommonReason = "你的网络环境不佳,导致难以连接到服务器。请检查网络,多重试几次,或尝试使用 VPN。"
  1449. End If
  1450. '构造输出信息
  1451. If CommonReason IsNot Nothing Then
  1452. Return CommonReason & "详细错误:" & DescList.First
  1453. Else
  1454. DescList.Reverse() '让最深层错误在最左边
  1455. Return Join(DescList, " ← ")
  1456. End If
  1457. End Function
  1458. ''' <summary>
  1459. ''' 返回一个枚举对应的字符串。
  1460. ''' </summary>
  1461. ''' <param name="EnumData">一个已经实例化的枚举类型。</param>
  1462. Public Function GetStringFromEnum(EnumData As [Enum]) As String
  1463. Return [Enum].GetName(EnumData.GetType, EnumData)
  1464. End Function
  1465. ''' <summary>
  1466. ''' 将文件大小转化为适合的文本形式,如“1.28 M”。
  1467. ''' </summary>
  1468. ''' <param name="FileSize">以字节为单位的大小表示。</param>
  1469. Public Function GetString(FileSize As Long) As String
  1470. Dim IsNegative = FileSize < 0
  1471. If IsNegative Then FileSize *= -1
  1472. If FileSize < 1000 Then
  1473. 'B 级
  1474. Return If(IsNegative, "-", "") & FileSize & " B"
  1475. ElseIf FileSize < 1024 * 1000 Then
  1476. 'K 级
  1477. Dim RoundResult As String = Math.Round(FileSize / 1024)
  1478. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " K"
  1479. ElseIf FileSize < 1024 * 1024 * 1000 Then
  1480. 'M 级
  1481. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024)
  1482. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024 / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " M"
  1483. Else
  1484. 'G 级
  1485. Dim RoundResult As String = Math.Round(FileSize / 1024 / 1024 / 1024)
  1486. Return If(IsNegative, "-", "") & Math.Round(FileSize / 1024 / 1024 / 1024, CInt(MathClamp(3 - RoundResult.Length, 0, 2))) & " G"
  1487. End If
  1488. End Function
  1489. ''' <summary>
  1490. ''' 获取 JSON 对象。
  1491. ''' </summary>
  1492. Public Function GetJson(Data As String)
  1493. Try
  1494. Return JsonConvert.DeserializeObject(Data, New JsonSerializerSettings With {.DateTimeZoneHandling = DateTimeZoneHandling.Local})
  1495. Catch ex As Exception
  1496. Dim Length As Integer = If(Data, "").Length
  1497. Throw New Exception("格式化 JSON 失败:" & If(Length > 2000, Data.Substring(0, 500) & $"...(全长 {Length} 个字符)..." & Right(Data, 500), Data))
  1498. End Try
  1499. End Function
  1500. ''' <summary>
  1501. ''' 将第一个字符转换为大写,其余字符转换为小写。
  1502. ''' </summary>
  1503. <Extension> Public Function Capitalize(word As String) As String
  1504. If String.IsNullOrEmpty(word) Then Return word
  1505. Return word.Substring(0, 1).ToUpperInvariant() & word.Substring(1).ToLowerInvariant()
  1506. End Function
  1507. ''' <summary>
  1508. ''' 将字符串统一至某个长度,过短则以 Code 将其右侧填充,过长则截取靠左的指定长度。
  1509. ''' </summary>
  1510. Public Function StrFill(Str As String, Code As String, Length As Byte) As String
  1511. If Str.Length > Length Then Return Mid(Str, 1, Length)
  1512. Return Mid(Str.PadRight(Length, Code), Str.Length + 1) & Str
  1513. End Function
  1514. ''' <summary>
  1515. ''' 将一个小数显示为固定的小数点后位数形式,将向零取整。
  1516. ''' 如 12 保留 2 位则输出 12.00,而 95.678 保留 2 位则输出 95.67。
  1517. ''' </summary>
  1518. Public Function StrFillNum(Num As Double, Length As Integer) As String
  1519. Num = Math.Round(Num, Length, MidpointRounding.AwayFromZero)
  1520. StrFillNum = Num
  1521. If Not StrFillNum.Contains(".") Then Return (StrFillNum & ".").PadRight(StrFillNum.Length + 1 + Length, "0")
  1522. Return StrFillNum.PadRight(StrFillNum.Split(".")(0).Length + 1 + Length, "0")
  1523. End Function
  1524. ''' <summary>
  1525. ''' 移除字符串首尾的标点符号、回车,以及括号中、冒号后的补充说明内容。
  1526. ''' </summary>
  1527. Public Function StrTrim(Str As String, Optional RemoveQuote As Boolean = True)
  1528. If RemoveQuote Then Str = Str.Split("(")(0).Split(":")(0).Split("(")(0).Split(":")(0)
  1529. Return Str.Trim(".", "。", "!", " ", "!", "?", "?", vbCr, vbLf)
  1530. End Function
  1531. ''' <summary>
  1532. ''' 连接字符串。
  1533. ''' </summary>
  1534. <Extension> Public Function Join(List As IEnumerable, Split As String) As String
  1535. Dim Builder As New StringBuilder
  1536. Dim IsFirst As Boolean = True
  1537. For Each Element In List
  1538. If IsFirst Then
  1539. IsFirst = False
  1540. Else
  1541. Builder.Append(Split)
  1542. End If
  1543. If Element IsNot Nothing Then Builder.Append(Element)
  1544. Next
  1545. Return Builder.ToString
  1546. End Function
  1547. ''' <summary>
  1548. ''' 分割字符串。
  1549. ''' </summary>
  1550. <Extension> Public Function Split(FullStr As String, SplitStr As String) As String()
  1551. If SplitStr.Length = 1 Then
  1552. Return FullStr.Split(SplitStr(0))
  1553. Else
  1554. Return FullStr.Split({SplitStr}, StringSplitOptions.None)
  1555. End If
  1556. End Function
  1557. ''' <summary>
  1558. ''' 获取字符串哈希值。
  1559. ''' </summary>
  1560. Public Function GetHash(Str As String) As ULong
  1561. GetHash = 5381
  1562. For i = 0 To Str.Length - 1
  1563. GetHash = (GetHash << 5) Xor GetHash Xor CType(AscW(Str(i)), ULong)
  1564. Next
  1565. Return GetHash Xor &HA98F501BC684032FUL
  1566. End Function
  1567. ''' <summary>
  1568. ''' 获取字符串 MD5。
  1569. ''' </summary>
  1570. Public Function GetStringMD5(Str As String) As String
  1571. Dim md5Hasher As New MD5CryptoServiceProvider
  1572. Dim hashedDataBytes As Byte()
  1573. hashedDataBytes = md5Hasher.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(Str))
  1574. Dim tmp As New StringBuilder()
  1575. For Each i As Byte In hashedDataBytes
  1576. tmp.Append(i.ToString("x2"))
  1577. Next
  1578. Return tmp.ToString()
  1579. End Function
  1580. ''' <summary>
  1581. ''' 检查字符串中的字符是否均为 ASCII 字符。
  1582. ''' </summary>
  1583. <Extension> Public Function IsASCII(Input As String) As Boolean
  1584. Return Input.All(Function(c) AscW(c) < 128)
  1585. End Function
  1586. ''' <summary>
  1587. ''' 获取在子字符串第一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024。
  1588. ''' 如果未找到子字符串则不裁切。
  1589. ''' </summary>
  1590. <Extension> Public Function BeforeFirst(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1591. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.IndexOfF(Text, IgnoreCase))
  1592. If Pos >= 0 Then
  1593. Return Str.Substring(0, Pos)
  1594. Else
  1595. Return Str
  1596. End If
  1597. End Function
  1598. ''' <summary>
  1599. ''' 获取在子字符串最后一次出现之前的部分,例如对 2024/11/08 拆切 / 会得到 2024/11。
  1600. ''' 如果未找到子字符串则不裁切。
  1601. ''' </summary>
  1602. <Extension> Public Function BeforeLast(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1603. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.LastIndexOfF(Text, IgnoreCase))
  1604. If Pos >= 0 Then
  1605. Return Str.Substring(0, Pos)
  1606. Else
  1607. Return Str
  1608. End If
  1609. End Function
  1610. ''' <summary>
  1611. ''' 获取在子字符串第一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 11/08。
  1612. ''' 如果未找到子字符串则不裁切。
  1613. ''' </summary>
  1614. <Extension> Public Function AfterFirst(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1615. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.IndexOfF(Text, IgnoreCase))
  1616. If Pos >= 0 Then
  1617. Return Str.Substring(Pos + Text.Length)
  1618. Else
  1619. Return Str
  1620. End If
  1621. End Function
  1622. ''' <summary>
  1623. ''' 获取在子字符串最后一次出现之后的部分,例如对 2024/11/08 拆切 / 会得到 08。
  1624. ''' 如果未找到子字符串则不裁切。
  1625. ''' </summary>
  1626. <Extension> Public Function AfterLast(Str As String, Text As String, Optional IgnoreCase As Boolean = False) As String
  1627. Dim Pos As Integer = If(String.IsNullOrEmpty(Text), -1, Str.LastIndexOfF(Text, IgnoreCase))
  1628. If Pos >= 0 Then
  1629. Return Str.Substring(Pos + Text.Length)
  1630. Else
  1631. Return Str
  1632. End If
  1633. End Function
  1634. ''' <summary>
  1635. ''' 获取处于两个子字符串之间的部分,裁切尽可能多的内容。
  1636. ''' 等效于 AfterLast 后接 BeforeFirst。
  1637. ''' 如果未找到子字符串则不裁切。
  1638. ''' </summary>
  1639. <Extension> Public Function Between(Str As String, After As String, Before As String, Optional IgnoreCase As Boolean = False) As String
  1640. Dim StartPos As Integer = If(String.IsNullOrEmpty(After), -1, Str.LastIndexOfF(After, IgnoreCase))
  1641. If StartPos >= 0 Then
  1642. StartPos += After.Length
  1643. Else
  1644. StartPos = 0
  1645. End If
  1646. Dim EndPos As Integer = If(String.IsNullOrEmpty(Before), -1, Str.IndexOfF(Before, StartPos, IgnoreCase))
  1647. If EndPos >= 0 Then
  1648. Return Str.Substring(StartPos, EndPos - StartPos)
  1649. ElseIf StartPos > 0 Then
  1650. Return Str.Substring(StartPos)
  1651. Else
  1652. Return Str
  1653. End If
  1654. End Function
  1655. ''' <summary>
  1656. ''' 高速的 StartsWith。
  1657. ''' </summary>
  1658. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1659. Public Function StartsWithF(Str As String, Prefix As String, Optional IgnoreCase As Boolean = False) As Boolean
  1660. Return Str.StartsWith(Prefix, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1661. End Function
  1662. ''' <summary>
  1663. ''' 高速的 EndsWith。
  1664. ''' </summary>
  1665. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1666. Public Function EndsWithF(Str As String, Suffix As String, Optional IgnoreCase As Boolean = False) As Boolean
  1667. Return Str.EndsWith(Suffix, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1668. End Function
  1669. ''' <summary>
  1670. ''' 支持可变大小写判断的 Contains。
  1671. ''' </summary>
  1672. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1673. Public Function ContainsF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Boolean
  1674. Return Str.IndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal)) >= 0
  1675. End Function
  1676. ''' <summary>
  1677. ''' 高速的 IndexOf。
  1678. ''' </summary>
  1679. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1680. Public Function IndexOfF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Integer
  1681. Return Str.IndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1682. End Function
  1683. ''' <summary>
  1684. ''' 高速的 IndexOf。
  1685. ''' </summary>
  1686. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1687. Public Function IndexOfF(Str As String, SubStr As String, StartIndex As Integer, Optional IgnoreCase As Boolean = False) As Integer
  1688. Return Str.IndexOf(SubStr, StartIndex, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1689. End Function
  1690. ''' <summary>
  1691. ''' 高速的 LastIndexOf。
  1692. ''' </summary>
  1693. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1694. Public Function LastIndexOfF(Str As String, SubStr As String, Optional IgnoreCase As Boolean = False) As Integer
  1695. Return Str.LastIndexOf(SubStr, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1696. End Function
  1697. ''' <summary>
  1698. ''' 高速的 LastIndexOf。
  1699. ''' </summary>
  1700. <Extension> <MethodImpl(MethodImplOptions.AggressiveInlining)>
  1701. Public Function LastIndexOfF(Str As String, SubStr As String, StartIndex As Integer, Optional IgnoreCase As Boolean = False) As Integer
  1702. Return Str.LastIndexOf(SubStr, StartIndex, If(IgnoreCase, StringComparison.OrdinalIgnoreCase, StringComparison.Ordinal))
  1703. End Function
  1704. ''' <summary>
  1705. ''' 不会报错的 Val。
  1706. ''' 如果输入有误,返回 0。
  1707. ''' </summary>
  1708. Public Function Val(Str As Object) As Double
  1709. Try
  1710. Return If(TypeOf Str Is String AndAlso Str = "&", 0, Conversion.Val(Str))
  1711. Catch
  1712. Return 0
  1713. End Try
  1714. End Function
  1715. '转义
  1716. ''' <summary>
  1717. ''' 为字符串进行 XML 转义。
  1718. ''' </summary>
  1719. Public Function EscapeXML(Str As String) As String
  1720. If Str.StartsWithF("{") Then Str = "{}" & Str '#4187
  1721. Return Str.
  1722. Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("'", "&apos;").
  1723. Replace("""", "&quot;").Replace(vbCrLf, "&#xa;")
  1724. End Function
  1725. ''' <summary>
  1726. ''' 为字符串进行 Like 关键字转义。
  1727. ''' </summary>
  1728. Public Function EscapeLikePattern(input As String) As String
  1729. Dim sb As New StringBuilder()
  1730. For Each c As Char In input
  1731. Select Case c
  1732. Case "["c, "]"c, "*"c, "?"c, "#"c
  1733. sb.Append("["c).Append(c).Append("]"c)
  1734. Case Else
  1735. sb.Append(c)
  1736. End Select
  1737. Next
  1738. Return sb.ToString()
  1739. End Function
  1740. '正则
  1741. ''' <summary>
  1742. ''' 搜索字符串中的所有正则匹配项。
  1743. ''' </summary>
  1744. <Extension> Public Function RegexSearch(str As String, regex As String, Optional options As RegexOptions = RegexOptions.None) As List(Of String)
  1745. Try
  1746. RegexSearch = New List(Of String)
  1747. Dim RegexSearchRes = New Regex(regex, options).Matches(str)
  1748. If RegexSearchRes Is Nothing Then Return RegexSearch
  1749. For Each item As Match In RegexSearchRes
  1750. RegexSearch.Add(item.Value)
  1751. Next
  1752. Catch ex As Exception
  1753. Log(ex, "正则匹配全部项出错")
  1754. Return New List(Of String)
  1755. End Try
  1756. End Function
  1757. ''' <summary>
  1758. ''' 获取字符串中的第一个正则匹配项,若无匹配则返回 Nothing。
  1759. ''' </summary>
  1760. <Extension> Public Function RegexSeek(str As String, regex As String, Optional options As RegexOptions = RegexOptions.None) As String
  1761. Try
  1762. Dim Result = RegularExpressions.Regex.Match(str, regex, options).Value
  1763. Return If(Result = "", Nothing, Result)
  1764. Catch ex As Exception
  1765. Log(ex, "正则匹配第一项出错")
  1766. Return Nothing
  1767. End Try
  1768. End Function
  1769. ''' <summary>
  1770. ''' 检查字符串是否匹配某正则模式。
  1771. ''' </summary>
  1772. <Extension> Public Function RegexCheck(str As String, regex As String, Optional options As RegexOptions = RegexOptions.None) As Boolean
  1773. Try
  1774. Return RegularExpressions.Regex.IsMatch(str, regex, options)
  1775. Catch ex As Exception
  1776. Log(ex, "正则检查出错")
  1777. Return False
  1778. End Try
  1779. End Function
  1780. ''' <summary>
  1781. ''' 进行正则替换,会抛出错误。
  1782. ''' </summary>
  1783. <Extension> Public Function RegexReplace(AllContents As String, SearchRegex As String, ReplaceTo As String, Optional options As RegexOptions = RegexOptions.None) As String
  1784. Return Regex.Replace(AllContents, SearchRegex, ReplaceTo, options)
  1785. End Function
  1786. ''' <summary>
  1787. ''' 对每个正则匹配分别进行替换,会抛出错误。
  1788. ''' </summary>
  1789. <Extension> Public Function RegexReplaceEach(AllContents As String, SearchRegex As String, ReplaceTo As MatchEvaluator, Optional options As RegexOptions = RegexOptions.None) As String
  1790. Return Regex.Replace(AllContents, SearchRegex, ReplaceTo, options)
  1791. End Function
  1792. #End Region
  1793. #Region "搜索"
  1794. ''' <summary>
  1795. ''' 获取搜索文本的相似度。
  1796. ''' </summary>
  1797. ''' <param name="Source">被搜索的长内容。</param>
  1798. ''' <param name="Query">用户输入的搜索文本。</param>
  1799. Private Function SearchSimilarity(Source As String, Query As String) As Double
  1800. Dim qp As Integer = 0, lenSum As Double = 0
  1801. Source = Source.ToLower.Replace(" ", "")
  1802. Query = Query.ToLower.Replace(" ", "")
  1803. Dim sourceLength As Integer = Source.Length, queryLength As Integer = Query.Length '用于计算最后因数的长度缓存
  1804. Do While qp < queryLength
  1805. '对 qp 作为开始位置计算
  1806. Dim sp As Integer = 0, lenMax As Integer = 0, spMax As Integer = 0
  1807. '查找以 qp 为头的最大子串
  1808. Do While sp < Source.Length
  1809. '对每个 sp 作为开始位置计算最大子串
  1810. Dim len As Integer = 0
  1811. Do While (qp + len) < queryLength AndAlso (sp + len) < Source.Length AndAlso Source(sp + len) = Query(qp + len)
  1812. len += 1
  1813. Loop
  1814. '存储 len
  1815. If len > lenMax Then
  1816. lenMax = len
  1817. spMax = sp
  1818. End If
  1819. '根据结果增加 sp
  1820. sp += Math.Max(1, len)
  1821. Loop
  1822. If lenMax > 0 Then
  1823. Source = Source.Substring(0, spMax) & If(Source.Count > spMax + lenMax, Source.Substring(spMax + lenMax), String.Empty) '将源中的对应字段替换空
  1824. '存储 lenSum
  1825. Dim IncWeight = (Math.Pow(1.4, 3 + lenMax) - 3.6) '根据长度加成
  1826. IncWeight *= 1 + 0.3 * Math.Max(0, 3 - Math.Abs(qp - spMax)) '根据位置加成
  1827. lenSum += IncWeight
  1828. End If
  1829. '根据结果增加 qp
  1830. qp += Math.Max(1, lenMax)
  1831. Loop
  1832. '计算结果:重复字段量 × 源长度影响比例
  1833. Return (lenSum / queryLength) * (3 / Math.Pow(sourceLength + 15, 0.5)) * If(queryLength <= 2, 3 - queryLength, 1)
  1834. End Function
  1835. ''' <summary>
  1836. ''' 获取多段文本加权后的相似度。
  1837. ''' </summary>
  1838. Private Function SearchSimilarityWeighted(Source As List(Of KeyValuePair(Of String, Double)), Query As String) As Double
  1839. Dim TotalWeight As Double = 0
  1840. Dim Sum As Double = 0
  1841. For Each Pair In Source
  1842. Sum += SearchSimilarity(Pair.Key, Query) * Pair.Value
  1843. TotalWeight += Pair.Value
  1844. Next
  1845. Return Sum / TotalWeight
  1846. End Function
  1847. ''' <summary>
  1848. ''' 用于搜索的项目。
  1849. ''' </summary>
  1850. Public Class SearchEntry(Of T)
  1851. ''' <summary>
  1852. ''' 该项目对应的源数据。
  1853. ''' </summary>
  1854. Public Item As T
  1855. ''' <summary>
  1856. ''' 该项目用于搜索的源。
  1857. ''' </summary>
  1858. Public SearchSource As List(Of KeyValuePair(Of String, Double))
  1859. ''' <summary>
  1860. ''' 相似度。
  1861. ''' </summary>
  1862. Public Similarity As Double
  1863. ''' <summary>
  1864. ''' 是否完全匹配。
  1865. ''' </summary>
  1866. Public AbsoluteRight As Boolean
  1867. End Class
  1868. ''' <summary>
  1869. ''' 进行多段文本加权搜索,获取相似度较高的数项结果。
  1870. ''' </summary>
  1871. ''' <param name="MaxBlurCount">返回的最大模糊结果数。</param>
  1872. ''' <param name="MinBlurSimilarity">返回结果要求的最低相似度。</param>
  1873. 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))
  1874. '初始化
  1875. Dim ResultList As New List(Of SearchEntry(Of T))
  1876. If Not Entries.Any() Then Return ResultList
  1877. '进行搜索,获取相似信息
  1878. For Each Entry In Entries
  1879. Entry.Similarity = SearchSimilarityWeighted(Entry.SearchSource, Query)
  1880. Entry.AbsoluteRight =
  1881. Query.Split(" ").All( '对于按空格分割的每一段
  1882. Function(QueryPart) Entry.SearchSource.Any( '若与任意一个搜索源完全匹配,则标记为完全匹配项
  1883. Function(Source) Source.Key.Replace(" ", "").ContainsF(QueryPart, True)))
  1884. Next
  1885. '按照相似度进行排序
  1886. Entries = Entries.Sort(
  1887. Function(Left, Right) As Boolean
  1888. If Left.AbsoluteRight Xor Right.AbsoluteRight Then
  1889. Return Left.AbsoluteRight
  1890. Else
  1891. Return Left.Similarity > Right.Similarity
  1892. End If
  1893. End Function)
  1894. '返回结果
  1895. Dim BlurCount As Integer = 0
  1896. For Each Entry In Entries
  1897. If Entry.AbsoluteRight Then
  1898. ResultList.Add(Entry) '完全匹配,直接加入
  1899. Else
  1900. If Entry.Similarity < MinBlurSimilarity OrElse BlurCount = MaxBlurCount Then Exit For '模糊结果边界条件
  1901. ResultList.Add(Entry)
  1902. BlurCount += 1 '模糊结果计数
  1903. End If
  1904. Next
  1905. Return ResultList
  1906. End Function
  1907. #End Region
  1908. #Region "系统"
  1909. ''' <summary>
  1910. ''' 线程安全的,可以直接使用 For Each 的 List。
  1911. ''' 在使用 For Each 循环时,列表的结果可能并非最新,但不会抛出异常。
  1912. ''' </summary>
  1913. Public Class SafeList(Of T)
  1914. Inherits SynchronizedCollection(Of T)
  1915. Implements IEnumerable, IEnumerable(Of T)
  1916. '构造函数
  1917. Public Sub New()
  1918. MyBase.New()
  1919. End Sub
  1920. Public Sub New(Data As IEnumerable(Of T))
  1921. MyBase.New(New Object, Data)
  1922. End Sub
  1923. Public Shared Widening Operator CType(Data As List(Of T)) As SafeList(Of T)
  1924. Return New SafeList(Of T)(Data)
  1925. End Operator
  1926. Public Shared Widening Operator CType(Data As SafeList(Of T)) As List(Of T)
  1927. Return New List(Of T)(Data)
  1928. End Operator
  1929. '基于 SyncLock 覆写
  1930. Public Overloads Function GetEnumerator() As IEnumerator(Of T) Implements IEnumerable(Of T).GetEnumerator
  1931. SyncLock SyncRoot
  1932. Return Items.ToList.GetEnumerator()
  1933. End SyncLock
  1934. End Function
  1935. Private Overloads Function GetEnumeratorGeneral() As IEnumerator Implements IEnumerable.GetEnumerator
  1936. SyncLock SyncRoot
  1937. Return Items.ToList.GetEnumerator()
  1938. End SyncLock
  1939. End Function
  1940. End Class
  1941. ''' <summary>
  1942. ''' 线程安全的,可以直接使用 For Each 的字典。
  1943. ''' 在使用 For Each 循环时,字典的结果可能并非最新,但不会抛出异常。
  1944. ''' </summary>
  1945. Public Class SafeDictionary(Of TKey, TValue)
  1946. Implements IDictionary(Of TKey, TValue)
  1947. Implements IEnumerable(Of KeyValuePair(Of TKey, TValue))
  1948. Private ReadOnly SyncRoot As New Object
  1949. Private ReadOnly _Dictionary As New Dictionary(Of TKey, TValue)
  1950. '构造函数
  1951. Public Sub New()
  1952. End Sub
  1953. Public Sub New(data As IEnumerable(Of KeyValuePair(Of TKey, TValue)))
  1954. For Each DataItem In data
  1955. _Dictionary.Add(DataItem.Key, DataItem.Value)
  1956. Next
  1957. End Sub
  1958. '线程安全的方法实现
  1959. Public Sub Add(key As TKey, value As TValue) Implements IDictionary(Of TKey, TValue).Add
  1960. SyncLock SyncRoot
  1961. _Dictionary.Add(key, value)
  1962. End SyncLock
  1963. End Sub
  1964. Public Function ContainsKey(key As TKey) As Boolean Implements IDictionary(Of TKey, TValue).ContainsKey
  1965. SyncLock SyncRoot
  1966. Return _Dictionary.ContainsKey(key)
  1967. End SyncLock
  1968. End Function
  1969. Public ReadOnly Property Keys As ICollection(Of TKey) Implements IDictionary(Of TKey, TValue).Keys
  1970. Get
  1971. SyncLock SyncRoot
  1972. Return New List(Of TKey)(_Dictionary.Keys)
  1973. End SyncLock
  1974. End Get
  1975. End Property
  1976. Public Function Remove(key As TKey) As Boolean Implements IDictionary(Of TKey, TValue).Remove
  1977. SyncLock SyncRoot
  1978. Return _Dictionary.Remove(key)
  1979. End SyncLock
  1980. End Function
  1981. Public Function TryGetValue(key As TKey, ByRef value As TValue) As Boolean Implements IDictionary(Of TKey, TValue).TryGetValue
  1982. SyncLock SyncRoot
  1983. Return _Dictionary.TryGetValue(key, value)
  1984. End SyncLock
  1985. End Function
  1986. Public ReadOnly Property Values As ICollection(Of TValue) Implements IDictionary(Of TKey, TValue).Values
  1987. Get
  1988. SyncLock SyncRoot
  1989. Return New List(Of TValue)(_Dictionary.Values)
  1990. End SyncLock
  1991. End Get
  1992. End Property
  1993. Default Public Property Item(key As TKey) As TValue Implements IDictionary(Of TKey, TValue).Item
  1994. Get
  1995. SyncLock SyncRoot
  1996. Return _Dictionary(key)
  1997. End SyncLock
  1998. End Get
  1999. Set(value As TValue)
  2000. SyncLock SyncRoot
  2001. _Dictionary(key) = value
  2002. End SyncLock
  2003. End Set
  2004. End Property
  2005. Public Sub Add(item As KeyValuePair(Of TKey, TValue)) Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Add
  2006. SyncLock SyncRoot
  2007. _Dictionary.Add(item.Key, item.Value)
  2008. End SyncLock
  2009. End Sub
  2010. Public Sub Clear() Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Clear
  2011. SyncLock SyncRoot
  2012. _Dictionary.Clear()
  2013. End SyncLock
  2014. End Sub
  2015. Public Function Contains(item As KeyValuePair(Of TKey, TValue)) As Boolean Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Contains
  2016. SyncLock SyncRoot
  2017. Return DirectCast(_Dictionary, IDictionary(Of TKey, TValue)).Contains(item)
  2018. End SyncLock
  2019. End Function
  2020. Public Sub CopyTo(array() As KeyValuePair(Of TKey, TValue), arrayIndex As Integer) Implements ICollection(Of KeyValuePair(Of TKey, TValue)).CopyTo
  2021. SyncLock SyncRoot
  2022. DirectCast(_Dictionary, IDictionary(Of TKey, TValue)).CopyTo(array, arrayIndex)
  2023. End SyncLock
  2024. End Sub
  2025. Public ReadOnly Property Count As Integer Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Count
  2026. Get
  2027. SyncLock SyncRoot
  2028. Return _Dictionary.Count
  2029. End SyncLock
  2030. End Get
  2031. End Property
  2032. Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of KeyValuePair(Of TKey, TValue)).IsReadOnly
  2033. Get
  2034. Return False
  2035. End Get
  2036. End Property
  2037. Public Function Remove(item As KeyValuePair(Of TKey, TValue)) As Boolean Implements ICollection(Of KeyValuePair(Of TKey, TValue)).Remove
  2038. SyncLock SyncRoot
  2039. Return DirectCast(_Dictionary, IDictionary(Of TKey, TValue)).Remove(item)
  2040. End SyncLock
  2041. End Function
  2042. '枚举器
  2043. Public Function GetEnumerator() As IEnumerator(Of KeyValuePair(Of TKey, TValue)) Implements IEnumerable(Of KeyValuePair(Of TKey, TValue)).GetEnumerator
  2044. SyncLock SyncRoot
  2045. Return New List(Of KeyValuePair(Of TKey, TValue))(_Dictionary).GetEnumerator()
  2046. End SyncLock
  2047. End Function
  2048. Private Function GetEnumeratorGeneral() As IEnumerator Implements IEnumerable.GetEnumerator
  2049. Return GetEnumerator()
  2050. End Function
  2051. End Class
  2052. ''' <summary>
  2053. ''' 可用于临时存放文件的,不含任何特殊字符的文件夹路径,以“\”结尾。
  2054. ''' </summary>
  2055. Public PathPure As String = GetPureASCIIDir()
  2056. Private Function GetPureASCIIDir() As String
  2057. If (Path & "PCL").IsASCII() Then
  2058. Return Path & "PCL\"
  2059. ElseIf PathAppdata.IsASCII() Then
  2060. Return PathAppdata
  2061. ElseIf PathTemp.IsASCII() Then
  2062. Return PathTemp
  2063. Else
  2064. Return OsDrive & "ProgramData\PCL\"
  2065. End If
  2066. End Function
  2067. ''' <summary>
  2068. ''' 指示接取到这个异常的函数进行重试。
  2069. ''' </summary>
  2070. Public Class RestartException
  2071. Inherits Exception
  2072. End Class
  2073. ''' <summary>
  2074. ''' 指示用户手动取消了操作,或用户已知晓操作被取消的原因。
  2075. ''' </summary>
  2076. Public Class CancelledException
  2077. Inherits Exception
  2078. End Class
  2079. ''' <summary>
  2080. ''' 当前程序是否拥有管理员权限。
  2081. ''' </summary>
  2082. Public Function IsAdmin() As Boolean
  2083. Dim id As WindowsIdentity = WindowsIdentity.GetCurrent()
  2084. Dim principal As New WindowsPrincipal(id)
  2085. Return principal.IsInRole(WindowsBuiltInRole.Administrator)
  2086. End Function
  2087. ''' <summary>
  2088. ''' 以管理员权限运行当前程序,并等待程序运行结束。
  2089. ''' 返回程序的返回代码,如果运行失败将抛出异常。
  2090. ''' </summary>
  2091. Public Function RunAsAdmin(Argument As String) As Integer
  2092. Dim NewProcess = Process.Start(New ProcessStartInfo(PathWithName) With {.Verb = "runas", .Arguments = Argument})
  2093. NewProcess.WaitForExit()
  2094. Return NewProcess.ExitCode
  2095. End Function
  2096. ''' <summary>
  2097. ''' 判断当前系统语言是否为 zh-CN。
  2098. ''' </summary>
  2099. Public Function IsSystemLanguageChinese() As Boolean
  2100. Return CultureInfo.CurrentCulture.Name = "zh-CN" OrElse CultureInfo.CurrentUICulture.Name = "zh-CN"
  2101. End Function
  2102. Private Uuid As Integer = 1
  2103. Private UuidLock As Object
  2104. ''' <summary>
  2105. ''' 获取一个全程序内不会重复的数字(伪 Uuid)。
  2106. ''' </summary>
  2107. Public Function GetUuid() As Integer
  2108. If UuidLock Is Nothing Then UuidLock = New Object
  2109. SyncLock UuidLock
  2110. Uuid += 1
  2111. Return Uuid
  2112. End SyncLock
  2113. End Function
  2114. ''' <summary>
  2115. ''' 将元素与 List 的混合体拆分为元素组。
  2116. ''' </summary>
  2117. Public Function GetFullList(Of T)(data As IList) As List(Of T)
  2118. GetFullList = New List(Of T)
  2119. For i = 0 To data.Count - 1
  2120. If TypeOf data(i) Is ICollection Then
  2121. GetFullList.AddRange(data(i))
  2122. Else
  2123. GetFullList.Add(data(i))
  2124. End If
  2125. Next i
  2126. End Function
  2127. ''' <summary>
  2128. ''' 数组去重。
  2129. ''' </summary>
  2130. <Extension> Public Function Distinct(Of T)(Arr As ICollection(Of T), IsEqual As ComparisonBoolean(Of T)) As List(Of T)
  2131. Dim ResultArray As New List(Of T)
  2132. For i = 0 To Arr.Count - 1
  2133. For ii = i + 1 To Arr.Count - 1
  2134. If IsEqual(Arr(i), Arr(ii)) Then GoTo NextElement
  2135. Next
  2136. ResultArray.Add(Arr(i))
  2137. NextElement:
  2138. Next i
  2139. Return ResultArray
  2140. End Function
  2141. ''' <summary>
  2142. ''' 获取格式类似于“11:08:52.037”的当前时间的字符串。
  2143. ''' </summary>
  2144. Public Function GetTimeNow() As String
  2145. Return Date.Now.ToString("HH':'mm':'ss'.'fff")
  2146. End Function
  2147. ''' <summary>
  2148. ''' 获取系统运行时间(毫秒),保证为正 Long 且大于 1,但可能突变减小。
  2149. ''' </summary>
  2150. Public Function GetTimeTick() As Long
  2151. Return My.Computer.Clock.TickCount + 2147483651L
  2152. End Function
  2153. ''' <summary>
  2154. ''' 将时间间隔转换为类似“5 分 10 秒前”的易于阅读的形式。
  2155. ''' </summary>
  2156. Public Function GetTimeSpanString(Span As TimeSpan, IsShortForm As Boolean) As String
  2157. Dim EndFix = If(Span.TotalMilliseconds > 0, "后", "前")
  2158. If Span.TotalMilliseconds < 0 Then Span = -Span
  2159. Dim TotalMonthes = Math.Floor(Span.Days / 30)
  2160. If IsShortForm Then
  2161. If TotalMonthes >= 12 Then
  2162. '1+ 年,“3 年”
  2163. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  2164. ElseIf TotalMonthes >= 2 Then
  2165. '2~11 月,“5 个月”
  2166. GetTimeSpanString = TotalMonthes & " 个月"
  2167. ElseIf Span.TotalDays >= 2 Then
  2168. '2 天 ~ 2 月,“23 天”
  2169. GetTimeSpanString = Span.Days & " 天"
  2170. ElseIf Span.TotalHours >= 1 Then
  2171. '1 小时 ~ 2 天,“15 小时”
  2172. GetTimeSpanString = Span.Hours & " 小时"
  2173. ElseIf Span.TotalMinutes >= 1 Then
  2174. '1 分钟 ~ 1 小时,“49 分钟”
  2175. GetTimeSpanString = Span.Minutes & " 分钟"
  2176. ElseIf Span.TotalSeconds >= 1 Then
  2177. '1 秒 ~ 1 分钟,“23 秒”
  2178. GetTimeSpanString = Span.Seconds & " 秒"
  2179. Else
  2180. '不到 1 秒
  2181. GetTimeSpanString = "1 秒"
  2182. End If
  2183. Else
  2184. If TotalMonthes >= 61 Then
  2185. '5+ 年,“5 年”
  2186. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年"
  2187. ElseIf TotalMonthes >= 12 Then
  2188. '12~60 月,“1 年 2 个月”
  2189. GetTimeSpanString = Math.Floor(TotalMonthes / 12) & " 年" & If((TotalMonthes Mod 12) > 0, " " & (TotalMonthes Mod 12) & " 个月", "")
  2190. ElseIf TotalMonthes >= 4 Then
  2191. '4~11 月,“5 个月”
  2192. GetTimeSpanString = TotalMonthes & " 个月"
  2193. ElseIf TotalMonthes >= 1 Then
  2194. '1~4 月,“2 个月 13 天”
  2195. GetTimeSpanString = TotalMonthes & " 月" & If((Span.Days Mod 30) > 0, " " & (Span.Days Mod 30) & " 天", "")
  2196. ElseIf Span.TotalDays >= 4 Then
  2197. '4~30 天,“23 天”
  2198. GetTimeSpanString = Span.Days & " 天"
  2199. ElseIf Span.TotalDays >= 1 Then
  2200. '1~3 天,“2 天 20 小时”
  2201. GetTimeSpanString = Span.Days & " 天" & If(Span.Hours > 0, " " & Span.Hours & " 小时", "")
  2202. ElseIf Span.TotalHours >= 10 Then
  2203. '10 小时 ~ 1 天,“15 小时”
  2204. GetTimeSpanString = Span.Hours & " 小时"
  2205. ElseIf Span.TotalHours >= 1 Then
  2206. '1~10 小时,“1 小时 20 分钟”
  2207. GetTimeSpanString = Span.Hours & " 小时" & If(Span.Minutes > 0, " " & Span.Minutes & " 分钟", "")
  2208. ElseIf Span.TotalMinutes >= 10 Then
  2209. '10 分钟 ~ 1 小时,“49 分钟”
  2210. GetTimeSpanString = Span.Minutes & " 分钟"
  2211. ElseIf Span.TotalMinutes >= 1 Then
  2212. '1~10 分钟,“9 分 23 秒”
  2213. GetTimeSpanString = Span.Minutes & " 分" & If(Span.Seconds > 0, " " & Span.Seconds & " 秒", "")
  2214. ElseIf Span.TotalSeconds >= 1 Then
  2215. '1 秒 ~ 1 分钟,“23 秒”
  2216. GetTimeSpanString = Span.Seconds & " 秒"
  2217. Else
  2218. '不到 1 秒
  2219. GetTimeSpanString = "1 秒"
  2220. End If
  2221. End If
  2222. GetTimeSpanString += EndFix
  2223. End Function
  2224. ''' <summary>
  2225. ''' 获取十进制 Unix 时间戳。
  2226. ''' </summary>
  2227. Public Function GetUnixTimestamp() As Long
  2228. Return (Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000
  2229. End Function
  2230. ''' <summary>
  2231. ''' 用于储存 RaiseByMouse 的 EventArgs。
  2232. ''' </summary>
  2233. Public NotInheritable Class RouteEventArgs
  2234. Inherits EventArgs
  2235. Public RaiseByMouse As Boolean
  2236. Public Handled As Boolean = False
  2237. Public Sub New(Optional RaiseByMouse As Boolean = False)
  2238. Me.RaiseByMouse = RaiseByMouse
  2239. End Sub
  2240. End Class
  2241. ''' <summary>
  2242. ''' 前台运行文件。
  2243. ''' </summary>
  2244. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  2245. ''' <param name="Arguments">运行参数。</param>
  2246. Public Sub ShellOnly(FileName As String, Optional Arguments As String = "")
  2247. Try
  2248. FileName = ShortenPath(FileName)
  2249. Using Program As New Process
  2250. Program.StartInfo.Arguments = Arguments
  2251. Program.StartInfo.FileName = FileName
  2252. Log("[System] 执行外部命令:" & FileName & " " & Arguments)
  2253. Program.Start()
  2254. End Using
  2255. Catch ex As Exception
  2256. Log(ex, "打开文件或程序失败:" & FileName, LogLevel.Msgbox)
  2257. End Try
  2258. End Sub
  2259. ''' <summary>
  2260. ''' 前台运行文件并返回返回值。
  2261. ''' </summary>
  2262. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  2263. ''' <param name="Arguments">运行参数。</param>
  2264. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会返回 Result.Timeout。</param>
  2265. Public Function ShellAndGetExitCode(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000) As ProcessReturnValues
  2266. Try
  2267. Using Program As New Process
  2268. Program.StartInfo.Arguments = Arguments
  2269. Program.StartInfo.FileName = FileName
  2270. Log("[System] 执行外部命令并等待返回码:" & FileName & " " & Arguments)
  2271. Program.Start()
  2272. If Program.WaitForExit(Timeout) Then
  2273. Return Program.ExitCode
  2274. Else
  2275. Return ProcessReturnValues.Timeout
  2276. End If
  2277. End Using
  2278. Catch ex As Exception
  2279. Log(ex, "执行命令失败:" & FileName, LogLevel.Msgbox)
  2280. Return ProcessReturnValues.Fail
  2281. End Try
  2282. End Function
  2283. ''' <summary>
  2284. ''' 静默运行文件并返回输出流字符串。执行失败会抛出异常。
  2285. ''' </summary>
  2286. ''' <param name="FileName">文件名。可以为“notepad”等缩写。</param>
  2287. ''' <param name="Arguments">运行参数。</param>
  2288. ''' <param name="Timeout">等待该程序结束的最长时间(毫秒)。超时会抛出错误。</param>
  2289. Public Function ShellAndGetOutput(FileName As String, Optional Arguments As String = "", Optional Timeout As Integer = 1000000, Optional WorkingDirectory As String = Nothing) As String
  2290. Dim Info = New ProcessStartInfo With {
  2291. .Arguments = Arguments,
  2292. .FileName = FileName,
  2293. .UseShellExecute = False,
  2294. .CreateNoWindow = True,
  2295. .RedirectStandardError = True,
  2296. .RedirectStandardOutput = True,
  2297. .WorkingDirectory = ShortenPath(If(WorkingDirectory, Path.TrimEnd("\"c)))
  2298. }
  2299. If WorkingDirectory IsNot Nothing Then
  2300. If Info.EnvironmentVariables.ContainsKey("appdata") Then
  2301. Info.EnvironmentVariables("appdata") = WorkingDirectory
  2302. Else
  2303. Info.EnvironmentVariables.Add("appdata", WorkingDirectory)
  2304. End If
  2305. End If
  2306. Log("[System] 执行外部命令并等待返回结果:" & FileName & " " & Arguments)
  2307. Using Program As New Process() With {.StartInfo = Info}
  2308. Program.Start()
  2309. Dim Result As String = Program.StandardOutput.ReadToEnd & Program.StandardError.ReadToEnd
  2310. Program.WaitForExit(Timeout)
  2311. If Not Program.HasExited Then Program.Kill()
  2312. Return Result
  2313. End Using
  2314. End Function
  2315. ''' <summary>
  2316. ''' 在新的工作线程中执行代码。
  2317. ''' </summary>
  2318. Public Function RunInNewThread(Action As Action, Optional Name As String = Nothing, Optional Priority As ThreadPriority = ThreadPriority.Normal) As Thread
  2319. Dim th As New Thread(
  2320. Sub()
  2321. Try
  2322. Action()
  2323. Catch ex As ThreadInterruptedException
  2324. Log(Name & ":线程已中止")
  2325. Catch ex As Exception
  2326. Log(ex, Name & ":线程执行失败", LogLevel.Feedback)
  2327. End Try
  2328. End Sub) With {.Name = If(Name, "Runtime New Invoke " & GetUuid() & "#"), .Priority = Priority}
  2329. th.Start()
  2330. Return th
  2331. End Function
  2332. ''' <summary>
  2333. ''' 确保在 UI 线程中执行代码。
  2334. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  2335. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  2336. ''' </summary>
  2337. Public Function RunInUiWait(Of Output)(Action As Func(Of Output)) As Output
  2338. If RunInUi() Then
  2339. Return Action()
  2340. Else
  2341. Return Application.Current.Dispatcher.Invoke(Action)
  2342. End If
  2343. End Function
  2344. ''' <summary>
  2345. ''' 确保在 UI 线程中执行代码。
  2346. ''' 如果当前并非 UI 线程,则会阻断当前线程,直至 UI 线程执行完毕。
  2347. ''' 为防止线程互锁,请仅在开始加载动画、从 UI 获取输入时使用!
  2348. ''' </summary>
  2349. Public Sub RunInUiWait(Action As Action)
  2350. If RunInUi() Then
  2351. Action()
  2352. Else
  2353. Application.Current.Dispatcher.Invoke(Action)
  2354. End If
  2355. End Sub
  2356. ''' <summary>
  2357. ''' 确保在 UI 线程中执行代码,代码按触发顺序执行。
  2358. ''' 如果当前并非 UI 线程,也不阻断当前线程的执行。
  2359. ''' </summary>
  2360. Public Sub RunInUi(Action As Action, Optional ForceWaitUntilLoaded As Boolean = False)
  2361. If ForceWaitUntilLoaded Then
  2362. Application.Current.Dispatcher.InvokeAsync(Action, Threading.DispatcherPriority.Loaded)
  2363. ElseIf RunInUi() Then
  2364. Action()
  2365. Else
  2366. Application.Current.Dispatcher.InvokeAsync(Action)
  2367. End If
  2368. End Sub
  2369. ''' <summary>
  2370. ''' 确保在工作线程中执行代码。
  2371. ''' </summary>
  2372. Public Sub RunInThread(Action As Action)
  2373. If RunInUi() Then
  2374. RunInNewThread(Action, "Runtime Invoke " & GetUuid() & "#")
  2375. Else
  2376. Action()
  2377. End If
  2378. End Sub
  2379. ''' <summary>
  2380. ''' 按照既定的函数进行选择排序。
  2381. ''' 传入两个对象,若第一个对象应该排在前面,则返回 True。
  2382. ''' </summary>
  2383. <Extension> Public Function Sort(Of T)(List As IList(Of T), SortRule As ComparisonBoolean(Of T)) As List(Of T)
  2384. Dim NewList As New List(Of T)
  2385. While List.Any
  2386. Dim Highest = List(0)
  2387. For i = 1 To List.Count - 1
  2388. If SortRule(List(i), Highest) Then Highest = List(i)
  2389. Next
  2390. List.Remove(Highest)
  2391. NewList.Add(Highest)
  2392. End While
  2393. Return NewList
  2394. End Function
  2395. Public Delegate Function ComparisonBoolean(Of T)(Left As T, Right As T) As Boolean
  2396. ''' <summary>
  2397. ''' 返回列表的浅表副本。
  2398. ''' </summary>
  2399. <Extension> Public Function Clone(Of T)(list As IList(Of T)) As IList(Of T)
  2400. Return New List(Of T)(list)
  2401. End Function
  2402. ''' <summary>
  2403. ''' 尝试从字典中获取某项,如果该项不存在,则返回默认值。
  2404. ''' </summary>
  2405. <Extension> Public Function GetOrDefault(Of TKey, TValue)(Dict As Dictionary(Of TKey, TValue), Key As TKey, Optional DefaultValue As TValue = Nothing) As TValue
  2406. If Dict.ContainsKey(Key) Then
  2407. Return Dict(Key)
  2408. Else
  2409. Return DefaultValue
  2410. End If
  2411. End Function
  2412. ''' <summary>
  2413. ''' 将某项添加到以列表作为值的字典中。
  2414. ''' </summary>
  2415. <Extension> Public Sub AddToList(Of TKey, TValue)(Dict As Dictionary(Of TKey, List(Of TValue)), Key As TKey, Value As TValue)
  2416. If Dict.ContainsKey(Key) Then
  2417. Dict(Key).Add(Value)
  2418. Else
  2419. Dict.Add(Key, New List(Of TValue) From {Value})
  2420. End If
  2421. End Sub
  2422. ''' <summary>
  2423. ''' 获取程序启动参数。
  2424. ''' </summary>
  2425. ''' <param name="Name">参数名。</param>
  2426. ''' <param name="DefaultValue">默认值。</param>
  2427. Public Function GetProgramArgument(Name As String, Optional DefaultValue As Object = "")
  2428. Dim AllArguments() As String = Command.Split(" ")
  2429. For i = 0 To AllArguments.Length - 1
  2430. If AllArguments(i) = "-" & Name Then
  2431. If AllArguments.Length = i + 1 OrElse AllArguments(i + 1).StartsWithF("-") Then Return True
  2432. Return AllArguments(i + 1)
  2433. End If
  2434. Next
  2435. Return DefaultValue
  2436. End Function
  2437. ''' <summary>
  2438. ''' 时间戳转化为日期。
  2439. ''' </summary>
  2440. Public Function GetDate(timeStamp As Integer) As Date
  2441. Dim dtStart As Date = TimeZone.CurrentTimeZone.ToLocalTime(New Date(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
  2442. Dim lTime As Long = (CLng(timeStamp) * 10000000)
  2443. Return dtStart.Add(New TimeSpan(lTime))
  2444. End Function
  2445. ''' <summary>
  2446. ''' 将 UTC 时间转化为当前时区的时间。
  2447. ''' </summary>
  2448. Public Function GetLocalTime(UtcDate As Date) As Date
  2449. Return DateTime.SpecifyKind(UtcDate, DateTimeKind.Utc).ToLocalTime
  2450. End Function
  2451. ''' <summary>
  2452. ''' 打开网页。
  2453. ''' </summary>
  2454. Public Sub OpenWebsite(Url As String)
  2455. Try
  2456. If Not Url.StartsWithF("http", True) AndAlso Not Url.StartsWithF("minecraft://", True) Then
  2457. Throw New Exception(Url & " 不是一个有效的网址,它必须以 http 开头!")
  2458. End If
  2459. Log("[System] 正在打开网页:" & Url)
  2460. Process.Start(Url)
  2461. Catch ex As Exception
  2462. Log(ex, "无法打开网页(" & Url & ")")
  2463. ClipboardSet(Url, False)
  2464. MyMsgBox("可能由于浏览器未正确配置,PCL 无法为你打开网页。" & vbCrLf & "网址已经复制到剪贴板,若有需要可以手动粘贴访问。" & vbCrLf &
  2465. $"网址:{Url}", "无法打开网页")
  2466. End Try
  2467. End Sub
  2468. ''' <summary>
  2469. ''' 打开 explorer。
  2470. ''' 若不以 \ 结尾,则将视作文件路径,打开并选中此文件。
  2471. ''' </summary>
  2472. Public Sub OpenExplorer(Location As String)
  2473. Try
  2474. Location = ShortenPath(Location.Replace("/", "\").Trim(" "c, """"c))
  2475. Log("[System] 正在打开资源管理器:" & Location)
  2476. If Location.EndsWith("\") Then
  2477. ShellOnly(Location)
  2478. Else
  2479. ShellOnly("explorer", $"/select,""{Location}""")
  2480. End If
  2481. Catch ex As Exception
  2482. Log(ex, "打开资源管理器失败,请尝试关闭安全软件(如 360 安全卫士)", LogLevel.Msgbox)
  2483. End Try
  2484. End Sub
  2485. ''' <summary>
  2486. ''' 设置剪贴板。将在另一线程运行,且不会抛出异常。
  2487. ''' </summary>
  2488. Public Sub ClipboardSet(Text As String, Optional ShowSuccessHint As Boolean = True)
  2489. RunInThread(
  2490. Sub()
  2491. Dim RetryCount As Integer = 0
  2492. Retry:
  2493. Try
  2494. RunInUi(
  2495. Sub()
  2496. My.Computer.Clipboard.Clear()
  2497. My.Computer.Clipboard.SetText(Text)
  2498. End Sub)
  2499. Catch ex As Exception
  2500. RetryCount += 1
  2501. If RetryCount <= 5 Then
  2502. Thread.Sleep(20)
  2503. GoTo Retry
  2504. Else
  2505. Log(ex, "可能由于剪贴板被其他程序占用,文本复制失败", LogLevel.Hint)
  2506. End If
  2507. End Try
  2508. If ShowSuccessHint Then Hint("已成功复制!", HintType.Finish)
  2509. End Sub)
  2510. End Sub
  2511. ''' <summary>
  2512. ''' 以 Byte() 形式获取程序中的资源。
  2513. ''' </summary>
  2514. Public Function GetResources(ResourceName As String) As Byte()
  2515. Log("[System] 获取资源:" & ResourceName)
  2516. Dim Raw As Byte() = My.Resources.ResourceManager.GetObject(ResourceName)
  2517. Return Raw
  2518. End Function
  2519. #End Region
  2520. #Region "UI"
  2521. '边距改变
  2522. ''' <summary>
  2523. ''' 相对增减控件的左边距。
  2524. ''' </summary>
  2525. Public Sub DeltaLeft(control As FrameworkElement, newValue As Double)
  2526. '安全性检查
  2527. DebugAssert(Not Double.IsNaN(newValue))
  2528. DebugAssert(Not Double.IsInfinity(newValue))
  2529. If TypeOf control Is Window Then
  2530. '窗口改变
  2531. CType(control, Window).Left += newValue
  2532. Else
  2533. '根据 HorizontalAlignment 改变数值
  2534. Select Case control.HorizontalAlignment
  2535. Case HorizontalAlignment.Left, HorizontalAlignment.Stretch
  2536. control.Margin = New Thickness(control.Margin.Left + newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2537. Case HorizontalAlignment.Right
  2538. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right - newValue, control.Margin.Bottom)
  2539. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2540. Case Else
  2541. DebugAssert(False)
  2542. End Select
  2543. End If
  2544. End Sub
  2545. ''' <summary>
  2546. ''' 设置控件的左边距。(仅针对置左控件)
  2547. ''' </summary>
  2548. Public Sub SetLeft(control As FrameworkElement, newValue As Double)
  2549. DebugAssert(control.HorizontalAlignment = HorizontalAlignment.Left)
  2550. control.Margin = New Thickness(newValue, control.Margin.Top, control.Margin.Right, control.Margin.Bottom)
  2551. End Sub
  2552. ''' <summary>
  2553. ''' 相对增减控件的上边距。
  2554. ''' </summary>
  2555. Public Sub DeltaTop(control As FrameworkElement, newValue As Double)
  2556. '安全性检查
  2557. DebugAssert(Not Double.IsNaN(newValue))
  2558. DebugAssert(Not Double.IsInfinity(newValue))
  2559. If TypeOf control Is Window Then
  2560. '窗口改变
  2561. CType(control, Window).Top += newValue
  2562. Else
  2563. '根据 VerticalAlignment 改变数值
  2564. Select Case control.VerticalAlignment
  2565. Case VerticalAlignment.Top
  2566. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top + newValue, control.Margin.Right, control.Margin.Bottom)
  2567. Case VerticalAlignment.Bottom
  2568. control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, control.Margin.Bottom - newValue)
  2569. 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, CType(control.Parent, Object).ActualWidth - control.ActualWidth - newValue, control.Margin.Bottom)
  2570. Case Else
  2571. DebugAssert(False)
  2572. End Select
  2573. End If
  2574. 'If Double.IsNaN(newValue) OrElse Double.IsInfinity(newValue) Then Exit Sub '安全性检查
  2575. 'Select Case control.VerticalAlignment
  2576. ' Case VerticalAlignment.Top, VerticalAlignment.Stretch, VerticalAlignment.Center
  2577. ' control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2578. ' Case VerticalAlignment.Bottom
  2579. ' control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, -newValue)
  2580. ' 'control.Margin = New Thickness(control.Margin.Left, control.Margin.Top, control.Margin.Right, CType(control.Parent, Object).ActualHeight - control.ActualHeight - newValue)
  2581. 'End Select
  2582. End Sub
  2583. ''' <summary>
  2584. ''' 设置控件的顶边距。(仅针对置上控件)
  2585. ''' </summary>
  2586. Public Sub SetTop(control As FrameworkElement, newValue As Double)
  2587. DebugAssert(control.VerticalAlignment = VerticalAlignment.Top)
  2588. control.Margin = New Thickness(control.Margin.Left, newValue, control.Margin.Right, control.Margin.Bottom)
  2589. End Sub
  2590. 'DPI 转换
  2591. Public ReadOnly DPI As Integer = System.Drawing.Graphics.FromHwnd(IntPtr.Zero).DpiX
  2592. ''' <summary>
  2593. ''' 将经过 DPI 缩放的 WPF 尺寸转化为实际的像素尺寸。
  2594. ''' </summary>
  2595. Public Function GetPixelSize(WPFSize As Double) As Double
  2596. Return WPFSize / 96 * DPI
  2597. End Function
  2598. ''' <summary>
  2599. ''' 将实际的像素尺寸转化为经过 DPI 缩放的 WPF 尺寸。
  2600. ''' </summary>
  2601. Public Function GetWPFSize(PixelSize As Double) As Double
  2602. Return PixelSize * 96 / DPI
  2603. End Function
  2604. 'UI 截图
  2605. ''' <summary>
  2606. ''' 将某个控件的呈现转换为图片。
  2607. ''' </summary>
  2608. Public Function ControlBrush(UI As FrameworkElement) As ImageBrush
  2609. Dim Width = UI.ActualWidth, Height = UI.ActualHeight
  2610. If Width < 1 OrElse Height < 1 Then Return New ImageBrush
  2611. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Pbgra32)
  2612. bmp.Render(UI)
  2613. Return New ImageBrush(bmp)
  2614. End Function
  2615. ''' <summary>
  2616. ''' 将某个控件的模拟呈现转换为图片。
  2617. ''' </summary>
  2618. Public Function ControlBrush(UI As FrameworkElement, Width As Double, Height As Double, Optional Left As Double = 0, Optional Top As Double = 0) As ImageBrush
  2619. UI.Measure(New Size(Width, Height))
  2620. UI.Arrange(New Rect(0, 0, Width, Height))
  2621. Dim bmp As New RenderTargetBitmap(GetPixelSize(Width), GetPixelSize(Height), DPI, DPI, PixelFormats.Default)
  2622. bmp.Render(UI)
  2623. If Not (Left = 0 AndAlso Top = 0) Then UI.Arrange(New Rect(Left, Top, Width, Height))
  2624. Return New ImageBrush(bmp)
  2625. End Function
  2626. ''' <summary>
  2627. ''' 将 UI 内容固定为图片并进行 Clear。
  2628. ''' </summary>
  2629. Public Sub ControlFreeze(UI As Panel)
  2630. UI.Background = ControlBrush(UI)
  2631. UI.Children.Clear()
  2632. End Sub
  2633. ''' <summary>
  2634. ''' 将 UI 内容固定为图片并进行 Clear。
  2635. ''' </summary>
  2636. Public Sub ControlFreeze(UI As Border)
  2637. UI.Background = ControlBrush(UI)
  2638. UI.Child = Nothing
  2639. End Sub
  2640. ''' <summary>
  2641. ''' 将 XML 转换为对应 UI 对象。
  2642. ''' </summary>
  2643. Public Function GetObjectFromXML(Str As XElement)
  2644. Return GetObjectFromXML(Str.ToString)
  2645. End Function
  2646. ''' <summary>
  2647. ''' 将 XML 转换为对应 UI 对象。
  2648. ''' </summary>
  2649. Public Function GetObjectFromXML(Str As String) As Object
  2650. Using Stream As New MemoryStream(Encoding.UTF8.GetBytes(Str))
  2651. '类型检查
  2652. Using Reader As New XamlXmlReader(Stream)
  2653. While Reader.Read()
  2654. For Each BlackListType In {GetType(WebBrowser), GetType(Frame), GetType(MediaElement), GetType(ObjectDataProvider), GetType(XamlReader), GetType(Window), GetType(XmlDataProvider)}
  2655. If Reader.Type IsNot Nothing AndAlso BlackListType.IsAssignableFrom(Reader.Type.UnderlyingType) Then Throw New UnauthorizedAccessException($"不允许使用 {BlackListType.Name} 类型。")
  2656. If Reader.Value IsNot Nothing AndAlso Reader.Value = BlackListType.Name Then Throw New UnauthorizedAccessException($"不允许使用 {BlackListType.Name} 值。")
  2657. Next
  2658. For Each BlackListMember In {"Code", "FactoryMethod", "Static"}
  2659. If Reader.Member IsNot Nothing AndAlso Reader.Member.Name = BlackListMember Then Throw New UnauthorizedAccessException($"不允许使用 {BlackListMember} 成员。")
  2660. Next
  2661. End While
  2662. End Using
  2663. '实际的加载
  2664. Stream.Position = 0
  2665. Using Writer As New StreamWriter(Stream)
  2666. Writer.Write(Str)
  2667. Writer.Flush()
  2668. Stream.Position = 0
  2669. Return Markup.XamlReader.Load(Stream)
  2670. End Using
  2671. End Using
  2672. End Function
  2673. Private ReadOnly UiThreadId As Integer = Thread.CurrentThread.ManagedThreadId
  2674. ''' <summary>
  2675. ''' 当前线程是否为主线程。
  2676. ''' </summary>
  2677. Public Function RunInUi() As Boolean
  2678. Return Thread.CurrentThread.ManagedThreadId = UiThreadId
  2679. End Function
  2680. ''' <summary>
  2681. ''' 检查某个控件是否位于主窗口可视区域内,且控件本身可见。
  2682. ''' </summary>
  2683. <Extension> Public Function IsVisibleInForm(element As FrameworkElement) As Boolean
  2684. If Not element.IsVisible Then Return False
  2685. Dim bounds As Rect = element.TransformToAncestor(FrmMain).TransformBounds(New Rect(0, 0, element.ActualWidth, element.ActualHeight))
  2686. Dim rect As New Rect(0, 0, FrmMain.ActualWidth, FrmMain.ActualHeight)
  2687. Return rect.Contains(bounds.TopLeft) OrElse rect.Contains(bounds.BottomRight)
  2688. End Function
  2689. ''' <summary>
  2690. ''' 控件是否受到 TextTrimming 属性影响,导致内容被截取。
  2691. ''' </summary>
  2692. <Extension> Public Function IsTextTrimmed(Control As TextBlock) As Boolean
  2693. Control.Measure(New Size(Double.MaxValue, Double.MaxValue))
  2694. Return Control.DesiredSize.Width > Control.ActualWidth
  2695. End Function
  2696. ''' <summary>
  2697. ''' 获取文本在被渲染后的宽度。
  2698. ''' </summary>
  2699. Public Function MeasureStringWidth(text As String, Optional fontSize As Double = 14, Optional fontFamily As FontFamily = Nothing) As Double
  2700. If fontFamily Is Nothing Then fontFamily = New FontFamily("微软雅黑")
  2701. Dim formattedText = New FormattedText(
  2702. text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, New Typeface(fontFamily, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
  2703. fontSize, Brushes.Black, New NumberSubstitution(), TextFormattingMode.Display, New DpiScale(1, 1).PixelsPerDip)
  2704. Return formattedText.Width
  2705. End Function
  2706. #End Region
  2707. #Region "Debug"
  2708. Public ModeDebug As Boolean = False
  2709. 'Log
  2710. Public Enum LogLevel
  2711. ''' <summary>
  2712. ''' 不提示,只记录日志。
  2713. ''' </summary>
  2714. Normal = 0
  2715. ''' <summary>
  2716. ''' 只提示开发者。
  2717. ''' </summary>
  2718. Developer = 1
  2719. ''' <summary>
  2720. ''' 只提示开发者与调试模式用户。
  2721. ''' </summary>
  2722. Debug = 2
  2723. ''' <summary>
  2724. ''' 弹出提示所有用户。
  2725. ''' </summary>
  2726. Hint = 3
  2727. ''' <summary>
  2728. ''' 弹窗,不要求反馈。
  2729. ''' </summary>
  2730. Msgbox = 4
  2731. ''' <summary>
  2732. ''' 弹窗,要求反馈。
  2733. ''' </summary>
  2734. Feedback = 5
  2735. ''' <summary>
  2736. ''' 弹窗,结束程序。
  2737. ''' </summary>
  2738. Assert = 6
  2739. End Enum
  2740. Private LogList As New StringBuilder
  2741. Private LogWritter As StreamWriter
  2742. Public Sub LogStart()
  2743. RunInNewThread(
  2744. Sub()
  2745. Dim IsInitSuccess As Boolean = True
  2746. Try
  2747. For i = 4 To 1 Step -1
  2748. If File.Exists(Path & "PCL\Log" & i & ".txt") Then
  2749. If File.Exists(Path & "PCL\Log" & (i + 1) & ".txt") Then File.Delete(Path & "PCL\Log" & (i + 1) & ".txt")
  2750. CopyFile(Path & "PCL\Log" & i & ".txt", Path & "PCL\Log" & (i + 1) & ".txt")
  2751. End If
  2752. Next
  2753. File.Create(Path & "PCL\Log1.txt").Dispose()
  2754. Catch ex As IOException
  2755. IsInitSuccess = False
  2756. Hint("可能同时开启了多个 PCL,程序可能会出现未知问题!", HintType.Critical)
  2757. Log(ex, "日志初始化失败(疑似文件占用问题)")
  2758. Catch ex As Exception
  2759. IsInitSuccess = False
  2760. Log(ex, "日志初始化失败", LogLevel.Hint)
  2761. End Try
  2762. Try
  2763. LogWritter = New StreamWriter(Path & "PCL\Log1.txt", True) With {.AutoFlush = True}
  2764. Catch ex As Exception
  2765. LogWritter = Nothing
  2766. Log(ex, "日志写入失败", LogLevel.Hint)
  2767. End Try
  2768. While True
  2769. If IsInitSuccess Then
  2770. LogFlush()
  2771. Else
  2772. LogList = New StringBuilder '清空 LogList 避免内存爆炸
  2773. End If
  2774. Thread.Sleep(50)
  2775. End While
  2776. End Sub, "Log Writer", ThreadPriority.Lowest)
  2777. End Sub
  2778. Private ReadOnly LogFlushLock As New Object '防止外部调用 LogFlush 时同时输出多次日志
  2779. Public Sub LogFlush()
  2780. On Error Resume Next
  2781. If LogWritter Is Nothing Then Exit Sub
  2782. Dim Log As String = Nothing
  2783. SyncLock LogFlushLock
  2784. If LogList.Length > 0 Then
  2785. Dim LogListCache As StringBuilder
  2786. LogListCache = LogList
  2787. LogList = New StringBuilder
  2788. Log = LogListCache.ToString
  2789. End If
  2790. End SyncLock
  2791. If Log IsNot Nothing Then
  2792. LogWritter.Write(Log)
  2793. End If
  2794. End Sub
  2795. Private ReadOnly LogListLock As New Object '防止日志乱码,只在调试模式下启用
  2796. ''' <summary>
  2797. ''' 输出 Log。
  2798. ''' </summary>
  2799. ''' <param name="Title">如果要求弹窗,指定弹窗的标题。</param>
  2800. Public Sub Log(Text As String, Optional Level As LogLevel = LogLevel.Normal, Optional Title As String = "出现错误")
  2801. On Error Resume Next
  2802. '放在最后会导致无法显示极端错误下的弹窗(如无法写入日志文件)
  2803. '处理错误会导致再次调用 Log() 导致无限循环
  2804. '输出日志
  2805. Dim AppendText As String = "[" & GetTimeNow() & "] " & Text & vbCrLf '减轻同步锁占用
  2806. If ModeDebug Then
  2807. SyncLock LogListLock
  2808. LogList.Append(AppendText)
  2809. End SyncLock
  2810. Else
  2811. LogList.Append(AppendText)
  2812. End If
  2813. #If DEBUG Then
  2814. Console.Write(AppendText)
  2815. #End If
  2816. If IsProgramEnded OrElse Level = LogLevel.Normal Then Exit Sub
  2817. '去除前缀
  2818. Text = Text.RegexReplace("\[[^\]]+?\] ", "")
  2819. '输出提示
  2820. Select Case Level
  2821. #If DEBUG Then
  2822. Case LogLevel.Developer
  2823. Hint("[开发者模式] " & Text, HintType.Info, False)
  2824. Case LogLevel.Debug
  2825. Hint("[调试模式] " & Text, HintType.Info, False)
  2826. #Else
  2827. Case LogLevel.Developer
  2828. Case LogLevel.Debug
  2829. If ModeDebug Then Hint("[调试模式] " & Text, HintType.Info, False)
  2830. #End If
  2831. Case LogLevel.Hint
  2832. Hint(Text, HintType.Critical, False)
  2833. Case LogLevel.Msgbox
  2834. MyMsgBox(Text, Title, IsWarn:=True)
  2835. Case LogLevel.Feedback
  2836. If CanFeedback(False) Then
  2837. If MyMsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  2838. Else
  2839. MyMsgBox(Text & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  2840. End If
  2841. Case LogLevel.Assert
  2842. Dim Time As Long = GetTimeTick()
  2843. If CanFeedback(False) Then
  2844. If MsgBox(Text & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  2845. Else
  2846. MsgBox(Text & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  2847. End If
  2848. If GetTimeTick() - Time < 1500 Then
  2849. '弹窗无法保留
  2850. Log("[System] PCL 已崩溃:" & vbCrLf & Text)
  2851. FormMain.EndProgramForce(ProcessReturnValues.Exception)
  2852. Else
  2853. FormMain.EndProgramForce(ProcessReturnValues.Fail)
  2854. End If
  2855. End Select
  2856. End Sub
  2857. ''' <summary>
  2858. ''' 输出错误信息。
  2859. ''' </summary>
  2860. ''' <param name="Desc">错误描述。会在处理时在末尾加入冒号。</param>
  2861. Public Sub Log(Ex As Exception, Desc As String, Optional Level As LogLevel = LogLevel.Debug, Optional Title As String = "出现错误")
  2862. On Error Resume Next
  2863. If TypeOf Ex Is ThreadInterruptedException Then Exit Sub
  2864. '获取错误信息
  2865. Dim ExFull As String = Desc & ":" & GetExceptionDetail(Ex)
  2866. '输出日志
  2867. Dim AppendText As String = "[" & GetTimeNow() & "] " & Desc & ":" & GetExceptionDetail(Ex, True) & vbCrLf '减轻同步锁占用
  2868. If ModeDebug Then
  2869. SyncLock LogListLock
  2870. LogList.Append(AppendText)
  2871. End SyncLock
  2872. Else
  2873. LogList.Append(AppendText)
  2874. End If
  2875. #If DEBUG Then
  2876. Console.Write(AppendText)
  2877. #End If
  2878. If IsProgramEnded Then Exit Sub
  2879. '输出提示
  2880. Select Case Level
  2881. Case LogLevel.Normal
  2882. #If DEBUG Then
  2883. Case LogLevel.Developer
  2884. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2885. Hint("[开发者模式] " & ExLine, HintType.Info, False)
  2886. Case LogLevel.Debug
  2887. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2888. Hint("[调试模式] " & ExLine, HintType.Info, False)
  2889. #Else
  2890. Case LogLevel.Developer
  2891. Case LogLevel.Debug
  2892. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2893. If ModeDebug Then Hint("[调试模式] " & ExLine, HintType.Info, False)
  2894. #End If
  2895. Case LogLevel.Hint
  2896. Dim ExLine As String = Desc & ":" & GetExceptionSummary(Ex)
  2897. Hint(ExLine, HintType.Critical, False)
  2898. Case LogLevel.Msgbox
  2899. MyMsgBox(ExFull, Title, IsWarn:=True)
  2900. Case LogLevel.Feedback
  2901. If CanFeedback(False) Then
  2902. If MyMsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", Title, "反馈", "取消", IsWarn:=True) = 1 Then Feedback(False, True)
  2903. Else
  2904. MyMsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", Title, IsWarn:=True)
  2905. End If
  2906. Case LogLevel.Assert
  2907. Dim Time As Long = GetTimeTick()
  2908. If CanFeedback(False) Then
  2909. If MsgBox(ExFull & vbCrLf & vbCrLf & "是否反馈此问题?如果不反馈,这个问题可能永远无法得到解决!", MsgBoxStyle.Critical + MsgBoxStyle.YesNo, Title) = MsgBoxResult.Yes Then Feedback(False, True)
  2910. Else
  2911. MsgBox(ExFull & vbCrLf & vbCrLf & "将 PCL 更新至最新版或许可以解决这个问题……", MsgBoxStyle.Critical, Title)
  2912. End If
  2913. If GetTimeTick() - Time < 1500 Then
  2914. '弹窗无法保留
  2915. Log("[System] PCL 已崩溃:" & vbCrLf & ExFull)
  2916. FormMain.EndProgramForce(ProcessReturnValues.Exception)
  2917. Else
  2918. FormMain.EndProgramForce(ProcessReturnValues.Fail)
  2919. End If
  2920. End Select
  2921. End Sub
  2922. '反馈
  2923. Public Sub Feedback(Optional ShowMsgbox As Boolean = True, Optional ForceOpenLog As Boolean = False)
  2924. On Error Resume Next
  2925. FeedbackInfo()
  2926. If ForceOpenLog OrElse (ShowMsgbox AndAlso MyMsgBox("若你在汇报一个 Bug,请点击 打开文件夹 按钮,并上传 Log(1~5).txt 中包含错误信息的文件。" & vbCrLf & "游戏崩溃一般与启动器无关,请不要因为游戏崩溃而提交反馈。", "反馈提交提醒", "打开文件夹", "不需要") = 1) Then
  2927. OpenExplorer(Path & "PCL\Log1.txt")
  2928. End If
  2929. OpenWebsite("https://github.com/Hex-Dragon/PCL2/issues/")
  2930. End Sub
  2931. Public Function CanFeedback(ShowHint As Boolean) As Boolean
  2932. If False.Equals(PageSetupSystem.IsLauncherNewest) Then
  2933. If ShowHint Then
  2934. If MyMsgBox($"你的 PCL 不是最新版,因此无法提交反馈。{vbCrLf}请在更新后,确认该问题在最新版中依然存在,然后再提交反馈。", "无法提交反馈", "更新", "取消") = 1 Then
  2935. UpdateCheckByButton()
  2936. End If
  2937. End If
  2938. Return False
  2939. Else
  2940. Return True
  2941. End If
  2942. End Function
  2943. ''' <summary>
  2944. ''' 在日志中输出系统诊断信息。
  2945. ''' </summary>
  2946. Public Sub FeedbackInfo()
  2947. On Error Resume Next
  2948. Log("[System] 诊断信息:" & vbCrLf &
  2949. "操作系统:" & My.Computer.Info.OSFullName & "(32 位:" & Is32BitSystem & ")" & vbCrLf &
  2950. "剩余内存:" & Int(My.Computer.Info.AvailablePhysicalMemory / 1024 / 1024) & " M / " & Int(My.Computer.Info.TotalPhysicalMemory / 1024 / 1024) & " M" & vbCrLf &
  2951. "DPI:" & DPI & "(" & Math.Round(DPI / 96, 2) * 100 & "%)" & vbCrLf &
  2952. "MC 文件夹:" & If(PathMcFolder, "Nothing") & vbCrLf &
  2953. "文件位置:" & Path)
  2954. End Sub
  2955. '断言
  2956. Public Sub DebugAssert(Exp As Boolean)
  2957. If Not Exp Then Throw New Exception("断言命中")
  2958. End Sub
  2959. '获取当前的堆栈信息
  2960. Public Function GetStackTrace() As String
  2961. Dim Stack As New StackTrace()
  2962. Return Join(Stack.GetFrames().Skip(1).Select(Function(f) f.GetMethod).
  2963. Select(Function(f) f.Name & "(" & Join(f.GetParameters.Select(Function(p) p.ToString).ToList, ", ") & ") - " & f.Module.ToString).ToList,
  2964. vbCrLf).Replace(vbCrLf & vbCrLf, vbCrLf)
  2965. End Function
  2966. #End Region
  2967. #Region "随机"
  2968. Private ReadOnly Random As New Random
  2969. ''' <summary>
  2970. ''' 随机选择其一。
  2971. ''' </summary>
  2972. Public Function RandomOne(Of T)(objects As ICollection(Of T)) As T
  2973. Return objects(RandomInteger(0, objects.Count - 1))
  2974. End Function
  2975. ''' <summary>
  2976. ''' 取随机整数。
  2977. ''' </summary>
  2978. Public Function RandomInteger(min As Integer, max As Integer) As Integer
  2979. Return Math.Floor((max - min + 1) * Random.NextDouble) + min
  2980. End Function
  2981. ''' <summary>
  2982. ''' 将数组随机打乱。
  2983. ''' </summary>
  2984. Public Function Shuffle(Of T)(array As IList(Of T)) As IList(Of T)
  2985. Shuffle = New List(Of T)
  2986. Do While array.Any
  2987. Dim i As Integer = RandomInteger(0, array.Count - 1)
  2988. Shuffle.Add(array(i))
  2989. array.RemoveAt(i)
  2990. Loop
  2991. End Function
  2992. #End Region
  2993. End Module
  2994. #Region "WPF"
  2995. ''' <summary>
  2996. ''' 对数据绑定进行加法运算,使用参数决定加数。
  2997. ''' </summary>
  2998. Public Class AdditionConverter
  2999. Implements IValueConverter
  3000. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3001. If value Is Nothing Then Return 0
  3002. Dim before As Double
  3003. If Not Double.TryParse(value.ToString(), before) Then Return 0
  3004. Dim scale As Double = 1
  3005. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3006. Return before + scale
  3007. End Function
  3008. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3009. If value Is Nothing Then Return Binding.DoNothing
  3010. Dim before As Double
  3011. If Not Double.TryParse(value.ToString(), before) Then Return Binding.DoNothing
  3012. Dim scale As Double = 1
  3013. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3014. If scale = 0 Then Return Binding.DoNothing
  3015. Return before - scale
  3016. End Function
  3017. End Class
  3018. ''' <summary>
  3019. ''' 对数据绑定进行乘法运算,使用参数决定乘数。
  3020. ''' </summary>
  3021. Public Class MultiplicationConverter
  3022. Implements IValueConverter
  3023. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3024. If value Is Nothing Then Return 0
  3025. Dim before As Double
  3026. If Not Double.TryParse(value.ToString(), before) Then Return 0
  3027. Dim scale As Double = 1
  3028. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3029. Return before * scale
  3030. End Function
  3031. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3032. If value Is Nothing Then Return Binding.DoNothing
  3033. Dim before As Double
  3034. If Not Double.TryParse(value.ToString(), before) Then Return Binding.DoNothing
  3035. Dim scale As Double = 1
  3036. If parameter IsNot Nothing Then Double.TryParse(parameter.ToString(), scale)
  3037. If scale = 0 Then Return Binding.DoNothing
  3038. Return before / scale
  3039. End Function
  3040. End Class
  3041. ''' <summary>
  3042. ''' 将取反的 Boolean 绑定到 Visibility。
  3043. ''' </summary>
  3044. Public Class InverseBooleanToVisibilityConverter
  3045. Implements IValueConverter
  3046. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3047. If value Is Nothing Then Return Visibility.Visible
  3048. Dim boolValue As Boolean
  3049. Return If(Boolean.TryParse(value.ToString(), boolValue), If(boolValue, Visibility.Collapsed, Visibility.Visible), Visibility.Visible)
  3050. End Function
  3051. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3052. If value Is Nothing Then Return False
  3053. Return If(TypeOf value Is Visibility, value <> Visibility.Visible, False)
  3054. End Function
  3055. End Class
  3056. ''' <summary>
  3057. ''' 将 Boolean 取反。
  3058. ''' </summary>
  3059. Public Class InverseBooleanConverter
  3060. Implements IValueConverter
  3061. Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
  3062. If value Is Nothing Then Return False
  3063. Dim boolValue As Boolean
  3064. Return If(Boolean.TryParse(value.ToString(), boolValue), Not boolValue, False)
  3065. End Function
  3066. Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
  3067. If value Is Nothing Then Return False
  3068. Return If(Boolean.TryParse(value.ToString(), value), Not value, False)
  3069. End Function
  3070. End Class
  3071. #End Region