ModBase.vb 160 KB

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