├── ColorPanel.pas ├── FastStringCaseUtils.pas ├── GUIPanel.pas ├── GUIPanelHVList.pas ├── InternetUtils.pas ├── LICENSE ├── MainFormUnit.dfm ├── MainFormUnit.pas ├── PTZGlyphButton.pas ├── PTZPanel.pas ├── PTZProgressBar.pas ├── PTZStdCtrls.pas ├── PTZSymbolButton.pas ├── PTZWinControlButton.pas ├── README.md ├── UpdateFixer.dpr ├── UpdateFixer.dproj ├── Win64bitDetector.pas ├── license.txt └── uMiniStringTools.pas /FastStringCaseUtils.pas: -------------------------------------------------------------------------------- 1 | unit FastStringCaseUtils; 2 | 3 | 4 | // FastStringCaseUtils version 1.3 5 | // 6 | // A fast, unicode compatible string to uppercase and lowercase library 7 | // 8 | // Copyright 2022 - Jouni Flemming / Macecraft Software 9 | // Used in jv16 PowerTools Windows Utility Suite 10 | // https://jv16powertools.com 11 | // 12 | // Latest version available at: https://github.com/jv16x/FastStringCaseUtils 13 | // and 14 | // https://sourceforge.net/p/faststringcaseutils/ 15 | // 16 | // Licensed under MIT open source license. 17 | 18 | 19 | {$R-,T-,X+,H+,B-,O+,Q-} 20 | 21 | 22 | interface 23 | 24 | {.$DEFINE Debug_ReferenceMode_DoubleCheckResults} 25 | {.$DEFINE Debug_PerformSelftestOnInit} 26 | 27 | // Using inline increases speed only very slightly, less than 1%. 28 | {.$DEFINE UseInline} 29 | 30 | 31 | uses 32 | Windows, 33 | SysUtils, 34 | System.Character, 35 | StrUtils; 36 | 37 | type 38 | TCharCaseTable = array [WideChar] of WideChar; 39 | TCharOrdTable = array [WideChar] of UInt16; 40 | 41 | procedure Init_FastStringCaseUtils(); 42 | procedure SelfTest_FastStringCaseUtils(); 43 | function Benchmark_FastStringCaseUtils() : String; 44 | 45 | 46 | // A faster version of AnsiLowerCase() 47 | // If MaxLen is provided, only the first MaxLen characters are processed 48 | // E.g. FastLowerCase('FOOBAR!', 3) = 'fooBAR!' 49 | function FastLowerCase(const Str : String; const MaxLen : Integer = -1): String; {$IFDEF UseInline} inline; {$ENDIF} 50 | 51 | // A faster version of AnsiUpperCase() 52 | function FastUpperCase(const Str : String; const MaxLen : Integer = -1): String; {$IFDEF UseInline} inline; {$ENDIF} 53 | 54 | // A faster version of AnsiLowerCase(Trim()) 55 | function FastLowerCase_Trim(const Str : String): String; 56 | 57 | // A faster version of AnsiUpperCase(Trim()) 58 | function FastUpperCase_Trim(const Str : String): String; 59 | 60 | 61 | // Note: To quickly get ordval := Ord(Str[x].ToLower), 62 | // simply write: 63 | // ordval := GLOB_LowCaseOrdTable[Str[x]]; 64 | 65 | // Similarly, you can replace any Str[x].ToLower or Str[x].ToUpper 66 | // with GLOB_CharLowCaseTable[Str[x]] and GLOB_CharUpCaseTable[Str[x]] 67 | 68 | // Warning: Replacing any Str[x].ToLower with GLOB_CharLowCaseTable[Str[x]] 69 | // can cause different results on certain unicode characters! 70 | 71 | // Warning: We consider all ASCII characters of value <= 32 to be White Space, including #0 72 | 73 | 74 | 75 | 76 | 77 | var 78 | GLOB_CharUpCaseTable : TCharCaseTable; 79 | GLOB_CharLowCaseTable : TCharCaseTable; 80 | GLOB_LowCaseOrdTable : TCharOrdTable; 81 | 82 | 83 | implementation 84 | 85 | 86 | 87 | function Benchmark_FastStringCaseUtils() : String; 88 | const 89 | TEST_DATA_STR = ' PÅ hVER handletur du GJØR 123 XXX xxx 123 SERPIŞTIRMEK1 ÜÇ nOKTA ΕΛΛΗΝΙΚΉ ΓΛΏΣΣΑ fÖÖBÄR '; 90 | TEST_LOOPS = 10000000; 91 | 92 | var 93 | i : Integer; 94 | time_start : UInt64; 95 | time_end : UInt64; 96 | TmpStr : String; 97 | begin 98 | 99 | 100 | {$IFDEF Debug_ReferenceMode_DoubleCheckResults} 101 | EXIT('Disable Debug_ReferenceMode_DoubleCheckResults before running Benchmark_FastStringCaseUtils()'); 102 | {$ENDIF} 103 | 104 | 105 | Result := ''; 106 | Result := Result + 'Non-Unicode Lower Case conversion:' + #13#10; 107 | 108 | // Test 1: LowerCase() 109 | time_start := GetTickCount64(); 110 | 111 | for i := 1 to TEST_LOOPS do 112 | begin 113 | TmpStr := LowerCase(TEST_DATA_STR); 114 | Assert( Length(TmpStr) = Length(TEST_DATA_STR), 'Benchmark_FastStringCaseUtils Fail Test-1'); 115 | end; 116 | 117 | time_end := GetTickCount64(); 118 | Result := Result + 'Test 1 - LowerCase(): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 119 | 120 | 121 | // Test 2: LowerCase(Trim()) 122 | time_start := GetTickCount64(); 123 | 124 | for i := 1 to TEST_LOOPS do 125 | begin 126 | TmpStr := LowerCase(Trim(TEST_DATA_STR)); 127 | Assert( Length(TmpStr) = Length(TEST_DATA_STR) - 2, 'Benchmark_FastStringCaseUtils Fail Test-2'); 128 | end; 129 | 130 | time_end := GetTickCount64(); 131 | Result := Result + 'Test 2 - LowerCase(Trim()): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 132 | 133 | 134 | Result := Result + #13#10; 135 | Result := Result + 'Unicode Lower Case conversion:' + #13#10; 136 | 137 | 138 | // Test 3: AnsiLowerCase() 139 | time_start := GetTickCount64(); 140 | 141 | for i := 1 to TEST_LOOPS do 142 | begin 143 | TmpStr := AnsiLowerCase(TEST_DATA_STR); 144 | Assert( Length(TmpStr) = Length(TEST_DATA_STR), 'Benchmark_FastStringCaseUtils Fail Test-3'); 145 | end; 146 | 147 | time_end := GetTickCount64(); 148 | Result := Result + 'Test 3 - AnsiLowerCase(): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 149 | 150 | 151 | // Test 4: AnsiLowerCase(Trim()) 152 | time_start := GetTickCount64(); 153 | 154 | for i := 1 to TEST_LOOPS do 155 | begin 156 | TmpStr := AnsiLowerCase(Trim(TEST_DATA_STR)); 157 | Assert( Length(TmpStr) = Length(TEST_DATA_STR) - 2, 'Benchmark_FastStringCaseUtils Fail Test-4'); 158 | end; 159 | 160 | time_end := GetTickCount64(); 161 | Result := Result + 'Test 4 - AnsiLowerCase(Trim()): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 162 | 163 | 164 | // Test 5: Str.ToLower() 165 | time_start := GetTickCount64(); 166 | 167 | for i := 1 to TEST_LOOPS do 168 | begin 169 | TmpStr := TEST_DATA_STR.ToLower; 170 | Assert( Length(TmpStr) = Length(TEST_DATA_STR), 'Benchmark_FastStringCaseUtils Fail Test-5'); 171 | end; 172 | 173 | time_end := GetTickCount64(); 174 | Result := Result + 'Test 5 - Str.ToLower(): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 175 | 176 | 177 | // Test 6: Trim(Str.ToLower()) 178 | time_start := GetTickCount64(); 179 | 180 | for i := 1 to TEST_LOOPS do 181 | begin 182 | TmpStr := Trim(TEST_DATA_STR.ToLower); 183 | Assert( Length(TmpStr) = Length(TEST_DATA_STR) - 2, 'Benchmark_FastStringCaseUtils Fail Test-6'); 184 | end; 185 | 186 | time_end := GetTickCount64(); 187 | Result := Result + 'Test 6 - Trim(Str.ToLower()): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 188 | 189 | 190 | Result := Result + #13#10; 191 | Result := Result + 'FastStringCaseUtils Unicode Lower Case conversion:' + #13#10; 192 | 193 | 194 | // Test 7: FastLowerCase() 195 | time_start := GetTickCount64(); 196 | 197 | for i := 1 to TEST_LOOPS do 198 | begin 199 | TmpStr := FastLowerCase(TEST_DATA_STR); 200 | Assert( Length(TmpStr) = Length(TEST_DATA_STR), 'Benchmark_FastStringCaseUtils Fail Test-7'); 201 | end; 202 | 203 | time_end := GetTickCount64(); 204 | Result := Result + 'Test 7 - FastLowerCase(): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 205 | 206 | 207 | // Test 8: FastLowerCase_Trim() 208 | time_start := GetTickCount64(); 209 | 210 | for i := 1 to TEST_LOOPS do 211 | begin 212 | TmpStr := FastLowerCase_Trim(TEST_DATA_STR); 213 | Assert( Length(TmpStr) = Length(TEST_DATA_STR) - 2, 'Benchmark_FastStringCaseUtils Fail Test-8'); 214 | end; 215 | 216 | time_end := GetTickCount64(); 217 | Result := Result + 'Test 8 - FastLowerCase_Trim(): ' + IntToStr(time_end - time_start) + ' msec' + #13#10; 218 | 219 | 220 | 221 | end; 222 | 223 | 224 | // A faster version of AnsiLowerCase(Trim()) 225 | function FastLowerCase_Trim(const Str : String): String; 226 | var 227 | i : Integer; 228 | j : Integer; 229 | len : Integer; 230 | idx_1 : Integer; 231 | idx_2 : Integer; 232 | begin 233 | 234 | // Note: Detecting Unicode White Space characters by directly 235 | // using System.Character's GetUnicodeCategory() would be faster, 236 | // but it results in 'depricated' compiler warnings. 237 | 238 | len := Length(Str); 239 | if len = 0 then EXIT(''); 240 | 241 | if len = 1 then 242 | begin 243 | if (Str[1].IsWhiteSpace) or 244 | (GLOB_LowCaseOrdTable[Str[1]] <= 32) then EXIT(''); 245 | 246 | SetLength(Result, 1); 247 | Result[1] := GLOB_CharLowCaseTable[Str[1]]; 248 | end else 249 | begin 250 | 251 | idx_1 := 1; 252 | while (idx_1 <= len) and 253 | ((Str[idx_1].IsWhiteSpace) or 254 | (GLOB_LowCaseOrdTable[Str[idx_1]] <= 32)) do Inc(idx_1); 255 | 256 | if idx_1 > len then EXIT(''); 257 | idx_2 := len; 258 | 259 | while (idx_2 > idx_1) and 260 | ((Str[idx_2].IsWhiteSpace) or 261 | (GLOB_LowCaseOrdTable[Str[idx_2]] <= 32)) do Dec(idx_2); 262 | 263 | SetLength(Result, len - (len - idx_2) - (idx_1 - 1)); 264 | 265 | i := 1; 266 | for j := idx_1 to idx_2 do 267 | begin 268 | Result[i] := GLOB_CharLowCaseTable[Str[j]]; 269 | Inc(i); 270 | end; 271 | end; 272 | 273 | 274 | 275 | {$IFDEF Debug_ReferenceMode_DoubleCheckResults} 276 | Assert(AnsiLowerCase(Trim(Str)) = Result, 'FastLowerCase_Trim Debug_ReferenceMode_DoubleCheckResults Fail: ' + Result); 277 | {$ENDIF} 278 | 279 | end; 280 | 281 | 282 | 283 | 284 | 285 | // A faster version of AnsiLowerCase() 286 | function FastLowerCase(const Str : String; const MaxLen : Integer = -1): String; {$IFDEF UseInline} inline; {$ENDIF} 287 | var 288 | i : Integer; 289 | len : Integer; 290 | begin 291 | 292 | len := Length(Str); 293 | if len = 0 then EXIT(''); 294 | 295 | SetLength(Result, len); 296 | 297 | if MaxLen > 0 then 298 | begin 299 | 300 | for i := 1 to len do 301 | if i <= MaxLen then 302 | Result[i] := GLOB_CharLowCaseTable[Str[i]] 303 | else Result[i] := Str[i]; 304 | 305 | end else 306 | for i := 1 to len do 307 | Result[i] := GLOB_CharLowCaseTable[Str[i]]; 308 | 309 | {$IFDEF Debug_ReferenceMode_DoubleCheckResults} 310 | Assert(AnsiLowerCase(Str) = Result, 'FastLowerCase Debug_ReferenceMode_DoubleCheckResults Fail: ' + Result); 311 | {$ENDIF} 312 | 313 | end; 314 | 315 | 316 | // A faster version of AnsiUpperCase() 317 | function FastUpperCase(const Str : String; const MaxLen : Integer = -1): String; {$IFDEF UseInline} inline; {$ENDIF} 318 | var 319 | i : Integer; 320 | len : Integer; 321 | begin 322 | 323 | len := Length(Str); 324 | if len = 0 then EXIT(''); 325 | 326 | SetLength(Result, len); 327 | 328 | if MaxLen > 0 then 329 | begin 330 | 331 | for i := 1 to len do 332 | if i <= MaxLen then 333 | Result[i] := GLOB_CharUpCaseTable[Str[i]] 334 | else Result[i] := Str[i]; 335 | 336 | end else 337 | for i := 1 to Len do 338 | Result[i] := GLOB_CharUpCaseTable[Str[i]]; 339 | 340 | 341 | {$IFDEF Debug_ReferenceMode_DoubleCheckResults} 342 | Assert(AnsiUpperCase(Str) = Result, 'FastUpperCase Debug_ReferenceMode_DoubleCheckResults Fail: ' + Result); 343 | {$ENDIF} 344 | 345 | end; 346 | 347 | 348 | // A faster version of AnsiUpperCase(Trim()) 349 | // If TrimAllUnderOrd32, all characters with Ord() code <= 32 will be trimmed 350 | function FastUpperCase_Trim(const Str : String): String; 351 | var 352 | i : Integer; 353 | j : Integer; 354 | len : Integer; 355 | idx_1 : Integer; 356 | idx_2 : Integer; 357 | begin 358 | 359 | len := Length(Str); 360 | if len = 0 then EXIT(''); 361 | 362 | if len = 1 then 363 | begin 364 | if (Str[1].IsWhiteSpace) or 365 | (GLOB_LowCaseOrdTable[Str[1]] <= 32) then EXIT(''); 366 | 367 | SetLength(Result, 1); 368 | Result[1] := GLOB_CharUpCaseTable[Str[1]]; 369 | end else 370 | begin 371 | 372 | idx_1 := 1; 373 | while (idx_1 <= len) and 374 | ((Str[idx_1].IsWhiteSpace) or 375 | (GLOB_LowCaseOrdTable[Str[idx_1]] <= 32)) do Inc(idx_1); 376 | 377 | if idx_1 > len then EXIT(''); 378 | idx_2 := len; 379 | 380 | while (idx_2 > idx_1) and 381 | ((Str[idx_2].IsWhiteSpace) or 382 | (GLOB_LowCaseOrdTable[Str[idx_2]] <= 32)) do Dec(idx_2); 383 | 384 | SetLength(Result, len - (len - idx_2) - (idx_1 - 1)); 385 | 386 | i := 1; 387 | for j := idx_1 to idx_2 do 388 | begin 389 | Result[i] := GLOB_CharUpCaseTable[Str[j]]; 390 | Inc(i); 391 | end; 392 | end; 393 | 394 | 395 | 396 | 397 | {$IFDEF Debug_ReferenceMode_DoubleCheckResults} 398 | Assert(AnsiUpperCase(Trim(Str)) = Result, 'FastUpperCase_Trim Debug_ReferenceMode_DoubleCheckResults Fail: ' + Result); 399 | {$ENDIF} 400 | 401 | end; 402 | 403 | 404 | 405 | Procedure SelfTest_FastStringCaseUtils(); 406 | begin 407 | 408 | Assert( FastLowerCase('Foobar!') = 'foobar!', 'SelfTest_FastStringCaseUtils Fail-1'); 409 | Assert( FastUpperCase('Qwerty!') = 'QWERTY!', 'SelfTest_FastStringCaseUtils Fail-2'); 410 | 411 | Assert( FastLowerCase('Fööbär') = 'fööbär', 'SelfTest_FastStringCaseUtils Fail-3'); 412 | Assert( FastUpperCase('Fööbär') = 'FÖÖBÄR', 'SelfTest_FastStringCaseUtils Fail-4'); 413 | 414 | Assert( FastLowerCase('Ligação') = 'ligação', 'SelfTest_FastStringCaseUtils Fail-5'); 415 | Assert( FastUpperCase('Ligação') = 'LIGAÇÃO', 'SelfTest_FastStringCaseUtils Fail-6'); 416 | 417 | Assert( FastLowerCase('På Hver Handletur Du Gjør') = 'på hver handletur du gjør', 'SelfTest_FastStringCaseUtils Fail-7'); 418 | Assert( FastUpperCase('på hver handletur du gjør') = 'PÅ HVER HANDLETUR DU GJØR', 'SelfTest_FastStringCaseUtils Fail-8'); 419 | 420 | Assert( FastLowerCase('Serpiştirmek1') = 'serpiştirmek1', 'SelfTest_FastStringCaseUtils Fail-9'); 421 | Assert( FastUpperCase('Serpiştirmek1') = 'SERPIŞTIRMEK1', 'SelfTest_FastStringCaseUtils Fail-10'); 422 | 423 | Assert( FastLowerCase('üç nokta') = 'üç nokta', 'SelfTest_FastStringCaseUtils Fail-11'); 424 | Assert( FastUpperCase('üç nokta') = 'ÜÇ NOKTA', 'SelfTest_FastStringCaseUtils Fail-12'); 425 | 426 | Assert( FastLowerCase('ελληνική γλώσσα') = 'ελληνική γλώσσα', 'SelfTest_FastStringCaseUtils Fail-13'); 427 | Assert( FastUpperCase('ελληνική γλώσσα') = 'ΕΛΛΗΝΙΚΉ ΓΛΏΣΣΑ', 'SelfTest_FastStringCaseUtils Fail-14'); 428 | 429 | Assert( FastLowerCase_Trim('Fööbär') = 'fööbär', 'SelfTest_FastStringCaseUtils Fail-15'); 430 | Assert( FastUpperCase_Trim('Fööbär') = 'FÖÖBÄR', 'SelfTest_FastStringCaseUtils Fail-16'); 431 | 432 | Assert( FastLowerCase_Trim('Fööbär ') = 'fööbär', 'SelfTest_FastStringCaseUtils Fail-17'); 433 | Assert( FastUpperCase_Trim('Fööbär ') = 'FÖÖBÄR', 'SelfTest_FastStringCaseUtils Fail-18'); 434 | 435 | Assert( FastLowerCase_Trim(' Fööbär') = 'fööbär', 'SelfTest_FastStringCaseUtils Fail-19'); 436 | Assert( FastUpperCase_Trim(' Fööbär') = 'FÖÖBÄR', 'SelfTest_FastStringCaseUtils Fail-20'); 437 | 438 | Assert( FastLowerCase_Trim(' Fööbär ') = 'fööbär', 'SelfTest_FastStringCaseUtils Fail-21'); 439 | Assert( FastUpperCase_Trim(' Fööbär ') = 'FÖÖBÄR', 'SelfTest_FastStringCaseUtils Fail-22'); 440 | 441 | Assert( FastLowerCase_Trim(#9 + ' Fööbär ' + #9 + #0) = 'fööbär', 'SelfTest_FastStringCaseUtils Fail-23'); 442 | Assert( FastUpperCase_Trim(#9 + ' Fööbär ' + #9 + #0) = 'FÖÖBÄR', 'SelfTest_FastStringCaseUtils Fail-24'); 443 | 444 | Assert( FastLowerCase_Trim(' ' + #9 + #0) = '', 'SelfTest_FastStringCaseUtils Fail-25'); 445 | Assert( FastUpperCase_Trim(' ' + #9 + #0) = '', 'SelfTest_FastStringCaseUtils Fail-26'); 446 | 447 | Assert( FastLowerCase('') = '', 'SelfTest_FastStringCaseUtils Fail-27'); 448 | Assert( FastUpperCase('') = '', 'SelfTest_FastStringCaseUtils Fail-28'); 449 | 450 | Assert( FastLowerCase_Trim('') = '', 'SelfTest_FastStringCaseUtils Fail-29'); 451 | Assert( FastUpperCase_Trim('') = '', 'SelfTest_FastStringCaseUtils Fail-30'); 452 | 453 | Assert( FastLowerCase_Trim(#3 + ' Fööbär ' + #2) = 'fööbär', 'SelfTest_FastStringCaseUtils Fail-31'); 454 | Assert( FastUpperCase_Trim(#3 + ' Fööbär ' + #2) = 'FÖÖBÄR', 'SelfTest_FastStringCaseUtils Fail-32'); 455 | 456 | Assert( FastLowerCase('c') = 'c', 'SelfTest_FastStringCaseUtils Fail-33'); 457 | Assert( FastUpperCase('c') = 'C', 'SelfTest_FastStringCaseUtils Fail-34'); 458 | Assert( FastLowerCase('C') = 'c', 'SelfTest_FastStringCaseUtils Fail-35'); 459 | Assert( FastUpperCase('C') = 'C', 'SelfTest_FastStringCaseUtils Fail-36'); 460 | 461 | Assert( FastLowerCase_Trim('c') = 'c', 'SelfTest_FastStringCaseUtils Fail-37'); 462 | Assert( FastUpperCase_Trim('c') = 'C', 'SelfTest_FastStringCaseUtils Fail-38'); 463 | Assert( FastLowerCase_Trim('C') = 'c', 'SelfTest_FastStringCaseUtils Fail-39'); 464 | Assert( FastUpperCase_Trim('C') = 'C', 'SelfTest_FastStringCaseUtils Fail-40'); 465 | 466 | Assert( FastLowerCase('cÖ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-41'); 467 | Assert( FastUpperCase('cÖ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-42'); 468 | Assert( FastLowerCase('CÖ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-43'); 469 | Assert( FastUpperCase('CÖ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-44'); 470 | 471 | Assert( FastLowerCase_Trim('cÖ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-45'); 472 | Assert( FastUpperCase_Trim('cÖ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-46'); 473 | Assert( FastLowerCase_Trim('CÖ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-47'); 474 | Assert( FastUpperCase_Trim('CÖ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-48'); 475 | 476 | Assert( FastLowerCase_Trim('cÖ ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-49'); 477 | Assert( FastUpperCase_Trim('cÖ ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-50'); 478 | Assert( FastLowerCase_Trim('CÖ ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-51'); 479 | Assert( FastUpperCase_Trim('CÖ ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-52'); 480 | 481 | Assert( FastLowerCase_Trim(' cÖ ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-53'); 482 | Assert( FastUpperCase_Trim(' cÖ ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-54'); 483 | Assert( FastLowerCase_Trim(' CÖ ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-55'); 484 | Assert( FastUpperCase_Trim(' CÖ ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-56'); 485 | 486 | Assert( FastLowerCase_Trim(' cÖ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-57'); 487 | Assert( FastUpperCase_Trim(' cÖ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-58'); 488 | Assert( FastLowerCase_Trim(' CÖ') = 'cö', 'SelfTest_FastStringCaseUtils Fail-59'); 489 | Assert( FastUpperCase_Trim(' CÖ') = 'CÖ', 'SelfTest_FastStringCaseUtils Fail-60'); 490 | 491 | Assert( FastLowerCase_Trim('Ö ') = 'ö', 'SelfTest_FastStringCaseUtils Fail-61'); 492 | Assert( FastUpperCase_Trim('Ö ') = 'Ö', 'SelfTest_FastStringCaseUtils Fail-62'); 493 | Assert( FastLowerCase_Trim('Ö ') = 'ö', 'SelfTest_FastStringCaseUtils Fail-63'); 494 | Assert( FastUpperCase_Trim('Ö ') = 'Ö', 'SelfTest_FastStringCaseUtils Fail-64'); 495 | 496 | Assert( FastLowerCase_Trim(' Ö ') = 'ö', 'SelfTest_FastStringCaseUtils Fail-65'); 497 | Assert( FastUpperCase_Trim(' Ö ') = 'Ö', 'SelfTest_FastStringCaseUtils Fail-66'); 498 | Assert( FastLowerCase_Trim(' Ö ') = 'ö', 'SelfTest_FastStringCaseUtils Fail-67'); 499 | Assert( FastUpperCase_Trim(' Ö ') = 'Ö', 'SelfTest_FastStringCaseUtils Fail-68'); 500 | 501 | Assert( FastLowerCase_Trim(' Ö') = 'ö', 'SelfTest_FastStringCaseUtils Fail-69'); 502 | Assert( FastUpperCase_Trim(' Ö') = 'Ö', 'SelfTest_FastStringCaseUtils Fail-70'); 503 | Assert( FastLowerCase_Trim(' Ö') = 'ö', 'SelfTest_FastStringCaseUtils Fail-71'); 504 | Assert( FastUpperCase_Trim(' Ö') = 'Ö', 'SelfTest_FastStringCaseUtils Fail-72'); 505 | 506 | Assert( FastLowerCase_Trim(#9) = '', 'SelfTest_FastStringCaseUtils Fail-73'); 507 | Assert( FastUpperCase_Trim(#9) = '', 'SelfTest_FastStringCaseUtils Fail-74'); 508 | 509 | Assert( FastLowerCase_Trim(#9 + #9) = '', 'SelfTest_FastStringCaseUtils Fail-75'); 510 | Assert( FastUpperCase_Trim(#9 + #9) = '', 'SelfTest_FastStringCaseUtils Fail-76'); 511 | 512 | Assert( FastLowerCase_Trim(#9 + #9 + #9) = '', 'SelfTest_FastStringCaseUtils Fail-77'); 513 | Assert( FastUpperCase_Trim(#9 + #9 + #9) = '', 'SelfTest_FastStringCaseUtils Fail-78'); 514 | 515 | end; 516 | 517 | 518 | 519 | procedure Init_FastStringCaseUtils(); 520 | var 521 | i : Cardinal; 522 | begin 523 | 524 | 525 | for i := 0 to Length(GLOB_CharUpCaseTable) - 1 do 526 | begin 527 | GLOB_CharUpCaseTable[Char(i)] := Char(i); 528 | GLOB_CharLowCaseTable[Char(i)] := Char(i); 529 | end; 530 | 531 | CharUpperBuff(@GLOB_CharUpCaseTable , Length(GLOB_CharUpCaseTable)); 532 | CharLowerBuff(@GLOB_CharLowCaseTable, Length(GLOB_CharLowCaseTable)); 533 | 534 | for i := 0 to Length(GLOB_LowCaseOrdTable) - 1 do 535 | GLOB_LowCaseOrdTable[Char(i)] := Ord(GLOB_CharLowCaseTable[Char(i)]); 536 | 537 | 538 | 539 | end; 540 | 541 | 542 | 543 | initialization 544 | 545 | Init_FastStringCaseUtils(); 546 | 547 | 548 | {$IFDEF Debug_PerformSelftestOnInit} 549 | SelfTest_FastStringCaseUtils(); 550 | {$ENDIF} 551 | 552 | 553 | end. 554 | -------------------------------------------------------------------------------- /GUIPanel.pas: -------------------------------------------------------------------------------- 1 | unit GUIPanel; 2 | 3 | 4 | {$R-,T-,X+,H+,B-,O+,Q-} 5 | 6 | interface 7 | 8 | {.$DEFINE EnablePerformanceLog} 9 | {.$DEFINE Debug_ExplicitMadExceptUse} 10 | 11 | uses 12 | {$IFDEF Debug_ExplicitMadExceptUse} madExcept, {$ENDIF} 13 | Windows, Messages, SysUtils, Classes, 14 | Graphics, Controls, Forms, System.Types, 15 | {$IFDEF EnablePerformanceLog} PerformanceLog, {$ENDIF} 16 | ExtCtrls, Contnrs, Vcl.Themes; 17 | 18 | type 19 | TCustomGUIPanel = class(TCustomPanel) 20 | private 21 | FAlignControlsCalls: Integer; 22 | procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; 23 | protected 24 | FAutoSizeW: Boolean; 25 | FAutoSizeH: Boolean; 26 | FControlList: TObjectList; 27 | procedure Paint; override; 28 | procedure AdjustControls(const ForceUpdate : Boolean = False); virtual; 29 | procedure Set_AutoSizeW(Value: Boolean); virtual; 30 | procedure Set_AutoSizeH(Value: Boolean); virtual; 31 | procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED; 32 | procedure CMControlListChanging(var Message: TCMControlListChanging); message CM_CONTROLLISTCHANGING; 33 | public 34 | constructor Create(AOwner: TComponent); override; 35 | destructor Destroy; override; 36 | procedure AlignControls(AControl: TControl; var Rect: TRect); override; 37 | procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; 38 | function GetControlIndex(AControl: TControl): Integer; 39 | procedure SetControlIndex(AControl: TControl; Index: Integer); 40 | published 41 | end; 42 | 43 | TGUIPanel = class(TCustomGUIPanel) 44 | public 45 | procedure AdjustControls(const ForceUpdate : Boolean = False); override; 46 | published 47 | property AutoSizeW: Boolean read FAutoSizeW write Set_AutoSizeW; 48 | property AutoSizeH: Boolean read FAutoSizeH write Set_AutoSizeH; 49 | property BevelEdges; 50 | property BevelInner; 51 | property BevelKind; 52 | property BevelOuter; 53 | property BevelWidth; 54 | property BorderWidth; 55 | property BorderStyle; 56 | property Font; 57 | property Color; 58 | property ParentColor; 59 | property Enabled; 60 | property Visible; 61 | property Align; 62 | property Alignment; 63 | property Cursor; 64 | property Hint; 65 | property ParentShowHint; 66 | property ShowHint; 67 | property PopupMenu; 68 | property TabOrder; 69 | property TabStop; 70 | property UseDockManager; 71 | property Anchors; 72 | property BiDiMode; 73 | property Constraints; 74 | property DragKind; 75 | property DragMode; 76 | property DragCursor; 77 | property ParentBiDiMode; 78 | property DockSite; 79 | property OnEndDock; 80 | property OnStartDock; 81 | property OnCanResize; 82 | property OnConstrainedResize; 83 | property OnDockDrop; 84 | property OnDockOver; 85 | property OnGetSiteInfo; 86 | property OnUnDock; 87 | property OnContextPopup; 88 | property OnClick; 89 | property OnDblClick; 90 | property OnDragDrop; 91 | property OnDragOver; 92 | property OnEndDrag; 93 | property OnEnter; 94 | property OnExit; 95 | property OnMouseDown; 96 | property OnMouseMove; 97 | property OnMouseUp; 98 | property OnResize; 99 | property OnStartDrag; 100 | end; 101 | 102 | procedure Register; 103 | 104 | implementation 105 | 106 | procedure Register; 107 | begin 108 | RegisterComponents('Macecraft GUIPanels', [TGUIPanel]); 109 | end; 110 | 111 | constructor TCustomGUIPanel.Create(AOwner: TComponent); 112 | begin 113 | inherited Create(AOwner); 114 | 115 | FAlignControlsCalls := 0; 116 | 117 | FControlList := TObjectList.Create(False); 118 | 119 | ControlStyle := ControlStyle - [csSetCaption]; 120 | ControlStyle := ControlStyle + [csAcceptsControls, csOpaque]; 121 | DoubleBuffered := True; 122 | 123 | FAutoSizeW := False; 124 | FAutoSizeH := False; 125 | 126 | ParentFont := True; 127 | ParentColor := True; 128 | 129 | SetBounds(0, 0, 185, 41); 130 | AdjustControls; 131 | end; 132 | 133 | destructor TCustomGUIPanel.Destroy; 134 | begin 135 | FControlList.Free; 136 | inherited; 137 | end; 138 | 139 | procedure TCustomGUIPanel.WMEraseBkgnd(var Message: TWmEraseBkgnd); 140 | begin 141 | { Only erase background if we're not doublebuffering or painting to memory. } 142 | if not FDoubleBuffered or 143 | {$IF DEFINED(CLR)} 144 | (Message.OriginalMessage.WParam = Message.OriginalMessage.LParam) then 145 | {$ELSE} 146 | (TMessage(Message).WParam = WParam(TMessage(Message).LParam)) then 147 | {$ENDIF} 148 | begin 149 | if StyleServices.Enabled and Assigned(Parent) and (csParentBackground in ControlStyle) then 150 | begin 151 | if Parent.DoubleBuffered then 152 | PerformEraseBackground(Self, Message.DC) 153 | else 154 | StyleServices.DrawParentBackground(Handle, Message.DC, nil, False); 155 | end 156 | else 157 | FillRect(Message.DC, ClientRect, Brush.Handle); 158 | end; 159 | Message.Result := 1; 160 | end; 161 | 162 | procedure TCustomGUIPanel.CMControlListChanging 163 | (var Message: TCMControlListChanging); 164 | begin 165 | 166 | Try 167 | inherited; 168 | if Message.Inserting and (Message.ControlListItem.Parent = Self) then 169 | begin 170 | if FControlList.IndexOf(Message.ControlListItem.Control) < 0 then 171 | FControlList.Add(Message.ControlListItem.Control); 172 | end 173 | else 174 | FControlList.Remove(Message.ControlListItem.Control); 175 | Except 176 | //HandleException(); 177 | End; 178 | 179 | 180 | end; 181 | 182 | procedure TCustomGUIPanel.GetChildren(Proc: TGetChildProc; Root: TComponent); 183 | var 184 | i : Integer; 185 | Control : TControl; 186 | begin 187 | 188 | for i := 0 to FControlList.Count - 1 do 189 | begin 190 | 191 | if (assigned(FControlList[i]) and (FControlList[i] is TControl)) then 192 | begin 193 | Control := TControl(FControlList[i]); 194 | if Control.Owner = Root then Proc(Control); 195 | end; 196 | end; 197 | 198 | end; 199 | 200 | function TCustomGUIPanel.GetControlIndex(AControl: TControl): Integer; 201 | begin 202 | Result := FControlList.IndexOf(AControl); 203 | end; 204 | 205 | procedure TCustomGUIPanel.SetControlIndex(AControl: TControl; Index: Integer); 206 | var 207 | CurIndex: Integer; 208 | begin 209 | 210 | CurIndex := GetControlIndex(AControl); 211 | if (CurIndex > -1) and (CurIndex <> Index) and (Index < FControlList.Count) 212 | then 213 | begin 214 | FControlList.Move(CurIndex, Index); 215 | Realign; 216 | end; 217 | end; 218 | 219 | procedure TCustomGUIPanel.Set_AutoSizeW(Value: Boolean); 220 | begin 221 | 222 | FAutoSizeW := Value; 223 | Invalidate; 224 | AdjustControls; 225 | end; 226 | 227 | procedure TCustomGUIPanel.Set_AutoSizeH(Value: Boolean); 228 | begin 229 | 230 | FAutoSizeH := Value; 231 | Invalidate; 232 | AdjustControls; 233 | end; 234 | 235 | procedure TCustomGUIPanel.CMEnabledChanged(var Message: TMessage); 236 | begin 237 | inherited; 238 | Invalidate; 239 | end; 240 | 241 | procedure TCustomGUIPanel.AlignControls(AControl: TControl; var Rect: TRect); 242 | begin 243 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TCustomGUIPanel.AlignControls', Self); {$ENDIF} 244 | Try 245 | 246 | Inc(FAlignControlsCalls); 247 | if ControlCount < 1 then 248 | begin 249 | if Showing then 250 | AdjustSize; 251 | Exit; 252 | end; 253 | AdjustClientRect(Rect); 254 | AdjustControls; 255 | Except 256 | //HandleException(); 257 | End; 258 | 259 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TCustomGUIPanel.AlignControls'); end; {$ENDIF} 260 | end; 261 | 262 | procedure TCustomGUIPanel.AdjustControls; 263 | begin 264 | // do nothing, descendants should override this 265 | end; 266 | 267 | procedure TGUIPanel.AdjustControls(const ForceUpdate : Boolean = False); 268 | var 269 | Control: TControl; 270 | I, X, Y: Integer; 271 | MinPos, MaxPos: TPoint; 272 | begin 273 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TGUIPanel.AdjustControls', Self); {$ENDIF} 274 | if csReading in ComponentState then Exit; 275 | 276 | Try 277 | 278 | if ControlCount < 1 then 279 | begin 280 | if Showing then 281 | AdjustSize; 282 | Exit; 283 | end; 284 | 285 | // iterate components; collect width and height 286 | for I := 0 to FControlList.Count - 1 do 287 | begin 288 | Control := TControl(FControlList[I]); 289 | 290 | X := Control.Left; 291 | Y := Control.Top; 292 | if (X < MinPos.X) or (I = 0) then 293 | MinPos.X := X; 294 | if (Y < MinPos.Y) or (I = 0) then 295 | MinPos.Y := Y; 296 | 297 | X := X + Control.Width; 298 | Y := Y + Control.Height; 299 | if (X > MaxPos.X) or (I = 0) then 300 | MaxPos.X := X; 301 | if (Y > MaxPos.Y) or (I = 0) then 302 | MaxPos.Y := Y; 303 | end; 304 | 305 | if Self.Align = alClient then 306 | begin 307 | FAutoSizeW := False; 308 | FAutoSizeH := False; 309 | end; 310 | 311 | if Self.Align = alClient then 312 | begin 313 | FAutoSizeW := False; 314 | FAutoSizeH := False; 315 | end; 316 | 317 | if Self.Align = alTop then 318 | FAutoSizeW := False; 319 | if Self.Align = alBottom then 320 | FAutoSizeW := False; 321 | if Self.Align = alLeft then 322 | FAutoSizeH := False; 323 | if Self.Align = alRight then 324 | FAutoSizeH := False; 325 | 326 | // resize width if needed 327 | if FAutoSizeW then 328 | begin 329 | for I := 0 to FControlList.Count - 1 do 330 | with TControl(FControlList[I]) do 331 | Left := Left - MinPos.X; 332 | X := MaxPos.X - MinPos.X; 333 | if X <> Width then 334 | Width := X; 335 | end; 336 | 337 | // resize height if needed 338 | if FAutoSizeH then 339 | begin 340 | for I := 0 to FControlList.Count - 1 do 341 | with TControl(FControlList[I]) do 342 | Top := Top - MinPos.Y; 343 | Y := MaxPos.Y - MinPos.Y; 344 | if Y <> Height then 345 | Height := Y; 346 | end; 347 | 348 | ControlsAligned; 349 | if Showing then 350 | AdjustSize; 351 | 352 | Except 353 | //HandleException(); 354 | End; 355 | 356 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TGUIPanel.AdjustControls'); end; {$ENDIF} 357 | end; 358 | 359 | procedure TCustomGUIPanel.Paint; 360 | var 361 | memoryBitmap: TBitmap; 362 | trt: TRect; 363 | S: String; 364 | X: Integer; 365 | begin 366 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TCustomGUIPanel.Paint', Self); {$ENDIF} 367 | 368 | memoryBitmap := TBitmap.Create; // create memory bitmap to draw flicker-free 369 | try 370 | memoryBitmap.Height := ClientRect.Bottom; 371 | memoryBitmap.Width := ClientRect.Right; 372 | 373 | if csDesigning in ComponentState then 374 | begin 375 | trt := ClientRect; 376 | with memoryBitmap.Canvas do 377 | begin 378 | // Draw background 379 | Brush.Color := clWhite; 380 | FillRect(trt); 381 | 382 | // Draw border 383 | Brush.Color := clSilver; 384 | FrameRect(trt); 385 | InflateRect(trt, -1, -1); 386 | FrameRect(trt); 387 | 388 | // Display classname at designtime 389 | if (Height > 25) and (Width > 30) then 390 | begin 391 | S := Self.ClassName; 392 | Brush.Style := bsClear; 393 | Font.Name := 'Arial'; 394 | Font.Style := [fsBold]; 395 | Font.Size := 8; 396 | X := memoryBitmap.Canvas.TextWidth(S); 397 | Font.Color := clBlack; 398 | TextOut(ClientWidth - X - 3, 3, S); 399 | Font.Color := clWhite; 400 | TextOut(ClientWidth - X - 4, 2, S); 401 | end; 402 | end; 403 | end 404 | else 405 | begin 406 | // Draw background 407 | memoryBitmap.Canvas.Brush.Color := Self.Color; 408 | memoryBitmap.Canvas.FillRect(ClientRect); 409 | end; 410 | 411 | // Copy memoryBitmap to screen 412 | Canvas.CopyRect(ClientRect, memoryBitmap.Canvas, ClientRect); 413 | finally 414 | FreeAndNil(memoryBitmap); // delete the bitmap 415 | end; 416 | 417 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TCustomGUIPanel.Paint'); end; {$ENDIF} 418 | end; 419 | 420 | end. 421 | -------------------------------------------------------------------------------- /GUIPanelHVList.pas: -------------------------------------------------------------------------------- 1 | unit GUIPanelHVList; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | // If the list contains automatically positioned elements, throw Assert in case they were resized or re-positioned elsewhere 6 | {.$DEFINE Debug_Assert_IfPosChanged} 7 | {.$DEFINE EnablePerformanceLog} 8 | 9 | interface 10 | 11 | 12 | {.$DEFINE Debug_ExplicitMadExceptUse} 13 | 14 | uses 15 | {$IFDEF Debug_ExplicitMadExceptUse} madExcept, {$ENDIF} 16 | Windows, Messages, SysUtils, Classes, Graphics, Controls, 17 | {$IFDEF EnablePerformanceLog} PerformanceLog, {$ENDIF} 18 | 19 | {$IFDEF Debug_Assert_IfPosChanged} 20 | AssertUnit, 21 | System.Generics.Collections, {$ENDIF} 22 | 23 | Forms, StdCtrls, ExtCtrls, Contnrs, GUIPanel, System.Types; 24 | 25 | 26 | 27 | type 28 | TCustomGUIPanelList = class(TGUIPanel) 29 | private 30 | FResizeControls: Boolean; 31 | FIgnoreInvisible: Boolean; 32 | FSortByTags: Boolean; 33 | FReverseFill: Boolean; 34 | procedure SetResizeControls(Value: Boolean); 35 | protected 36 | FMarginTop: Integer; 37 | FMarginLeft: Integer; 38 | FMarginSeparator: Integer; 39 | procedure Set_AutoSizeW(Value: Boolean); override; 40 | procedure Set_AutoSizeH(Value: Boolean); override; 41 | procedure SetMarginTop(Value: Integer); 42 | procedure SetMarginLeft(Value: Integer); 43 | procedure SetMarginSeparator(Value: Integer); 44 | procedure SetIgnoreInvisibleControls(Value: Boolean); 45 | procedure SetSortByTags(Value: Boolean); 46 | procedure SetReverseFill(Value: Boolean); 47 | public 48 | constructor Create(AOwner: TComponent); override; 49 | Function GetAverageControlWidth : Single; 50 | Function GetBottomControlTop(PlusItsHeight : Boolean) : Integer; 51 | Function GetVisibleControlCount() : Integer; 52 | published 53 | property AutoSizeW: Boolean read FAutoSizeW write Set_AutoSizeW; 54 | property AutoSizeH: Boolean read FAutoSizeH write Set_AutoSizeH; 55 | property MarginTop: Integer read FMarginTop write SetMarginTop; 56 | property MarginLeft: Integer read FMarginLeft write SetMarginLeft; 57 | property MarginSeparator: Integer read FMarginSeparator write SetMarginSeparator; 58 | property ResizeControls : Boolean read FResizeControls write SetResizeControls; 59 | property SortByTags: Boolean read FSortByTags write SetSortByTags; 60 | property ReverseFill: Boolean read FReverseFill write SetReverseFill; 61 | property IgnoreInvisibleControls: Boolean read FIgnoreInvisible write SetIgnoreInvisibleControls; 62 | end; 63 | 64 | TGUIPanelHList = class(TCustomGUIPanelList) 65 | private 66 | FMarginHorizontal: Integer; 67 | FLastAdjustState : String; 68 | {$IFDEF Debug_Assert_IfPosChanged} FLastControlStates : TDictionary; {$ENDIF} 69 | 70 | procedure SetMarginHorizontal(Value: Integer); 71 | function GetAdjustState() : String; 72 | public 73 | constructor Create(AOwner: TComponent); override; 74 | procedure AdjustControls(const ForceUpdate : Boolean = False); override; 75 | published 76 | property MarginHorizontal: Integer read FMarginHorizontal write SetMarginHorizontal; 77 | end; 78 | 79 | TGUIPanelVList = class(TCustomGUIPanelList) 80 | private 81 | FMarginVertical: Integer; 82 | FExtraLabelMargin: Integer; 83 | FExtraLabelSeparation : Integer; 84 | FExtraMemoMargin: Integer; 85 | FLastAdjustState : String; 86 | {$IFDEF Debug_Assert_IfPosChanged} FLastControlStates : TDictionary; {$ENDIF} 87 | 88 | procedure SetMarginVertical(Value: Integer); 89 | procedure SetExtraLabelMargin(Value: Integer); 90 | procedure SetExtraLabelSeparation(Value: Integer); 91 | procedure SetExtraMemoMargin(Value: Integer); 92 | function GetAdjustState() : String; 93 | public 94 | constructor Create(AOwner: TComponent); override; 95 | procedure AdjustControls(const ForceUpdate : Boolean = False); override; 96 | published 97 | property MarginVertical: Integer read FMarginVertical write SetMarginVertical; 98 | property ExtraLabelMargin: Integer read FExtraLabelMargin write SetExtraLabelMargin; // Horizontal margin! 99 | property ExtraLabelSeparation: Integer read FExtraLabelSeparation write SetExtraLabelSeparation; // Vertical margin! 100 | property ExtraMemoMargin: Integer read FExtraMemoMargin write SetExtraMemoMargin; 101 | 102 | 103 | end; 104 | 105 | procedure Register; 106 | 107 | implementation 108 | 109 | procedure Register; 110 | begin 111 | RegisterComponents('Macecraft GUIPanels', [TGUIPanelHList]); 112 | RegisterComponents('Macecraft GUIPanels', [TGUIPanelVList]); 113 | end; 114 | 115 | constructor TCustomGUIPanelList.Create(AOwner: TComponent); 116 | begin 117 | inherited Create(AOwner); 118 | Self.DoubleBuffered := True; 119 | Self.ParentBackground := False; 120 | 121 | FAutoSizeW := False; 122 | FAutoSizeH := False; 123 | FMarginTop := 5; 124 | FMarginLeft := 5; 125 | FMarginSeparator := 0; 126 | FResizeControls := False; 127 | FIgnoreInvisible := True; 128 | FSortByTags := False; 129 | FReverseFill := False; 130 | 131 | AdjustControls; 132 | end; 133 | 134 | constructor TGUIPanelHList.Create(AOwner: TComponent); 135 | begin 136 | inherited Create(AOwner); 137 | {$IFDEF Debug_Assert_IfPosChanged} FLastControlStates := TDictionary.Create; {$ENDIF} 138 | Self.DoubleBuffered := True; 139 | Self.ParentBackground := False; 140 | 141 | FMarginHorizontal := 5; 142 | end; 143 | 144 | constructor TGUIPanelVList.Create(AOwner: TComponent); 145 | begin 146 | inherited Create(AOwner); 147 | {$IFDEF Debug_Assert_IfPosChanged} FLastControlStates := TDictionary.Create; {$ENDIF} 148 | Self.DoubleBuffered := True; 149 | Self.ParentBackground := False; 150 | 151 | FMarginVertical := 5; 152 | FExtraLabelSeparation := 0; 153 | FExtraLabelMargin := 0; 154 | FExtraMemoMargin := 0; 155 | end; 156 | 157 | procedure TCustomGUIPanelList.Set_AutoSizeW(Value: Boolean); 158 | begin 159 | 160 | if Self.Align = alClient then Value := False; 161 | if Self.Align = alTop then Value := False; 162 | if Self.Align = alBottom then Value := False; 163 | 164 | if FAutoSizeW <> Value then 165 | begin 166 | FAutoSizeW := Value; 167 | if Value = True then 168 | ResizeControls := False; 169 | 170 | Invalidate; 171 | AdjustControls; 172 | end; 173 | end; 174 | 175 | procedure TCustomGUIPanelList.Set_AutoSizeH(Value: Boolean); 176 | begin 177 | 178 | if Self.Align = alClient then 179 | Value := False; 180 | if Self.Align = alLeft then 181 | Value := False; 182 | if Self.Align = alRight then 183 | Value := False; 184 | 185 | 186 | if FAutoSizeH <> Value then 187 | begin 188 | FAutoSizeH := Value; 189 | Invalidate; 190 | AdjustControls; 191 | end; 192 | end; 193 | 194 | procedure TGUIPanelHList.SetMarginHorizontal(Value: Integer); 195 | begin 196 | FMarginHorizontal := Value; 197 | Invalidate; 198 | AdjustControls; 199 | end; 200 | 201 | 202 | procedure TGUIPanelVList.SetExtraMemoMargin(Value: Integer); 203 | begin 204 | FExtraMemoMargin := Value; 205 | Invalidate; 206 | AdjustControls; 207 | end; 208 | 209 | procedure TGUIPanelVList.SetExtraLabelMargin(Value: Integer); 210 | begin 211 | FExtraLabelMargin := Value; 212 | Invalidate; 213 | AdjustControls; 214 | end; 215 | 216 | procedure TGUIPanelVList.SetExtraLabelSeparation(Value: Integer); 217 | begin 218 | FExtraLabelSeparation := Value; 219 | Invalidate; 220 | AdjustControls; 221 | end; 222 | 223 | 224 | 225 | procedure TGUIPanelVList.SetMarginVertical(Value: Integer); 226 | begin 227 | FMarginVertical := Value; 228 | Invalidate; 229 | AdjustControls; 230 | end; 231 | 232 | procedure TCustomGUIPanelList.SetMarginTop(Value: Integer); 233 | begin 234 | FMarginTop := Value; 235 | Invalidate; 236 | AdjustControls; 237 | end; 238 | 239 | procedure TCustomGUIPanelList.SetMarginLeft(Value: Integer); 240 | begin 241 | FMarginLeft := Value; 242 | Invalidate; 243 | AdjustControls; 244 | end; 245 | 246 | procedure TCustomGUIPanelList.SetMarginSeparator(Value: Integer); 247 | begin 248 | FMarginSeparator := Value; 249 | Invalidate; 250 | AdjustControls; 251 | end; 252 | 253 | Function TCustomGUIPanelList.GetAverageControlWidth : Single; 254 | Var 255 | i : Integer; 256 | c : TControl; 257 | Sum : Integer; 258 | Count : Integer; 259 | begin 260 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TCustomGUIPanelList.GetAverageControlWidth', Self); {$ENDIF} // SmartUpdate('GUIPanelHVList:255'); 261 | 262 | Sum := 0; 263 | Count := 0; 264 | 265 | for i := 0 to FControlList.Count-1 do 266 | begin 267 | c := TControl(FControlList[i]); 268 | if c = nil then Continue; 269 | 270 | Inc(Count); 271 | Sum := Sum + c.Width; 272 | end; 273 | 274 | if Count > 0 then Result := Sum / Count else Result := 0; 275 | 276 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TCustomGUIPanelList.GetAverageControlWidth'); end; {$ENDIF} 277 | end; 278 | 279 | Function TCustomGUIPanelList.GetBottomControlTop(PlusItsHeight : Boolean) : Integer; 280 | Var 281 | i : Integer; 282 | c : TControl; 283 | x_val : Integer; 284 | x_idx : Integer; 285 | begin 286 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TCustomGUIPanelList.GetBottomControlTop', Self); {$ENDIF} // SmartUpdate('GUIPanelHVList:281'); 287 | 288 | Result := 0; 289 | If FControlList.Count < 1 then EXIT; 290 | 291 | x_val := 0; 292 | x_idx := -1; 293 | 294 | for i := 0 to FControlList.Count-1 do 295 | begin 296 | c := TControl(FControlList[i]); 297 | if (c = nil) or (c.Visible = False) then Continue; 298 | 299 | if (x_idx < 0) or (c.Top > x_val) then 300 | begin 301 | x_idx := i; 302 | x_val := c.Top; 303 | End; 304 | end; 305 | 306 | If (x_idx > -1) then 307 | begin 308 | c := TControl(FControlList[x_idx]); 309 | 310 | if (c <> nil) and (c.Visible) then 311 | begin 312 | if PlusItsHeight then Result := c.Top + c.Height else Result := c.Top; 313 | End; 314 | End; 315 | 316 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TCustomGUIPanelList.GetBottomControlTop'); end; {$ENDIF} 317 | end; 318 | 319 | Function TCustomGUIPanelList.GetVisibleControlCount() : Integer; 320 | Var 321 | i : Integer; 322 | c : TControl; 323 | begin 324 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TCustomGUIPanelList.GetVisibleControlCount', Self); {$ENDIF} // SmartUpdate('GUIPanelHVList:319'); 325 | 326 | Result := 0; 327 | 328 | for i := 0 to FControlList.Count-1 do 329 | begin 330 | c := TControl(FControlList[i]); 331 | if (c = nil) or (c.Visible = False) then Continue; 332 | Inc(Result); 333 | End; 334 | 335 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TCustomGUIPanelList.GetVisibleControlCount'); end; {$ENDIF} 336 | end; 337 | 338 | procedure TCustomGUIPanelList.SetResizeControls(Value: Boolean); 339 | begin 340 | 341 | Try 342 | FResizeControls := Value; 343 | 344 | if Value = True then 345 | begin 346 | if Self is TGUIPanelVList then FAutoSizeW := False; 347 | if Self is TGUIPanelHList then FAutoSizeH := False; 348 | end; 349 | 350 | Invalidate; 351 | AdjustControls; 352 | Except 353 | //HandleException(); 354 | End; 355 | 356 | end; 357 | 358 | procedure TCustomGUIPanelList.SetIgnoreInvisibleControls(Value: Boolean); 359 | begin 360 | 361 | Try 362 | FIgnoreInvisible := Value; 363 | Invalidate; 364 | AdjustControls; 365 | Except 366 | //HandleException(); 367 | End; 368 | 369 | 370 | end; 371 | 372 | procedure TCustomGUIPanelList.SetSortByTags(Value: Boolean); 373 | begin 374 | FSortByTags := Value; 375 | Invalidate; 376 | AdjustControls; 377 | end; 378 | 379 | procedure TCustomGUIPanelList.SetReverseFill(Value: Boolean); 380 | begin 381 | FReverseFill := Value; 382 | Invalidate; 383 | AdjustControls; 384 | end; 385 | 386 | // sort controls according to their horizontal position 387 | function ControlSorter_H(p1, p2: Pointer): Integer; 388 | var 389 | y1, y2: Integer; 390 | begin 391 | y1 := TControl(p1).Left; 392 | y2 := TControl(p2).Left; 393 | if y1 > y2 then 394 | Result := 1 395 | else if y1 < y2 then 396 | Result := -1 397 | else 398 | Result := 0; 399 | end; 400 | 401 | // sort controls according to their vertical position 402 | function ControlSorter_V(p1, p2: Pointer): Integer; 403 | var 404 | y1, y2: Integer; 405 | begin 406 | y1 := TControl(p1).Top; 407 | y2 := TControl(p2).Top; 408 | if y1 > y2 then 409 | Result := 1 410 | else if y1 < y2 then 411 | Result := -1 412 | else 413 | Result := 0; 414 | end; 415 | 416 | // sort controls according to their Tag value 417 | function ControlSorter_Tag(p1, p2: Pointer): Integer; 418 | var 419 | y1, y2: Integer; 420 | begin 421 | y1 := TControl(p1).Tag; 422 | y2 := TControl(p2).Tag; 423 | if y1 > y2 then 424 | Result := 1 425 | else if y1 < y2 then 426 | Result := -1 427 | else 428 | Result := 0; 429 | end; 430 | 431 | // sort controls according to their horizontal position 432 | function ControlSorter_H_Reverse(p1, p2: Pointer): Integer; 433 | var 434 | y1, y2: Integer; 435 | begin 436 | y1 := TControl(p1).Left; 437 | y2 := TControl(p2).Left; 438 | if y1 > y2 then 439 | Result := -1 440 | else if y1 < y2 then 441 | Result := 1 442 | else 443 | Result := 0; 444 | end; 445 | 446 | // sort controls according to their vertical position 447 | function ControlSorter_V_Reverse(p1, p2: Pointer): Integer; 448 | var 449 | y1, y2: Integer; 450 | begin 451 | y1 := TControl(p1).Top; 452 | y2 := TControl(p2).Top; 453 | if y1 > y2 then 454 | Result := -1 455 | else if y1 < y2 then 456 | Result := 1 457 | else 458 | Result := 0; 459 | end; 460 | 461 | 462 | function TGUIPanelHList.GetAdjustState() : String; 463 | Var 464 | i : Integer; 465 | begin 466 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TGUIPanelHList.GetAdjustState', Self); {$ENDIF} // SmartUpdate('GUIPanelHVList:461'); 467 | 468 | Result := IntToStr(Self.Width) +'x'+ IntToStr(Self.Height) +':' + 469 | IntToStr(Self.ControlCount) +':'+ 470 | IntToStr(Self.ComponentCount) +':'+ 471 | IntToStr(Self.MarginHorizontal) +':'+ 472 | IntToStr(Self.MarginTop) +':'+ 473 | IntToStr(Self.MarginLeft) +':'+ 474 | IntToStr(Self.MarginSeparator) +':'; 475 | 476 | if Self.ResizeControls then Result := Result + 'x' else Result := Result + 'z'; 477 | if Self.SortByTags then Result := Result + 'x' else Result := Result + 'z'; 478 | if Self.ReverseFill then Result := Result + 'x' else Result := Result + 'z'; 479 | if Self.AutoSizeW then Result := Result + 'x' else Result := Result + 'z'; 480 | if Self.AutoSizeH then Result := Result + 'x' else Result := Result + 'z'; 481 | 482 | if Self.Parent <> nil then 483 | begin 484 | Result := Result + IntToStr(Self.Parent.Width) +'x'+ IntToStr(Self.Parent.Height) +':'; 485 | end; 486 | 487 | for i := 0 to Self.ControlCount-1 do 488 | begin 489 | // SmartUpdate('GUIPanelHVList:485'); 490 | Result := Result + 491 | IntToStr(Self.Controls[i].Width) + 'x' + 492 | IntToStr(Self.Controls[i].Height) +':'+ 493 | IntToStr(Self.Controls[i].Left) +':'+ 494 | IntToStr(Self.Controls[i].Top) +':'+ 495 | 496 | IntToStr(Self.Controls[i].Margins.Left) +':'+ 497 | IntToStr(Self.Controls[i].Margins.Top) +':'+ 498 | IntToStr(Self.Controls[i].Margins.Right) +':'+ 499 | IntToStr(Self.Controls[i].Margins.Bottom) +':'+ 500 | 501 | IntToStr(Self.Controls[i].Tag) +':'; 502 | if Self.Controls[i].Visible then Result := Result + 'vis'; 503 | end; 504 | 505 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TGUIPanelHList.GetAdjustState'); end; {$ENDIF} 506 | end; 507 | 508 | // Lines up controls horizontally 509 | procedure TGUIPanelHList.AdjustControls(const ForceUpdate : Boolean = False); 510 | var 511 | i, X, Y, H : Integer; 512 | prevName : String; 513 | CurState : String; 514 | NewSize : TPoint; 515 | MaxPos : TPoint; 516 | Control : TControl; 517 | ControlList : TObjectList; 518 | {$IFDEF Debug_Assert_IfPosChanged} CurState : String; OldState : String; {$ENDIF} 519 | begin 520 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TGUIPanelHList.AdjustControls', Self); {$ENDIF} // SmartUpdate('GUIPanelHVList:506'); 521 | 522 | if Self = nil then EXIT; 523 | if csReading in ComponentState then EXIT; 524 | if Self.ControlCount < 1 then EXIT; 525 | 526 | if ForceUpdate = False then 527 | begin 528 | CurState := GetAdjustState(); 529 | if FLastAdjustState = CurState then EXIT; 530 | End; 531 | 532 | // Call the AdjustControls() of any child controls: 533 | for i := 0 to Self.ControlCount - 1 do 534 | begin 535 | // SmartUpdate('GUIPanelHVList:531'); 536 | Control := Self.Controls[i]; 537 | if (Control <> nil) and (Control <> self) then 538 | begin 539 | If (Control is TGUIPanelVList) then TGUIPanelVList(Control).AdjustControls(); 540 | If (Control is TGUIPanelHList) then TGUIPanelHList(Control).AdjustControls(); 541 | 542 | //if (Control is TPTZCheckBox) then TPTZCheckBox(Control).AdjustAutoSize(); 543 | //if (Control is TPTZRadioButton) then TPTZRadioButton(Control).AdjustAutoSize(); 544 | 545 | // Fix case of autosize labels: 546 | if (Self.ResizeControls) and (Control is TLabel) and (TLabel(Control).AutoSize) then TLabel(Control).AutoSize := False; 547 | End; 548 | end; 549 | for i := 0 to Self.ControlCount - 1 do 550 | begin 551 | Control := Self.Controls[i]; 552 | if (Control <> nil) and (Control <> self) and (Control.Align <> alNone) and (Control is TWinControl) then TWinControl(Control).Realign; 553 | End; 554 | // ** 555 | 556 | 557 | 558 | Try 559 | NewSize := Point(0, 0); 560 | 561 | ControlList := TObjectList.Create(False); 562 | for i := 0 to Self.ControlCount - 1 do 563 | begin 564 | // SmartUpdate('GUIPanelHVList:557'); 565 | Control := Self.Controls[i]; 566 | if (Control = nil) or (Control = self) then Continue; // just in case 567 | if (FIgnoreInvisible) and (Control.Visible = False) then Continue; 568 | ControlList.Add(Control); 569 | end; 570 | 571 | if ReverseFill then 572 | begin 573 | X := Self.Width - FMarginLeft - 1; 574 | if FSortByTags then 575 | ControlList.Sort(@ControlSorter_Tag) 576 | else 577 | ControlList.Sort(@ControlSorter_H_Reverse); 578 | end 579 | else 580 | begin 581 | X := FMarginLeft; 582 | if FSortByTags then 583 | ControlList.Sort(@ControlSorter_Tag) 584 | else 585 | ControlList.Sort(@ControlSorter_H); 586 | end; 587 | 588 | 589 | 590 | {$IFDEF Debug_Assert_IfPosChanged} 591 | If (not (csReading in ComponentState)) and (FLastControlStates <> nil) and (FLastControlStates.Count > 0) then 592 | begin 593 | for i := 0 to ControlList.Count - 1 do 594 | begin 595 | Control := TControl(ControlList[i]); 596 | CurState := IntToStr(Control.Left) +':'+ IntToStr(Control.Top); 597 | If FLastControlStates.TryGetValue(Control.Name, OldState) then 598 | AssertEx(OldState = CurState, 'Control state changed: ' + Control.Name + ', Self: ' + Self.Name + ', Current state: ' + CurState + ', Old state: ' + OldState); 599 | End; 600 | End; 601 | {$ENDIF} 602 | 603 | H := 0; 604 | 605 | // find tallest control 606 | if not FAutoSizeH then 607 | begin 608 | 609 | for i := 0 to ControlList.Count - 1 do 610 | begin 611 | Control := TControl(ControlList[i]); 612 | if Control.Height > H then 613 | H := Control.Height; 614 | end; 615 | H := H div 2; 616 | end; 617 | 618 | // iterate controls; collect width and height 619 | for i := 0 to ControlList.Count - 1 do 620 | begin 621 | // SmartUpdate('GUIPanelHVList:614'); 622 | Control := TControl(ControlList[i]); 623 | 624 | if FResizeControls then 625 | begin 626 | Control.Top := FMarginTop; 627 | Control.Height := Height - (FMarginTop * 2); 628 | end 629 | else 630 | Control.Top := FMarginTop + (H - (Control.Height div 2)); 631 | 632 | if ReverseFill then 633 | begin 634 | Dec(X, Control.Width); 635 | if i > 0 then 636 | begin 637 | if Control.ClassName <> prevName then 638 | Dec(X, FMarginSeparator); 639 | Dec(X, FMarginHorizontal); 640 | 641 | if Control.AlignWithMargins then 642 | Dec(X, Control.Margins.Left); 643 | end; 644 | Control.Left := X; 645 | end 646 | else 647 | begin 648 | if i > 0 then 649 | begin 650 | if Control.ClassName <> prevName then 651 | Inc(X, FMarginSeparator); 652 | Inc(X, FMarginHorizontal); 653 | 654 | if Control.AlignWithMargins then 655 | Inc(X, Control.Margins.Left); 656 | end; 657 | Control.Left := X; 658 | Inc(X, Control.Width); 659 | end; 660 | 661 | prevName := Control.ClassName; 662 | end; 663 | 664 | if ReverseFill then 665 | Dec(X, FMarginHorizontal) 666 | else 667 | Inc(X, FMarginHorizontal); 668 | 669 | // resize height if needed 670 | if FAutoSizeH then 671 | begin 672 | for i := 0 to Self.ControlCount - 1 do 673 | begin 674 | Y := Controls[i].Height; 675 | if (Y > MaxPos.Y) or (i = 0) then 676 | MaxPos.Y := Y; 677 | end; 678 | Y := MaxPos.Y + (FMarginTop * 2); 679 | if Y <> Height then 680 | Height := Y; 681 | end; 682 | 683 | // resize width if needed 684 | if FAutoSizeW then 685 | begin 686 | Dec(X, FMarginHorizontal); 687 | Inc(X, FMarginLeft); 688 | 689 | if X <> Width then 690 | Width := X; 691 | end; 692 | 693 | 694 | {$IFDEF Debug_Assert_IfPosChanged} 695 | If not (csReading in ComponentState) then 696 | begin 697 | for i := 0 to ControlList.Count - 1 do 698 | begin 699 | Control := TControl(ControlList[i]); 700 | CurState := IntToStr(Control.Left) +':'+ IntToStr(Control.Top); 701 | FLastControlStates.AddOrSetValue(Control.Name, CurState); 702 | End; 703 | End; 704 | {$ENDIF} 705 | 706 | 707 | FLastAdjustState := GetAdjustState(); 708 | ControlList.Free; 709 | 710 | Except 711 | //HandleException(); 712 | End; 713 | 714 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TGUIPanelHList.AdjustControls'); end; {$ENDIF} 715 | end; 716 | 717 | 718 | function TGUIPanelVList.GetAdjustState() : String; 719 | Var 720 | i : Integer; 721 | begin 722 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TGUIPanelVList.GetAdjustState', Self); {$ENDIF} // SmartUpdate('GUIPanelHVList:692'); 723 | 724 | Result := IntToStr(Self.Width) +'x'+ IntToStr(Self.Height) +':' + 725 | IntToStr(Self.ControlCount) +':'+ 726 | IntToStr(Self.ComponentCount) +':'+ 727 | IntToStr(Self.MarginVertical) +':'+ 728 | IntToStr(Self.MarginTop) +':'+ 729 | IntToStr(Self.MarginLeft) +':'+ 730 | IntToStr(Self.MarginSeparator) +':'; 731 | 732 | if Self.ResizeControls then Result := Result + 'x' else Result := Result + 'z'; 733 | if Self.SortByTags then Result := Result + 'x' else Result := Result + 'z'; 734 | if Self.ReverseFill then Result := Result + 'x' else Result := Result + 'z'; 735 | if Self.AutoSizeW then Result := Result + 'x' else Result := Result + 'z'; 736 | if Self.AutoSizeH then Result := Result + 'x' else Result := Result + 'z'; 737 | 738 | if Self.Parent <> nil then 739 | begin 740 | Result := Result + IntToStr(Self.Parent.Width) +'x'+ IntToStr(Self.Parent.Height) +':'; 741 | end; 742 | 743 | for i := 0 to Self.ControlCount-1 do 744 | begin 745 | // SmartUpdate('GUIPanelHVList:738'); 746 | Result := Result + 747 | IntToStr(Self.Controls[i].Width) + 'x' + 748 | IntToStr(Self.Controls[i].Height) +':'+ 749 | IntToStr(Self.Controls[i].Left) +':'+ 750 | IntToStr(Self.Controls[i].Top) +':'+ 751 | 752 | IntToStr(Self.Controls[i].Margins.Left) +':'+ 753 | IntToStr(Self.Controls[i].Margins.Top) +':'+ 754 | IntToStr(Self.Controls[i].Margins.Right) +':'+ 755 | IntToStr(Self.Controls[i].Margins.Bottom) +':'+ 756 | 757 | IntToStr(Self.Controls[i].Tag) +':'; 758 | if Self.Controls[i].Visible then Result := Result + 'vis'; 759 | end; 760 | 761 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TGUIPanelVList.GetAdjustState'); end; {$ENDIF} 762 | end; 763 | 764 | // Lines up controls vertically 765 | procedure TGUIPanelVList.AdjustControls(const ForceUpdate : Boolean = False); 766 | var 767 | i, X, Y : Integer; 768 | iVal : Integer; 769 | prevName : String; 770 | CurState : String; 771 | NewSize : TPoint; 772 | MaxPos : TPoint; 773 | Control : TControl; 774 | ControlList : TObjectList; 775 | {$IFDEF Debug_Assert_IfPosChanged} CurState : String; OldState : String; {$ENDIF} 776 | begin 777 | {$IFDEF EnablePerformanceLog} try PerfLog_SectionBegin('TGUIPanelVList.AdjustControls', Self); {$ENDIF} // SmartUpdate('GUIPanelHVList:738'); 778 | 779 | if Self = nil then EXIT; 780 | if csReading in ComponentState then EXIT; 781 | If Self.ControlCount < 1 then EXIT; 782 | 783 | if ForceUpdate = False then 784 | begin 785 | CurState := GetAdjustState(); 786 | if FLastAdjustState = CurState then EXIT; 787 | End; 788 | 789 | 790 | // Call the AdjustControls() of any child controls: 791 | for i := 0 to Self.ControlCount - 1 do 792 | begin 793 | // SmartUpdate('GUIPanelHVList:786'); 794 | Control := Self.Controls[i]; 795 | if (Control <> nil) and (Control <> self) then 796 | begin 797 | If (Control is TGUIPanelVList) then TGUIPanelVList(Control).AdjustControls(); 798 | If (Control is TGUIPanelHList) then TGUIPanelHList(Control).AdjustControls(); 799 | 800 | //if (Control is TPTZCheckBox) then TPTZCheckBox(Control).AdjustAutoSize(); 801 | //if (Control is TPTZRadioButton) then TPTZRadioButton(Control).AdjustAutoSize(); 802 | 803 | // Fix case of autosize labels: 804 | if (Self.ResizeControls) and (Control is TLabel) and (TLabel(Control).AutoSize) then TLabel(Control).AutoSize := False; 805 | End; 806 | end; 807 | 808 | for i := 0 to Self.ControlCount - 1 do 809 | begin 810 | // SmartUpdate('GUIPanelHVList:800'); 811 | Control := Self.Controls[i]; 812 | if (Control <> nil) and (Control <> self) and (Control.Align <> alNone) and (Control is TWinControl) then TWinControl(Control).Realign; 813 | End; 814 | // ** 815 | 816 | 817 | NewSize := Point(0, 0); 818 | ControlList := TObjectList.Create(False); 819 | 820 | for i := 0 to Self.ControlCount - 1 do 821 | begin 822 | // SmartUpdate('GUIPanelHVList:812'); 823 | Control := Self.Controls[i]; 824 | if (Control = nil) or (Control = self) then Continue; // just in case 825 | If (FIgnoreInvisible) and (Control.Visible = False) then Continue; 826 | ControlList.Add(Control); 827 | end; 828 | 829 | if ReverseFill then 830 | begin 831 | Y := Height - FMarginTop - 1; 832 | if FSortByTags then 833 | ControlList.Sort(@ControlSorter_Tag) 834 | else 835 | ControlList.Sort(@ControlSorter_V_Reverse); 836 | end 837 | else 838 | begin 839 | Y := FMarginTop; 840 | if FSortByTags then 841 | ControlList.Sort(@ControlSorter_Tag) 842 | else 843 | ControlList.Sort(@ControlSorter_V); 844 | end; 845 | 846 | 847 | {$IFDEF Debug_Assert_IfPosChanged} 848 | If (not (csReading in ComponentState)) and (FLastControlStates <> nil) and (FLastControlStates.Count > 0) then 849 | begin 850 | for i := 0 to ControlList.Count - 1 do 851 | begin 852 | Control := TControl(ControlList[i]); 853 | CurState := IntToStr(Control.Left) +':'+ IntToStr(Control.Top); 854 | If FLastControlStates.TryGetValue(Control.Name, OldState) then 855 | AssertEx(OldState = CurState, 'Control state changed: ' + Control.Name + ', Self: ' + Self.Name + ', Current state: ' + CurState + ', Old state: ' + OldState); 856 | End; 857 | End; 858 | {$ENDIF} 859 | 860 | // iterate controls; collect width and height 861 | for i := 0 to ControlList.Count - 1 do 862 | begin 863 | // SmartUpdate('GUIPanelHVList:853'); 864 | Control := TControl(ControlList[i]); 865 | Control.Align := alNone; 866 | 867 | iVal := FMarginLeft; 868 | If (FExtraLabelMargin <> 0) and (Control is TLabel) then Inc(iVal, FExtraLabelMargin); 869 | If (FExtraMemoMargin <> 0) and (Control is TMemo) then Inc(iVal, FExtraMemoMargin); 870 | Control.Left := iVal; 871 | 872 | 873 | if FResizeControls then 874 | Control.Width := Self.Width - (Control.Left * 2); 875 | 876 | 877 | 878 | if ReverseFill then 879 | begin 880 | Dec(Y, Control.Height); 881 | if i > 0 then 882 | begin 883 | if Control.ClassName <> prevName then 884 | Dec(Y, FMarginSeparator); 885 | 886 | Dec(Y, FMarginVertical); 887 | if Control is TLabel then Dec(Y, FExtraLabelSeparation); 888 | 889 | if Control.AlignWithMargins then 890 | Dec(Y, Control.Margins.Top); 891 | end; 892 | Control.Top := Y; 893 | prevName := Control.ClassName; 894 | end 895 | else 896 | begin 897 | if i > 0 then 898 | begin 899 | if Control.ClassName <> prevName then 900 | Inc(Y, FMarginSeparator); 901 | 902 | Inc(Y, FMarginVertical); 903 | if Control is TLabel then Inc(Y, FExtraLabelSeparation); 904 | 905 | if Control.AlignWithMargins then 906 | Inc(Y, Control.Margins.Top); 907 | end; 908 | Control.Top := Y; 909 | Inc(Y, Control.Height); 910 | prevName := Control.ClassName; 911 | end; 912 | end; 913 | 914 | 915 | 916 | if ReverseFill then 917 | Dec(Y, FMarginVertical) 918 | else 919 | Inc(Y, FMarginVertical); 920 | 921 | 922 | // resize width if needed 923 | if FAutoSizeW then 924 | begin 925 | for i := 0 to Self.ControlCount - 1 do 926 | begin 927 | X := Controls[i].Width; 928 | if (X > MaxPos.X) or (i = 0) then MaxPos.X := X; 929 | end; 930 | 931 | X := MaxPos.X; 932 | 933 | if X <> Width then Width := X; 934 | end; 935 | 936 | // resize height if needed 937 | if FAutoSizeH then 938 | begin 939 | Y := Y + Self.Margins.Top; 940 | Y := Y + Self.Margins.Bottom; 941 | if Y <> Height then Height := Y; 942 | end; 943 | 944 | 945 | {$IFDEF Debug_Assert_IfPosChanged} 946 | If not (csReading in ComponentState) then 947 | begin 948 | for i := 0 to ControlList.Count - 1 do 949 | begin 950 | Control := TControl(ControlList[i]); 951 | CurState := IntToStr(Control.Left) +':'+ IntToStr(Control.Top); 952 | FLastControlStates.AddOrSetValue(Control.Name, CurState); 953 | End; 954 | End; 955 | {$ENDIF} 956 | 957 | FLastAdjustState := GetAdjustState(); 958 | ControlList.Free; 959 | 960 | {$IFDEF EnablePerformanceLog} finally PerfLog_SectionEnd('TGUIPanelVList.AdjustControls'); end; {$ENDIF} 961 | end; 962 | 963 | end. 964 | -------------------------------------------------------------------------------- /InternetUtils.pas: -------------------------------------------------------------------------------- 1 | unit InternetUtils; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | interface 6 | 7 | uses 8 | madExcept, Winapi.Windows, 9 | System.SysUtils, 10 | System.Classes, 11 | StrUtils, 12 | ShellApi, 13 | System.IOUtils, 14 | //FastStringUtils, 15 | Forms, 16 | //SystemInfoUtils, 17 | HTTPApp, IdHTTP, 18 | IdSSLOpenSSL, 19 | Winapi.WinInet, 20 | Winapi.UrlMon; 21 | 22 | 23 | {$DEFINE Use_Debug_Log} 24 | 25 | function DownloadURL_BLOCKING(const aUrl: string; var s: String; const Agent : String): Boolean; 26 | 27 | function DownloadURL_BLOCKING_method1(const aUrl: string; var s: String; const Agent : String): Boolean; 28 | function DownloadURL_BLOCKING_method2(const aUrl: string; var s: String; const Agent : String; AccessType : Integer): Boolean; 29 | 30 | function DownloadFILE_BLOCKING(const aUrl: string; const OutputFilename : String; const Agent : String) : Boolean; 31 | 32 | 33 | function DownloadFILE_BLOCKING_method1(const aURL: string; const DestinationFileName: string; const UserAgent: string) : Boolean; 34 | function DownloadFILE_BLOCKING_method2(const aUrl: string; const OutputFilename : String; const Agent : String; AccessType : Integer): Integer; 35 | function DownloadFILE_BLOCKING_method3(const aUrl: string; const OutputFilename : String): Boolean; 36 | function DownloadFILE_BLOCKING_method4(const aUrl: string; const OutputFilename : String): Boolean; 37 | function DownloadFILE_BLOCKING_method5(const aUrl: string; const OutputFilename : String): Boolean; 38 | 39 | function ArrayToString(const a: array of Char): string; 40 | 41 | function GetWinInetError(ErrorCode:Cardinal): string; 42 | Function RunAsAdminAndWait(Filename, Parameters : String; ShowMode : Integer = SW_SHOW; MaxWaitTimeMSEC : Integer = 5000) : Integer; 43 | 44 | 45 | 46 | Var 47 | GLOB_Internet_DebugLog : TStringList; 48 | GLOB_Has_Internet : Integer; // // 1: yes, 0: no, -1: unknown 49 | 50 | 51 | implementation 52 | 53 | 54 | function GetWinInetError(ErrorCode:Cardinal): string; 55 | const 56 | winetdll = 'wininet.dll'; 57 | var 58 | Len: Integer; 59 | Buffer: PChar; 60 | begin 61 | Len := FormatMessage( 62 | FORMAT_MESSAGE_FROM_HMODULE or FORMAT_MESSAGE_FROM_SYSTEM or 63 | FORMAT_MESSAGE_ALLOCATE_BUFFER or FORMAT_MESSAGE_IGNORE_INSERTS or FORMAT_MESSAGE_ARGUMENT_ARRAY, 64 | Pointer(GetModuleHandle(winetdll)), ErrorCode, 0, @Buffer, SizeOf(Buffer), nil); 65 | try 66 | while (Len > 0) and {$IFDEF UNICODE}(CharInSet(Buffer[Len - 1], [#0..#32, '.'])) {$ELSE}(Buffer[Len - 1] in [#0..#32, '.']) {$ENDIF} do Dec(Len); 67 | SetString(Result, Buffer, Len); 68 | finally 69 | LocalFree(HLOCAL(Buffer)); 70 | end; 71 | end; 72 | 73 | function ArrayToString(const a: array of Char): string; 74 | Var 75 | i : Integer; 76 | begin 77 | Result := ''; 78 | 79 | if Length(a) > 0 then 80 | begin 81 | if a[Low(a)] = #0 then Exit; // null string 82 | 83 | for i := Low(a) to High(a) do 84 | begin 85 | if a[i] = #0 then Break; 86 | Result := Result + String(a[i]); 87 | end; 88 | 89 | // SetString(Result, PChar(@a[0]), Length(a)); 90 | 91 | end; 92 | 93 | end; 94 | 95 | 96 | 97 | function DownloadFILE_BLOCKING(const aUrl: string; const OutputFilename : String; const Agent : String): Boolean; 98 | 99 | 100 | Function DoGetFileSize(const Filename : String) : Int64; 101 | var 102 | Sr : TSearchRec; 103 | begin 104 | 105 | Result := -1; 106 | If (Length(Filename) < 5) or (FileExists(Filename) = False) then Exit; 107 | 108 | Try 109 | Try 110 | FindFirst(Filename, faAnyFile, Sr); 111 | Result := Int64(Sr.FindData.nFileSizeHigh) shl Int64(32) + 112 | Int64(Sr.FindData.nFileSizeLow); 113 | Finally 114 | FindClose(sr); 115 | End; 116 | Except 117 | Result := -1; 118 | End; 119 | end; 120 | 121 | 122 | Begin 123 | 124 | 125 | if (OutputFilename = '') or (Length(OutputFilename) < 5) or (OutputFilename[2] <> ':') or (OutputFilename[3] <> '\') then EXIT(FALSE); 126 | 127 | Try 128 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add(#13#10 + 'DownloadFILE_BLOCKING Start: ' + aUrl + ', To: ' + OutputFilename); {$ENDIF} 129 | DownloadFILE_BLOCKING_method1(aUrl, OutputFilename, Agent); 130 | Except 131 | Sleep(500); 132 | End; 133 | 134 | 135 | // Fallback: 136 | if (DoGetFileSize(OutputFilename) < 5) then 137 | begin 138 | Try 139 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING FailSafe-m2 Start'); {$ENDIF} 140 | DownloadFILE_BLOCKING_method2(aUrl, OutputFilename, Agent, INTERNET_OPEN_TYPE_DIRECT); 141 | Except 142 | Sleep(500); 143 | End; 144 | end; 145 | 146 | 147 | // Fallback: 148 | if (DoGetFileSize(OutputFilename) < 5) then 149 | begin 150 | Try 151 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING FailSafe-m3 Start'); {$ENDIF} 152 | DownloadFILE_BLOCKING_method3(aUrl, OutputFilename); 153 | Except 154 | Sleep(500); 155 | End; 156 | end; 157 | 158 | // Fallback: 159 | if (DoGetFileSize(OutputFilename) < 5) then 160 | begin 161 | Try 162 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING FailSafe-m4 Start'); {$ENDIF} 163 | DownloadFILE_BLOCKING_method4(aUrl, OutputFilename); 164 | Except 165 | Sleep(500); 166 | End; 167 | end; 168 | 169 | // Fallback: 170 | if (DoGetFileSize(OutputFilename) < 5) then 171 | begin 172 | Try 173 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING FailSafe-m5 Start'); {$ENDIF} 174 | DownloadFILE_BLOCKING_method5(aUrl, OutputFilename); 175 | Except 176 | Sleep(500); 177 | End; 178 | end; 179 | 180 | Result := (DoGetFileSize(OutputFilename) >= 5); 181 | 182 | If Result then 183 | begin 184 | GLOB_Has_Internet := 1; 185 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING OK: ' + aUrl); {$ENDIF} 186 | End else 187 | begin 188 | if GLOB_Has_Internet = -1 then GLOB_Has_Internet := 0; 189 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING Fail: ' + aUrl); {$ENDIF} 190 | End; 191 | 192 | End; 193 | 194 | 195 | Function TrimEx_Simple(const Str : String; const RemoveStr : String) : String; 196 | Begin 197 | 198 | Result := Str; 199 | 200 | While (Result <> '') and (Pos(Result[1], RemoveStr) > 0) do Delete(Result, 1, 1); 201 | While (Result <> '') and (Pos(Result[Length(Result)], RemoveStr) > 0) do Result := Copy(Result, 1, Length(Result)-1); 202 | 203 | End; 204 | 205 | function DownloadFILE_BLOCKING_method1(const aURL: string; const DestinationFileName: string; const UserAgent: string) : Boolean; 206 | var 207 | i : Integer; 208 | hInet : HINTERNET; 209 | hConnect : HINTERNET; 210 | hRequest : HINTERNET; 211 | HttpStatus: Integer; 212 | lpvBuffer : PAnsiChar; 213 | lpdwBufferLength: DWORD; 214 | lpdwReserved : DWORD; 215 | dwBytesRead : DWORD; 216 | lpdwNumberOfBytesAvailable: DWORD; 217 | dwBytesWritten: DWORD; 218 | FileHandle: THandle; 219 | ServerName : String; 220 | Resource : String; 221 | begin 222 | 223 | Result := False; 224 | hInet := InternetOpen(PChar(UserAgent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); 225 | 226 | if hInet = nil then 227 | begin 228 | //ErrorCode := GetLastError; 229 | //raise Exception.Create(Format('InternetOpen Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)])); 230 | EXIT; 231 | end; 232 | 233 | i := Pos('.', aURL); 234 | if i < 2 then EXIT; 235 | 236 | i := PosEx('/', aURL, i); 237 | if i < 2 then EXIT; 238 | 239 | ServerName := Trim(Copy(aURL, 1, i-1)); 240 | Resource := Trim(Copy(aURL, i, Length(aURL))); 241 | ServerName := TrimEx_Simple(ServerName, ' :\/'); 242 | 243 | i := Pos(':', ServerName); 244 | if i > 0 then ServerName := Trim(Copy(ServerName, i+1, Length(ServerName))); 245 | ServerName := TrimEx_Simple(ServerName, ' :\/'); 246 | 247 | 248 | try 249 | hConnect := InternetConnect(hInet, PChar(ServerName), INTERNET_DEFAULT_HTTPS_PORT, nil, nil, INTERNET_SERVICE_HTTP, INTERNET_FLAG_SECURE, 1); 250 | if hConnect=nil then 251 | begin 252 | // ErrorCode:=GetLastError; 253 | // raise Exception.Create(Format('InternetConnect Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)])); 254 | EXIT; 255 | end; 256 | 257 | try 258 | //make the request 259 | hRequest := HttpOpenRequest(hConnect, 'GET', PChar(Resource), HTTP_VERSION, '', nil, INTERNET_FLAG_SECURE, 0); 260 | if hRequest=nil then 261 | begin 262 | //ErrorCode:=GetLastError; 263 | //raise Exception.Create(Format('HttpOpenRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)])); 264 | EXIT; 265 | end; 266 | 267 | try 268 | //send the GET request 269 | if not HttpSendRequest(hRequest, nil, 0, nil, 0) then 270 | begin 271 | //ErrorCode:=GetLastError; 272 | //raise Exception.Create(Format('HttpSendRequest Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)])); 273 | EXIT; 274 | end; 275 | 276 | lpdwBufferLength := SizeOf(HttpStatus); 277 | lpdwReserved :=0; 278 | //get the status code 279 | if not HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @HttpStatus, lpdwBufferLength, lpdwReserved) then 280 | begin 281 | //ErrorCode := GetLastError; 282 | //raise Exception.Create(Format('HttpQueryInfo Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)])); 283 | EXIT; 284 | end; 285 | 286 | FileHandle := CreateFile(PWideChar(DestinationFileName),GENERIC_WRITE,FILE_SHARE_WRITE,nil,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); 287 | if FileHandle <> INVALID_HANDLE_VALUE then 288 | begin 289 | //if HttpStatus=200 then //read the body response in case which the status code is 200 290 | repeat 291 | lpdwNumberOfBytesAvailable := 0; 292 | if InternetQueryDataAvailable(hRequest, lpdwNumberOfBytesAvailable, 0, 0) then 293 | begin 294 | GetMem(lpvBuffer,lpdwNumberOfBytesAvailable); 295 | try 296 | InternetReadFile(hRequest, lpvBuffer, lpdwNumberOfBytesAvailable, dwBytesRead); 297 | WriteFile(FileHandle, lpvBuffer^, dwBytesRead, dwBytesWritten, nil); 298 | Result := True; 299 | finally 300 | FreeMem(lpvBuffer); 301 | end; 302 | end 303 | until lpdwNumberOfBytesAvailable <= 0; 304 | CloseHandle(FileHandle); 305 | end 306 | else 307 | begin 308 | //ErrorCode := GetLastError(); 309 | // Log('Cannot create ' +DestinationFileName + ' file. Error Code = ' + IntToStr(ErrorCode) + '. File Attributes: ' + IntToHex(GetFileAttributes(PWideChar(DestinationFileName)), 8)); 310 | end; 311 | //else 312 | //begin 313 | // ErrorCode := GetLastError; 314 | // raise Exception.Create(Format('InternetQueryDataAvailable Error %d Description %s',[ErrorCode,GetWinInetError(ErrorCode)])); 315 | //end; 316 | finally 317 | InternetCloseHandle(hRequest); 318 | end; 319 | finally 320 | InternetCloseHandle(hConnect); 321 | end; 322 | finally 323 | InternetCloseHandle(hInet); 324 | end; 325 | end; 326 | 327 | function DownloadFILE_BLOCKING_method3(const aUrl: string; const OutputFilename : String): Boolean; 328 | Begin 329 | 330 | URLDownloadToFile(nil, 331 | PChar(aUrl), 332 | PChar(OutputFilename), 333 | 0, 334 | nil); 335 | 336 | Result := FileExists(OutputFilename); 337 | 338 | End; 339 | 340 | 341 | function DownloadFILE_BLOCKING_method4(const aUrl: string; const OutputFilename : String): Boolean; 342 | var 343 | IdHTTP: TIdHTTP; 344 | Stream: TMemoryStream; 345 | begin 346 | 347 | Result := False; 348 | 349 | Stream := TMemoryStream.Create; 350 | IdHTTP := TIdHTTP.Create(nil); 351 | IdHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(IdHTTP); 352 | IdHTTP.HandleRedirects := True; 353 | 354 | try 355 | Try 356 | IdHTTP.Get(aUrl, Stream); 357 | Stream.SaveToFile(OutputFilename); 358 | Except 359 | Exit; 360 | End; 361 | finally 362 | Stream.Free; 363 | IdHTTP.Free; 364 | end; 365 | 366 | Result := FileExists(OutputFilename); 367 | 368 | End; 369 | 370 | 371 | 372 | function DownloadFILE_BLOCKING_method5(const aUrl: string; const OutputFilename : String): Boolean; 373 | Var 374 | cUrlPath : String; 375 | TmpPath : String; 376 | begin 377 | 378 | Result := False; 379 | 380 | cUrlPath := ExtractFilePath(Application.Exename) + 'cURL\curl.exe'; 381 | if FileExists(cUrlPath) = False then cUrlPath := ExtractFilePath(Application.Exename) + 'cUrl\curl.exe'; 382 | if FileExists(cUrlPath) = False then cUrlPath := ExtractFilePath(Application.Exename) + 'curl\curl.exe'; 383 | 384 | if FileExists(cUrlPath) = False then 385 | begin 386 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING_method5 FAIL-1: ' + cUrlPath); {$ENDIF} 387 | EXIT; 388 | End; 389 | 390 | 391 | 392 | 393 | TmpPath := ExtractFilePath(OutputFilename); 394 | if DirectoryExists(TmpPath) = False then 395 | begin 396 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING_method5 FAIL-2: ' + TmpPath); {$ENDIF} 397 | EXIT; 398 | End; 399 | 400 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadFILE_BLOCKING_method5 Start: ' + cUrlPath); {$ENDIF} 401 | 402 | RunAsAdminAndWait(cUrlPath, ' -o "' + OutputFilename +'" '+ aUrl, SW_HIDE, 30000); 403 | 404 | Result := FileExists(OutputFilename); 405 | 406 | End; 407 | 408 | 409 | Function RunAsAdminAndWait(Filename, Parameters : String; ShowMode : Integer = SW_SHOW; MaxWaitTimeMSEC : Integer = 5000) : Integer; 410 | var 411 | Info : TShellExecuteInfo; 412 | ExitCode : DWORD; 413 | Start : UInt64; 414 | begin 415 | Result := -1; 416 | 417 | FillChar(Info, SizeOf(Info), 0); 418 | Info.cbSize := SizeOf(TShellExecuteInfo); 419 | Info.fMask := SEE_MASK_NOCLOSEPROCESS; 420 | Info.Wnd := Application.Handle; 421 | Info.lpVerb := 'RunAs'; 422 | Info.lpFile := PWideChar(Filename); 423 | Info.lpParameters := PWideChar(Parameters); 424 | Info.nShow := ShowMode; 425 | Start := GetTickCount64(); 426 | 427 | if ShellExecuteEx(@Info) and (MaxWaitTimeMSEC > 1) then 428 | begin 429 | ExitCode := 0; 430 | 431 | while True do 432 | begin 433 | Sleep(100); Application.ProcessMessages; 434 | GetExitCodeProcess(Info.hProcess, ExitCode); 435 | 436 | If (ExitCode <> STILL_ACTIVE) or (Application = nil) or (Application.Terminated) then Break; 437 | if GetTickCount64() - Start > MaxWaitTimeMSEC then Break; 438 | End; 439 | 440 | Result := ExitCode; 441 | end; 442 | 443 | end; 444 | 445 | function DownloadFILE_BLOCKING_method2(const aUrl: string; const OutputFilename : String; const Agent : String; AccessType : Integer): Integer; 446 | var 447 | hSession : HINTERNET; 448 | hService : HINTERNET; 449 | lpBuffer : array[0..1024 + 1] of Char; 450 | dwBytesRead : DWORD; 451 | Start : UInt64; 452 | FileOut : TFileStream; 453 | begin 454 | Result := 0; 455 | Start := GetTickCount64(); 456 | 457 | Try 458 | if FileExists(OutputFilename) then DeleteFile(PWideChar(OutputFilename)); 459 | Except 460 | Exit; 461 | End; 462 | 463 | FileOut := TFileStream.Create(OutputFilename, fmCreate); 464 | hSession := InternetOpen(PWideChar(Agent), AccessType, nil, nil, 0); 465 | 466 | try 467 | if Assigned(hSession) then 468 | begin 469 | //hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_IGNORE_CERT_DATE_INVALID or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS or INTERNET_FLAG_NO_UI, 0); 470 | 471 | hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_IGNORE_CERT_DATE_INVALID or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS or INTERNET_FLAG_NO_UI, 0); 472 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS or INTERNET_FLAG_NO_UI, 0); 473 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_NO_UI, 0); 474 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_NO_UI, 0); 475 | 476 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_IGNORE_CERT_DATE_INVALID, 0); 477 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_IGNORE_CERT_CN_INVALID, 0); 478 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, INTERNET_FLAG_RELOAD, 0); 479 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(aUrl), nil, 0, 0, 0); 480 | 481 | 482 | if Assigned(hService) then 483 | try 484 | 485 | while True do 486 | begin 487 | dwBytesRead := 1024; 488 | InternetReadFile(hService, @lpBuffer, 1024, dwBytesRead); 489 | if dwBytesRead = 0 then break; 490 | 491 | lpBuffer[dwBytesRead] := #0; 492 | FileOut.Write(lpBuffer, dwBytesRead); 493 | 494 | // Timeout 495 | if (GetTickCount64() - Start) > 30000 then 496 | begin 497 | Result := -1; 498 | Break; 499 | end; 500 | 501 | Result := 1; 502 | end; 503 | finally 504 | InternetCloseHandle(hService); 505 | end; 506 | end; 507 | finally 508 | InternetCloseHandle(hSession); 509 | FileOut.Free 510 | end; 511 | end; 512 | 513 | 514 | 515 | function DownloadURL_BLOCKING_Method1(const aUrl: string; var s: String; const Agent : String): Boolean; 516 | var 517 | i : Integer; 518 | hInet : HINTERNET; 519 | hConnect : HINTERNET; 520 | hRequest : HINTERNET; 521 | HttpStatus: Integer; 522 | ErrorCode : Integer; 523 | lpvBuffer : PAnsiChar; 524 | lpdwBufferLength: DWORD; 525 | lpdwReserved : DWORD; 526 | dwBytesRead : DWORD; 527 | lpdwNumberOfBytesAvailable: DWORD; 528 | ServerName : String; 529 | Resource : String; 530 | begin 531 | 532 | Result := False; 533 | s := ''; 534 | 535 | hInet := InternetOpen(PChar(Agent), INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0); 536 | 537 | {$IFDEF Use_Debug_Log} 538 | if Assigned(hInet) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 hInet: OK') 539 | else begin ErrorCode := GetLastError(); GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 hInet: FAIL - Error Code: ' + IntToStr(ErrorCode) + ', Error Desc: ' +GetWinInetError(ErrorCode)); End; 540 | {$ENDIF} 541 | 542 | if hInet = nil then EXIT; 543 | 544 | 545 | 546 | i := Pos('.', aURL); 547 | if i < 2 then EXIT; 548 | 549 | i := PosEx('/', aURL, i); 550 | if i < 2 then EXIT; 551 | 552 | ServerName := Trim(Copy(aURL, 1, i-1)); 553 | Resource := Trim(Copy(aURL, i, Length(aURL))); 554 | ServerName := TrimEx_Simple(ServerName, ' :\/'); 555 | 556 | i := Pos(':', ServerName); 557 | if i > 0 then ServerName := Trim(Copy(ServerName, i+1, Length(ServerName))); 558 | ServerName := TrimEx_Simple(ServerName, ' :\/'); 559 | 560 | 561 | try 562 | hConnect := InternetConnect(hInet, PChar(ServerName), INTERNET_DEFAULT_HTTPS_PORT, nil, nil, INTERNET_SERVICE_HTTP, INTERNET_FLAG_SECURE, 1); 563 | 564 | 565 | {$IFDEF Use_Debug_Log} 566 | if Assigned(hConnect) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 hConnect: OK') 567 | else begin ErrorCode := GetLastError(); GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 hConnect: FAIL - Error Code: ' + IntToStr(ErrorCode) + ', Error Desc: ' +GetWinInetError(ErrorCode)); End; 568 | {$ENDIF} 569 | 570 | if hConnect=nil then EXIT; 571 | 572 | try 573 | //make the request 574 | hRequest := HttpOpenRequest(hConnect, 'GET', PChar(Resource), HTTP_VERSION, '', nil, INTERNET_FLAG_SECURE, 0); 575 | 576 | {$IFDEF Use_Debug_Log} 577 | if Assigned(hRequest) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 hRequest: OK') 578 | else begin ErrorCode := GetLastError(); GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 hRequest: FAIL - Error Code: ' + IntToStr(ErrorCode) + ', Error Desc: ' +GetWinInetError(ErrorCode)); End; 579 | {$ENDIF} 580 | 581 | if hRequest=nil then EXIT; 582 | 583 | try 584 | //send the GET request 585 | if not HttpSendRequest(hRequest, nil, 0, nil, 0) then 586 | begin 587 | 588 | 589 | {$IFDEF Use_Debug_Log} 590 | ErrorCode := GetLastError(); 591 | GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 HttpSendRequest: FAIL - Error Code: ' + IntToStr(ErrorCode) + ', Error Desc: ' +GetWinInetError(ErrorCode)); 592 | {$ENDIF} 593 | 594 | EXIT; 595 | end; 596 | 597 | lpdwBufferLength := SizeOf(HttpStatus); 598 | lpdwReserved :=0; 599 | 600 | //get the status code 601 | if not HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE or HTTP_QUERY_FLAG_NUMBER, @HttpStatus, lpdwBufferLength, lpdwReserved) then 602 | begin 603 | 604 | {$IFDEF Use_Debug_Log} 605 | ErrorCode := GetLastError(); 606 | GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Method1 HttpQueryInfo: FAIL - Error Code: ' + IntToStr(ErrorCode) + ', Error Desc: ' +GetWinInetError(ErrorCode)); 607 | {$ENDIF} 608 | 609 | EXIT; 610 | end; 611 | 612 | //if HttpStatus=200 then //read the body response in case which the status code is 200 613 | repeat 614 | lpdwNumberOfBytesAvailable := 0; 615 | 616 | if InternetQueryDataAvailable(hRequest, lpdwNumberOfBytesAvailable, 0, 0) and (lpdwNumberOfBytesAvailable > 0) then 617 | begin 618 | GetMem(lpvBuffer,lpdwNumberOfBytesAvailable+1); 619 | try 620 | dwBytesRead := 0; 621 | InternetReadFile(hRequest, lpvBuffer, lpdwNumberOfBytesAvailable, dwBytesRead); 622 | //WriteFile(FileHandle, lpvBuffer^, dwBytesRead, dwBytesWritten, nil); 623 | 624 | If dwBytesRead < 1 then Break; 625 | lpvBuffer[dwBytesRead] := #0; 626 | s := s + String(lpvBuffer); 627 | 628 | Result := True; 629 | finally 630 | FreeMem(lpvBuffer); 631 | end; 632 | end else Break; 633 | 634 | until lpdwNumberOfBytesAvailable <= 0; 635 | 636 | finally 637 | InternetCloseHandle(hRequest); 638 | end; 639 | finally 640 | InternetCloseHandle(hConnect); 641 | end; 642 | finally 643 | InternetCloseHandle(hInet); 644 | end; 645 | 646 | end; 647 | 648 | 649 | 650 | function DownloadURL_BLOCKING(const aUrl: string; var s: String; const Agent : String): Boolean; 651 | Var 652 | ResStr : String; 653 | TmpDir : String; 654 | TmpFilename : String; 655 | TmpList : TStringList; 656 | ReadFail : Boolean; 657 | begin 658 | 659 | s := ''; 660 | ResStr := ''; 661 | ReadFail := False; 662 | Result := False; 663 | 664 | Try 665 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add(#13#10 + 'DownloadURL_BLOCKING Start: ' + aUrl + ', As: ' + Agent); {$ENDIF} 666 | Result := DownloadURL_BLOCKING_Method1(aUrl, ResStr, Agent); 667 | s := ResStr; 668 | Except 669 | ReadFail := True; 670 | End; 671 | 672 | 673 | // Failsafe: 674 | if (ReadFail) or (Result = False) or (Trim(ResStr) = '') then 675 | begin 676 | Try 677 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Failsafe-m2-a Start'); {$ENDIF} 678 | Result := DownloadURL_BLOCKING_Method2(aUrl, ResStr, Agent, INTERNET_OPEN_TYPE_PRECONFIG); 679 | Except 680 | ReadFail := True; 681 | End; 682 | 683 | s := ResStr; 684 | End; 685 | 686 | 687 | // Failsafe: 688 | if (ReadFail) or (Result = False) or (Trim(ResStr) = '') then 689 | begin 690 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Failsafe-m2-b Start'); {$ENDIF} 691 | 692 | Try 693 | ResStr := ''; 694 | Result := DownloadURL_BLOCKING_Method2(aUrl, ResStr, Agent, INTERNET_OPEN_TYPE_DIRECT); 695 | ReadFail := False; 696 | Except 697 | ReadFail := True; 698 | End; 699 | 700 | s := ResStr; 701 | end; 702 | 703 | 704 | 705 | // Failsafe via DownloadFILE_BLOCKING: 706 | if (ReadFail) or (Result = False) or (Trim(ResStr) = '') then 707 | begin 708 | TmpDir := System.IOUtils.TPath.GetTempPath(); 709 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Failsafe-by-File Start: ' + TmpDir); {$ENDIF} 710 | 711 | if (Copy(TmpDir, 2, 2) = ':\') and 712 | (DirectoryExists(TmpDir)) then 713 | begin 714 | TmpFilename := TmpDir + 'DownloadUrl_Failsafe_' + IntToStr(GetTickCount64()) + '.tmp'; 715 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Failsafe-by-File File: ' + TmpFilename); {$ENDIF} 716 | 717 | 718 | if FileExists(TmpFilename) = False then 719 | begin 720 | DownloadFILE_BLOCKING(aUrl, TmpFilename, Agent); 721 | 722 | if FileExists(TmpFilename) then 723 | begin 724 | TmpList := TStringList.Create; 725 | ReadFail := False; 726 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Failsafe-by-File File Exists!'); {$ENDIF} 727 | 728 | Try 729 | TmpList.LoadFromFile(TmpFilename, TEncoding.UTF8); 730 | Except 731 | ReadFail := True; 732 | End; 733 | 734 | if ReadFail then 735 | begin 736 | ReadFail := False; 737 | 738 | Try 739 | TmpList.LoadFromFile(TmpFilename); 740 | Except 741 | ReadFail := True; 742 | End; 743 | end; 744 | 745 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Failsafe-by-File File Size: ' + IntToStr(TmpList.Count)); {$ENDIF} 746 | 747 | If ReadFail = False then 748 | begin 749 | s := TmpList.Text; 750 | Result := s <> ''; 751 | End; 752 | 753 | TmpList.Free; 754 | 755 | Try 756 | DeleteFile(TmpFilename); 757 | Except 758 | ; 759 | End; 760 | end else 761 | begin 762 | 763 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Failsafe-by-File Download Failed'); {$ENDIF} 764 | 765 | End; 766 | end; 767 | end; 768 | end; 769 | 770 | 771 | 772 | If Result then 773 | begin 774 | GLOB_Has_Internet := 1; 775 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING OK: ' + aUrl + ', Res: ' + s); {$ENDIF} 776 | End else 777 | begin 778 | if GLOB_Has_Internet = -1 then GLOB_Has_Internet := 0; 779 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING Fail: ' + aUrl); {$ENDIF} 780 | End; 781 | 782 | 783 | end; 784 | 785 | 786 | function DownloadURL_BLOCKING_Method2(const aUrl: string; var s: String; const Agent : String; AccessType : Integer): Boolean; 787 | var 788 | hSession : HINTERNET; 789 | hService : HINTERNET; 790 | lpBuffer : array[0..1024 + 1] of AnsiChar; 791 | dwBytesRead : DWORD; 792 | Start : UInt64; 793 | FinalURL : String; 794 | begin 795 | Result := False; 796 | s := ''; 797 | Start := GetTickCount64(); 798 | FinalURL := Trim(aUrl); 799 | 800 | hSession := InternetOpen(PWideChar(Agent), AccessType, nil, nil, 0); 801 | 802 | {$IFDEF Use_Debug_Log} if Assigned(hSession) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do hSession: OK') else GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do hSession: Fail'); {$ENDIF} 803 | 804 | 805 | try 806 | if Assigned(hSession) then 807 | begin 808 | hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_DONT_CACHE or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_RELOAD, 0); 809 | {$IFDEF Use_Debug_Log} If not Assigned(hService) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do GetLastError: ' + IntToStr(GetLastError)); {$ENDIF} 810 | 811 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_DONT_CACHE or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_RELOAD, 0); 812 | {$IFDEF Use_Debug_Log} If not Assigned(hService) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do GetLastError: ' + IntToStr(GetLastError)); {$ENDIF} 813 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_IGNORE_CERT_DATE_INVALID or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS or INTERNET_FLAG_NO_UI, 0); 814 | 815 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS or INTERNET_FLAG_NO_UI, 0); 816 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_PRAGMA_NOCACHE or INTERNET_FLAG_NO_UI, 0); 817 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_NO_UI, 0); 818 | 819 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_IGNORE_CERT_CN_INVALID or INTERNET_FLAG_IGNORE_CERT_DATE_INVALID, 0); 820 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_RELOAD or INTERNET_FLAG_IGNORE_CERT_CN_INVALID, 0); 821 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, INTERNET_FLAG_RELOAD, 0); 822 | if not Assigned(hService) then hService := InternetOpenUrl(hSession, PWideChar(FinalURL), nil, 0, 0, 0); 823 | 824 | 825 | 826 | 827 | {$IFDEF Use_Debug_Log} If not Assigned(hService) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do GetLastError: ' + IntToStr(GetLastError)); {$ENDIF} 828 | {$IFDEF Use_Debug_Log} if Assigned(hService) then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do hService: OK') else GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do hService: Fail'); {$ENDIF} 829 | 830 | if Assigned(hService) then 831 | try 832 | 833 | while True do 834 | begin 835 | 836 | dwBytesRead := 1024; 837 | InternetReadFile(hService, @lpBuffer, 1024, dwBytesRead); 838 | 839 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do dwBytesRead: ' + IntToStr(dwBytesRead)); {$ENDIF} 840 | if dwBytesRead = 0 then break; 841 | 842 | lpBuffer[dwBytesRead] := #0; 843 | s := s + String(lpBuffer); 844 | {$IFDEF Use_Debug_Log} GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do s: ' + s); {$ENDIF} 845 | 846 | if (GetTickCount64() - Start) > 10000 then 847 | begin 848 | s := ''; 849 | Break; 850 | end; 851 | 852 | end; 853 | 854 | Result := s <> ''; 855 | finally 856 | InternetCloseHandle(hService); 857 | end; 858 | end; 859 | finally 860 | InternetCloseHandle(hSession); 861 | end; 862 | 863 | 864 | {$IFDEF Use_Debug_Log} If Result then GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do Result: OK') else GLOB_Internet_DebugLog.Add('DownloadURL_BLOCKING_Do Result: Fail'); {$ENDIF} 865 | end; 866 | 867 | 868 | 869 | initialization 870 | 871 | GLOB_Internet_DebugLog := TStringList.Create; 872 | GLOB_Has_Internet := -1; 873 | 874 | 875 | 876 | end. 877 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /PTZGlyphButton.pas: -------------------------------------------------------------------------------- 1 | unit PTZGlyphButton; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | interface 6 | 7 | {.$DEFINE Debug_ExplicitMadExceptUse} 8 | 9 | uses 10 | {$IFDEF Debug_ExplicitMadExceptUse} madExcept, {$ENDIF} 11 | System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, 12 | Vcl.Graphics, Winapi.Messages, Winapi.Windows, Winapi.GDIPAPI, 13 | Winapi.GDIPOBJ, Math, Vcl.ImageCollection; 14 | 15 | Const 16 | TIMER_TIMEOUT = 100; 17 | 18 | type 19 | TPTZGlyphButton = class(TCustomPanel) 20 | private 21 | FUpdateLock: Integer; 22 | FFadeStep: Integer; 23 | FDirection: Integer; 24 | FMouseDown: Boolean; 25 | FTimer: TTimer; 26 | FTimerStart : UInt64; 27 | FTimerLock : Boolean; 28 | FMouseEntered : Boolean; 29 | 30 | FFadeInSteps: Integer; 31 | FFadeInStepDelay: Integer; 32 | FFadeOutSteps: Integer; 33 | FFadeOutStepDelay: Integer; 34 | FClickSteps: Integer; 35 | FClickStepDelay: Integer; 36 | FBorderWidth: Integer; 37 | FBorderCornerRadius: Integer; 38 | FColor: TColor; 39 | FBorderColor: TColor; 40 | FFocusBorderColor: TColor; 41 | FFocusColor: TColor; 42 | FClickBorderColor: TColor; 43 | FClickColor: TColor; 44 | FBackgroundColor: TColor; // the color of the canvas under the button 45 | 46 | FLeftMarginGlyph : Integer; 47 | FLeftMarginText : Integer; 48 | FTopMarginGlyph : Integer; 49 | FTextAlignment : TAlignment ; 50 | 51 | FGlyphName : string; 52 | FGlyphSize : Integer; 53 | FGlyphForcedSize : Integer; 54 | FImageCollection: TImageCollection; 55 | FTagStr: String; 56 | FContentWidth : Integer; 57 | FGlyphCentered : Boolean; 58 | FDefaultButton : Boolean; 59 | FBorderWidthDef : Integer; 60 | 61 | procedure SetColor(NewColor: TColor); 62 | procedure SetBorderColor(NewColor: TColor); 63 | procedure SetFocusBorderColor(NewColor: TColor); 64 | procedure SetFocusColor(NewColor: TColor); 65 | procedure SetClickBorderColor(NewColor: TColor); 66 | procedure SetClickColor(NewColor: TColor); 67 | procedure SetBackgroundColor(NewColor: TColor); 68 | procedure SetBorderWidth(NewWidth: Integer); 69 | procedure SetDefaultButtonBorderWidth(NewWidth: Integer); 70 | procedure SetBorderCornerRadius(NewValue: Integer); 71 | 72 | procedure SetLeftMarginGlyph(NewValue: Integer); 73 | procedure SetLeftMarginText(NewValue: Integer); 74 | procedure SetTopMarginGlyph(NewValue: Integer); 75 | Procedure SetDefaultButton(NewValue : Boolean); 76 | 77 | procedure SetImageCollection(NewValue: TImageCollection); 78 | procedure SetGlyphName(NewValue: string); 79 | procedure SetGlyphForcedSize(NewValue: Integer); 80 | function GetContentWidth() : Integer; 81 | protected 82 | procedure OnTimer(Sender: TObject); 83 | 84 | procedure WMEraseBkGnd(var Message: TMessage); message WM_ERASEBKGND; 85 | procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; 86 | procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; 87 | procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; 88 | procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; 89 | procedure Paint; override; 90 | public 91 | constructor Create(AOwner: TComponent); override; 92 | destructor Free; 93 | 94 | procedure BeginUpdate(); 95 | procedure EndUpdate(); 96 | procedure CopySettingsFrom(const SrcBtn : TPTZGlyphButton); 97 | 98 | procedure UpdateWidth(ExtraMargin : Integer = 0); 99 | published 100 | property Caption; 101 | property Font; 102 | property AlignWithMargins; 103 | property Align; 104 | property OnClick; 105 | property OnDblClick; 106 | property OnMouseDown; 107 | property OnMouseMove; 108 | property OnMouseUp; 109 | property OnMouseEnter; 110 | property OnMouseLeave; 111 | property OnResize; 112 | property ParentColor; 113 | property ParentBackground; 114 | property PopupMenu; 115 | 116 | property Alignment: TAlignment read FTextAlignment write FTextAlignment; 117 | property DefaultButton: Boolean read FDefaultButton write SetDefaultButton; 118 | 119 | property FadeInSteps: Integer read FFadeInSteps write FFadeInSteps; 120 | property FadeInStepDelay: Integer read FFadeInStepDelay write FFadeInStepDelay; 121 | property FadeOutSteps: Integer read FFadeOutSteps write FFadeOutSteps; 122 | property FadeOutStepDelay: Integer read FFadeOutStepDelay write FFadeOutStepDelay; 123 | property ClickSteps: Integer read FClickSteps write FClickSteps; 124 | property ClickStepDelay: Integer read FClickStepDelay write FClickStepDelay; 125 | property BorderWidth: Integer read FBorderWidth write SetBorderWidth; 126 | property BorderWidthDefaultButton: Integer read FBorderWidthDef write SetDefaultButtonBorderWidth; // Border width if DefaultButton = True 127 | property BorderCornerRadius: Integer read FBorderCornerRadius write SetBorderCornerRadius; 128 | 129 | property LeftMarginGlyph: Integer read FLeftMarginGlyph write SetLeftMarginGlyph; 130 | property LeftMarginText: Integer read FLeftMarginText write SetLeftMarginText; 131 | property TopMarginGlyph: Integer read FTopMarginGlyph write SetTopMarginGlyph; 132 | 133 | property Color: TColor read FColor write SetColor; 134 | property BorderColor: TColor read FBorderColor write SetBorderColor; 135 | property FocusBorderColor: TColor read FFocusBorderColor write SetFocusBorderColor; 136 | property FocusColor: TColor read FFocusColor write SetFocusColor; 137 | property ClickBorderColor: TColor read FClickBorderColor write SetClickBorderColor; 138 | property ClickColor: TColor read FClickColor write SetClickColor; 139 | property BackgroundColor: TColor read FBackgroundColor write SetBackgroundColor; 140 | 141 | property ImageCollection: TImageCollection read FImageCollection write SetImageCollection; 142 | property GlyphName: string read FGlyphName write SetGlyphName; 143 | property GlyphSize: Integer read FGlyphSize; 144 | property GlyphForcedSize: Integer read FGlyphForcedSize write SetGlyphForcedSize; 145 | 146 | property ContentWidth: Integer read GetContentWidth; 147 | property GlyphCentered: Boolean read FGlyphCentered write FGlyphCentered; 148 | property TagStr: String read FTagStr write FTagStr; 149 | end; 150 | 151 | procedure Register; 152 | 153 | implementation 154 | 155 | 156 | // Allows drawing of fading in colors, for example from white to grays to black 157 | // Note: Indexing starts at zero! 158 | Function CalculateFadeinColor(StartColor, EndColor : TColor; CurrentStep, FinalStep : Integer) : TColor; 159 | Var 160 | Steps : Integer; 161 | Start_R : Byte; 162 | Start_G : Byte; 163 | Start_B : Byte; 164 | End_R : Byte; 165 | End_G : Byte; 166 | End_B : Byte; 167 | Final_R : Byte; 168 | Final_G : Byte; 169 | Final_B : Byte; 170 | Begin 171 | if CurrentStep <= 0 then EXIT(StartColor); 172 | if CurrentStep >= FinalStep then EXIT(EndColor); 173 | If StartColor = EndColor then EXIT(EndColor); 174 | 175 | Start_R := (StartColor and $000000ff); 176 | Start_G := (StartColor and $0000ff00) shr 8; 177 | Start_B := (StartColor and $00ff0000) shr 16; 178 | End_R := (EndColor and $000000ff); 179 | End_G := (EndColor and $0000ff00) shr 8; 180 | End_B := (EndColor and $00ff0000) shr 16; 181 | Final_R := Start_R; 182 | Final_G := Start_G; 183 | Final_B := Start_B; 184 | Steps := FinalStep; 185 | if Start_R < End_R then Final_R := Final_R + Round(((End_R-Start_R) / Steps) * CurrentStep) 186 | else Final_R := Final_R - Round(((Start_R-End_R) / Steps) * CurrentStep); 187 | if Start_G < End_G then Final_G := Final_G + Round(((End_G-Start_G) / Steps) * CurrentStep) 188 | else Final_G := Final_G - Round(((Start_G-End_G) / Steps) * CurrentStep); 189 | if Start_B < End_B then Final_B := Final_B + Round(((End_B-Start_B) / Steps) * CurrentStep) 190 | else Final_B := Final_B - Round(((Start_B-End_B) / Steps) * CurrentStep); 191 | Result := RGB(Final_R, Final_G, Final_B); 192 | End; 193 | 194 | 195 | 196 | constructor TPTZGlyphButton.Create(AOwner: TComponent); 197 | begin 198 | inherited; 199 | FUpdateLock := 0; 200 | 201 | Self.BeginUpdate(); 202 | 203 | Try 204 | Font.Name := 'Segoe UI'; 205 | Self.ParentBackground := False; 206 | 207 | FDefaultButton := False; 208 | FTextAlignment := taLeftJustify; 209 | FFadeInSteps := 0; 210 | FFadeInStepDelay := 25; 211 | FFadeOutSteps := 0; 212 | FFadeOutStepDelay := 25; 213 | FClickSteps := 0; 214 | FClickStepDelay := 25; 215 | 216 | FLeftMarginGlyph := 10; 217 | FLeftMarginText := 10; 218 | FTopMarginGlyph := 0; 219 | FTagStr := ''; 220 | FContentWidth := 0; 221 | FGlyphCentered := False; 222 | 223 | FDirection := 1; 224 | FFadeStep := 0; 225 | FGlyphSize := 0; 226 | FGlyphForcedSize := 0; 227 | 228 | FMouseEntered := False; 229 | FMouseDown := False; 230 | 231 | FTimerLock := False; 232 | FTimer := nil; 233 | FTimerStart := 0; 234 | Finally 235 | Self.EndUpdate(); 236 | End; 237 | 238 | end; 239 | 240 | destructor TPTZGlyphButton.Free; 241 | begin 242 | if FTimer <> nil then 243 | begin 244 | FTimer.Free; 245 | FTimer := nil; 246 | end; 247 | end; 248 | 249 | procedure TPTZGlyphButton.WMEraseBkGnd(var Message: TMessage); 250 | begin 251 | Message.Result := 1; 252 | end; 253 | 254 | 255 | procedure TPTZGlyphButton.CopySettingsFrom(const SrcBtn : TPTZGlyphButton); 256 | begin 257 | 258 | Self.BeginUpdate(); 259 | 260 | Self.FBorderWidth := SrcBtn.BorderWidth; 261 | Self.FBorderWidthDef := SrcBtn.FBorderWidthDef; 262 | Self.FBorderColor := SrcBtn.BorderColor; 263 | Self.FBorderCornerRadius := SrcBtn.BorderCornerRadius; 264 | 265 | Self.FClickSteps := SrcBtn.ClickSteps; 266 | Self.FClickStepDelay := SrcBtn.ClickStepDelay; 267 | Self.FClickBorderColor := SrcBtn.ClickBorderColor; 268 | Self.FClickColor := SrcBtn.FClickColor; 269 | Self.FColor := SrcBtn.FColor; 270 | Self.FBackgroundColor := SrcBtn.BackgroundColor; 271 | Self.FocusColor := SrcBtn.FocusColor; 272 | Self.FocusBorderColor := SrcBtn.FocusBorderColor; 273 | Self.FFadeInSteps := SrcBtn.FFadeInSteps; 274 | Self.FFadeInStepDelay := SrcBtn.FFadeInStepDelay; 275 | Self.FFadeOutSteps := SrcBtn.FFadeOutSteps; 276 | Self.FFadeOutStepDelay := SrcBtn.FFadeOutStepDelay; 277 | Self.FLeftMarginGlyph := SrcBtn.FLeftMarginGlyph; 278 | Self.FLeftMarginText := SrcBtn.FLeftMarginText; 279 | Self.FTextAlignment := SrcBtn.FTextAlignment; 280 | 281 | Self.AlignWithMargins := SrcBtn.AlignWithMargins; 282 | Self.Margins.Left := SrcBtn.Margins.Left; 283 | Self.Margins.Right := SrcBtn.Margins.Right; 284 | Self.Margins.Top := SrcBtn.Margins.Top; 285 | Self.Margins.Bottom := SrcBtn.Margins.Bottom; 286 | 287 | Self.Font.Assign(SrcBtn.Font); 288 | Self.EndUpdate(); 289 | 290 | end; 291 | 292 | procedure TPTZGlyphButton.BeginUpdate; 293 | Begin 294 | Inc(FUpdateLock); 295 | End; 296 | 297 | procedure TPTZGlyphButton.EndUpdate; 298 | Begin 299 | Dec(FUpdateLock); 300 | 301 | if FUpdateLock <= 0 then 302 | begin 303 | FUpdateLock := 0; 304 | Self.Invalidate; 305 | Self.Refresh; 306 | end; 307 | End; 308 | 309 | 310 | procedure TPTZGlyphButton.OnTimer(Sender: TObject); 311 | Var 312 | Runtime : Integer; 313 | begin 314 | 315 | if FTimerLock then EXIT; 316 | FTimerLock := True; 317 | 318 | Try 319 | 320 | Runtime := GetTickCount64() - FTimerStart; 321 | 322 | if FDirection = 1 then 323 | begin 324 | if FFadeStep < FFadeInSteps then 325 | begin 326 | FFadeStep := FFadeStep + 1; 327 | if (Runtime > TIMER_TIMEOUT) or (Runtime > FFadeInSteps*FFadeInStepDelay) then FFadeStep := FFadeInSteps; 328 | Invalidate; 329 | end 330 | else 331 | begin 332 | FTimer.Free; 333 | FTimer := nil; 334 | end; 335 | end 336 | else if FDirection = 2 then 337 | begin 338 | if FFadeStep < FClickSteps then 339 | begin 340 | FFadeStep := FFadeStep + 1; 341 | if (Runtime > TIMER_TIMEOUT) or (Runtime > FClickSteps*FClickStepDelay) then FFadeStep := FClickSteps; 342 | Invalidate; 343 | end 344 | else 345 | begin 346 | FTimer.Free; 347 | FTimer := nil; 348 | end; 349 | end 350 | else if FDirection = -1 then 351 | begin 352 | if FFadeStep < FFadeOutSteps then 353 | begin 354 | FFadeStep := FFadeStep + 1; 355 | if (Runtime > TIMER_TIMEOUT) or (Runtime > FFadeOutSteps*FFadeOutStepDelay) then FFadeStep := FFadeOutSteps; 356 | Invalidate; 357 | end 358 | else 359 | begin 360 | FTimer.Free; 361 | FTimer := nil; 362 | end; 363 | end 364 | else if FDirection = -2 then 365 | begin 366 | if FFadeStep < FClickSteps then 367 | begin 368 | FFadeStep := FFadeStep + 1; 369 | if (Runtime > TIMER_TIMEOUT) or (Runtime > FClickSteps*FClickStepDelay) then FFadeStep := FClickSteps; 370 | Invalidate; 371 | end 372 | else 373 | begin 374 | FTimer.Free; 375 | FTimer := nil; 376 | end; 377 | end; 378 | Finally 379 | FTimerLock := False; 380 | End; 381 | 382 | end; 383 | 384 | procedure TPTZGlyphButton.SetColor(NewColor: TColor); 385 | begin 386 | if NewColor <> FColor then 387 | begin 388 | FColor := NewColor; 389 | If Self.FUpdateLock = 0 then Self.Invalidate; 390 | end; 391 | end; 392 | 393 | procedure TPTZGlyphButton.SetBorderColor(NewColor: TColor); 394 | begin 395 | if NewColor <> FBorderColor then 396 | begin 397 | FBorderColor := NewColor; 398 | If Self.FUpdateLock = 0 then Self.Invalidate; 399 | end; 400 | end; 401 | 402 | procedure TPTZGlyphButton.SetFocusBorderColor(NewColor: TColor); 403 | begin 404 | if NewColor <> FFocusBorderColor then 405 | begin 406 | FFocusBorderColor := NewColor; 407 | If Self.FUpdateLock = 0 then Self.Invalidate; 408 | end; 409 | end; 410 | 411 | procedure TPTZGlyphButton.SetFocusColor(NewColor: TColor); 412 | begin 413 | if NewColor <> FFocusColor then 414 | begin 415 | FFocusColor := NewColor; 416 | If Self.FUpdateLock = 0 then Self.Invalidate; 417 | end; 418 | end; 419 | 420 | procedure TPTZGlyphButton.SetClickBorderColor(NewColor: TColor); 421 | begin 422 | if NewColor <> FClickBorderColor then 423 | begin 424 | FClickBorderColor := NewColor; 425 | If Self.FUpdateLock = 0 then Self.Invalidate; 426 | end; 427 | end; 428 | 429 | procedure TPTZGlyphButton.SetClickColor(NewColor: TColor); 430 | begin 431 | if NewColor <> FClickColor then 432 | begin 433 | FClickColor := NewColor; 434 | If Self.FUpdateLock = 0 then Self.Invalidate; 435 | end; 436 | end; 437 | 438 | procedure TPTZGlyphButton.SetBackgroundColor(NewColor: TColor); 439 | begin 440 | if NewColor <> FBackgroundColor then 441 | begin 442 | FBackgroundColor := NewColor; 443 | If Self.FUpdateLock = 0 then Self.Invalidate; 444 | end; 445 | end; 446 | 447 | Procedure TPTZGlyphButton.SetDefaultButton(NewValue : Boolean); 448 | Begin 449 | if NewValue <> FDefaultButton then 450 | begin 451 | FDefaultButton := NewValue; 452 | If Self.FUpdateLock = 0 then Self.Invalidate; 453 | end; 454 | End; 455 | 456 | procedure TPTZGlyphButton.SetBorderWidth(NewWidth: Integer); 457 | begin 458 | if NewWidth <> FBorderWidth then 459 | begin 460 | FBorderWidth := NewWidth; 461 | If Self.FUpdateLock = 0 then Self.Invalidate; 462 | end; 463 | end; 464 | 465 | procedure TPTZGlyphButton.SetBorderCornerRadius(NewValue: Integer); 466 | begin 467 | if NewValue <> FBorderCornerRadius then 468 | begin 469 | FBorderCornerRadius := NewValue; 470 | If Self.FUpdateLock = 0 then Self.Invalidate; 471 | end; 472 | end; 473 | 474 | procedure TPTZGlyphButton.SetDefaultButtonBorderWidth(NewWidth: Integer); 475 | begin 476 | if NewWidth <> FBorderWidthDef then 477 | begin 478 | FBorderWidthDef := NewWidth; 479 | If Self.FUpdateLock = 0 then Self.Invalidate; 480 | end; 481 | end; 482 | 483 | 484 | procedure TPTZGlyphButton.SetLeftMarginGlyph(NewValue: Integer); 485 | begin 486 | if NewValue <> FLeftMarginGlyph then 487 | begin 488 | FLeftMarginGlyph := NewValue; 489 | If Self.FUpdateLock = 0 then Self.Invalidate; 490 | end; 491 | end; 492 | 493 | procedure TPTZGlyphButton.SetLeftMarginText(NewValue: Integer); 494 | begin 495 | if NewValue <> FLeftMarginText then 496 | begin 497 | FLeftMarginText := NewValue; 498 | If Self.FUpdateLock = 0 then Self.Invalidate; 499 | end; 500 | end; 501 | 502 | procedure TPTZGlyphButton.SetTopMarginGlyph(NewValue: Integer); 503 | begin 504 | if NewValue <> FTopMarginGlyph then 505 | begin 506 | FTopMarginGlyph := NewValue; 507 | If Self.FUpdateLock = 0 then Self.Invalidate; 508 | end; 509 | end; 510 | 511 | procedure TPTZGlyphButton.SetImageCollection(NewValue: TImageCollection); 512 | begin 513 | FImageCollection := NewValue; 514 | If Self.FUpdateLock = 0 then Self.Invalidate; 515 | end; 516 | 517 | 518 | 519 | procedure TPTZGlyphButton.SetGlyphForcedSize(NewValue: Integer); 520 | begin 521 | FGlyphForcedSize := NewValue; 522 | If Self.FUpdateLock = 0 then Self.Invalidate; 523 | end; 524 | 525 | 526 | procedure TPTZGlyphButton.SetGlyphName(NewValue: string); 527 | begin 528 | FGlyphName := NewValue; 529 | If Self.FUpdateLock = 0 then Self.Invalidate; 530 | end; 531 | 532 | function TPTZGlyphButton.GetContentWidth() : Integer; 533 | begin 534 | if (Self = nil) then EXIT(0); 535 | 536 | Result := FContentWidth; 537 | 538 | If Result <= 0 then 539 | begin 540 | Result := Length(Self.Caption) * 2 + (FLeftMarginGlyph + FGlyphSize + FLeftMarginText); 541 | end; 542 | 543 | End; 544 | 545 | procedure TPTZGlyphButton.UpdateWidth(ExtraMargin : Integer = 0); 546 | Var 547 | iVal : Integer; 548 | begin 549 | if (FContentWidth <= 0) and (Self.Constraints.MinWidth <= 0) then EXIT; 550 | 551 | iVal := Round(GetContentWidth() * 1.1); 552 | if Self.DefaultButton then iVal := Round(iVal * 1.2); 553 | iVal := iVal + ExtraMargin; 554 | 555 | if Self.BorderWidth > 1 then iVal := iVal + Self.BorderWidth * 3; 556 | 557 | if iVal < Self.Constraints.MinWidth then iVal := Self.Constraints.MinWidth; 558 | if (Self.Constraints.MaxWidth > 1) and (iVal > Self.Constraints.MaxWidth) then iVal := Self.Constraints.MaxWidth; 559 | 560 | if (iVal > 0) and (Abs(Self.Width - iVal) > 5) then 561 | begin 562 | Self.Width := iVal; 563 | end; 564 | 565 | End; 566 | 567 | 568 | procedure TPTZGlyphButton.Paint; 569 | var 570 | BufferBitmap: Vcl.Graphics.TBitmap; 571 | ForeColor: TColor; 572 | BorderColor: TColor; 573 | EntireRect: TRect; 574 | TextX: Integer; 575 | TextY: Integer; 576 | BitmapSize: Integer; 577 | MaxGlyphWidth : Integer; 578 | MaxGlyphHeight : Integer; 579 | x, y, k, Index: Integer; 580 | iTextHeight : Integer; 581 | iTextWidth : Integer; 582 | iBorderWidth : Integer; 583 | CurDelta : Integer; 584 | BestDelta : Integer; 585 | BestSubIdx : Integer; 586 | begin 587 | 588 | if FUpdateLock > 0 then 589 | begin 590 | Inherited; 591 | EXIT; 592 | end; 593 | 594 | 595 | BufferBitmap := Vcl.Graphics.TBitmap.Create(); 596 | BufferBitmap.Width := Width; 597 | BufferBitmap.Height := Height; 598 | 599 | ForeColor := FColor; // anti hint 600 | BorderColor := FBorderColor; 601 | TextY := 0; 602 | 603 | if FDirection = 1 then 604 | begin 605 | ForeColor := CalculateFadeinColor(FColor, FFocusColor, FFadeStep, FFadeInSteps); 606 | BorderColor := CalculateFadeinColor(FBorderColor, FFocusBorderColor, FFadeStep, FFadeInSteps); 607 | end 608 | else if FDirection = 2 then 609 | begin 610 | ForeColor := CalculateFadeinColor(FFocusColor, FClickColor, FFadeStep, FClickSteps); 611 | BorderColor := CalculateFadeinColor(FFocusBorderColor, FClickBorderColor, FFadeStep, FClickSteps); 612 | end 613 | else if FDirection = -1 then 614 | begin 615 | ForeColor := CalculateFadeinColor(FFocusColor, FColor, FFadeStep, FFadeOutSteps); 616 | BorderColor := CalculateFadeinColor(FFocusBorderColor, FBorderColor, FFadeStep, FFadeOutSteps); 617 | end 618 | else if FDirection = -2 then 619 | begin 620 | ForeColor := CalculateFadeinColor(FClickColor, FFocusColor, FFadeStep, FClickSteps); 621 | BorderColor := CalculateFadeinColor(FClickBorderColor, FFocusBorderColor, FFadeStep, FClickSteps); 622 | end 623 | else if FDirection = -10 then 624 | begin 625 | ForeColor := CalculateFadeinColor(FColor, FClickColor, FFadeStep, FClickSteps); 626 | BorderColor := CalculateFadeinColor(FBorderColor, FClickBorderColor, FFadeStep, FClickSteps); 627 | end; 628 | 629 | EntireRect.Left := 0; 630 | EntireRect.Top := 0; 631 | EntireRect.Width := Width; 632 | EntireRect.Height := Height; 633 | 634 | if FDefaultButton then iBorderWidth := FBorderWidthDef else iBorderWidth := FBorderWidth; 635 | 636 | if iBorderWidth > 0 then BufferBitmap.Canvas.Brush.Color := BorderColor 637 | else BufferBitmap.Canvas.Brush.Color := ForeColor; 638 | 639 | BufferBitmap.Canvas.FillRect(EntireRect); 640 | 641 | if iBorderWidth > 0 then 642 | begin 643 | EntireRect.Left := iBorderWidth+1; 644 | EntireRect.Top := iBorderWidth+1; 645 | 646 | EntireRect.Width := Width - 2 * iBorderWidth -2; 647 | EntireRect.Height := Height - 2 * iBorderWidth -2; 648 | BufferBitmap.Canvas.Brush.Color := ForeColor; 649 | BufferBitmap.Canvas.FillRect(EntireRect); 650 | end; 651 | 652 | BitmapSize := 0; 653 | 654 | if (ImageCollection<>nil) and (FGlyphName<>'') then 655 | begin 656 | Index := ImageCollection.GetIndexByName(FGlyphName); 657 | if Index >= 0 then 658 | begin 659 | MaxGlyphWidth := ClientWidth - FLeftMarginGlyph; 660 | MaxGlyphHeight := ClientHeight - FTopMarginGlyph*2; 661 | BestDelta := MAXINT; 662 | BestSubIdx := 0; 663 | 664 | for k := 0 to ImageCollection.Images[Index].SourceImages.Count-1 do 665 | begin 666 | if (FGlyphForcedSize > 0) and 667 | (ImageCollection.Images[Index].SourceImages.Items[k].Image.Width = FGlyphForcedSize) and 668 | (ImageCollection.Images[Index].SourceImages.Items[k].Image.Height = FGlyphForcedSize) then 669 | begin 670 | BestSubIdx := k; 671 | Break; 672 | end; 673 | 674 | if (ImageCollection.Images[Index].SourceImages.Items[k].Image.Width <= MaxGlyphWidth) and 675 | (ImageCollection.Images[Index].SourceImages.Items[k].Image.Height <= MaxGlyphHeight) then 676 | begin 677 | CurDelta := Abs(ImageCollection.Images[Index].SourceImages.Items[k].Image.Width - MaxGlyphWidth) + 678 | Abs(ImageCollection.Images[Index].SourceImages.Items[k].Image.Height - MaxGlyphHeight); 679 | if (k = 0) or (CurDelta < BestDelta) then 680 | begin 681 | BestSubIdx := k; 682 | BestDelta := CurDelta; 683 | end; 684 | end; 685 | end; 686 | 687 | { 688 | while k < ImageCollection.Images[Index].SourceImages.Count do 689 | begin 690 | if (ImageCollection.Images[Index].SourceImages.Items[k].Image.Width >= DesiredWidth) and 691 | (ImageCollection.Images[Index].SourceImages.Items[k].Image.Height >= DesiredHeight) then 692 | begin 693 | Break; 694 | end; 695 | 696 | k := k + 1; 697 | end; 698 | } 699 | 700 | if (BestSubIdx >= 0) and (Index >= 0) and (Index <= ImageCollection.Count-1) and 701 | (BestSubIdx <= ImageCollection.Images[Index].SourceImages.Count-1) then 702 | begin 703 | y := (ClientHeight - ImageCollection.Images[Index].SourceImages.Items[BestSubIdx].Image.Height) div 2; 704 | 705 | if FGlyphCentered then x := (ClientWidth - ImageCollection.Images[Index].SourceImages.Items[BestSubIdx].Image.Width) div 2 else x := 0; 706 | x := x + FLeftMarginGlyph; 707 | 708 | BufferBitmap.Canvas.Draw(x, y, ImageCollection.Images[Index].SourceImages.Items[BestSubIdx].Image); 709 | BitmapSize := ImageCollection.Images[Index].SourceImages.Items[BestSubIdx].Image.Width; 710 | end; 711 | end; 712 | end; 713 | 714 | FGlyphSize := BitmapSize; 715 | 716 | If Caption <> '' then 717 | begin 718 | BufferBitmap.Canvas.Font.Assign(Font); 719 | 720 | iTextHeight := BufferBitmap.Canvas.TextHeight(Caption); 721 | iTextWidth := BufferBitmap.Canvas.TextWidth(Caption); 722 | 723 | TextY := (Height - iTextHeight) div 2 -1; 724 | 725 | if FTextAlignment = taLeftJustify then 726 | TextX := FLeftMarginGlyph + BitmapSize + FLeftMarginText 727 | else if FTextAlignment = taCenter then 728 | TextX := (FLeftMarginGlyph + BitmapSize) + (BufferBitmap.Width div 2 - iTextWidth div 2) 729 | else TextX := BufferBitmap.Width - (iTextWidth + FLeftMarginText); 730 | 731 | if TextX < 0 then TextX := 0; 732 | 733 | BufferBitmap.Canvas.TextOut(TextX, TextY, Caption); 734 | FContentWidth := iTextWidth + (FLeftMarginGlyph + BitmapSize + FLeftMarginText) + (iTextHeight div 2); 735 | 736 | End else FContentWidth := FLeftMarginGlyph * 2 + BitmapSize; 737 | 738 | Canvas.Draw(0, 0, BufferBitmap); 739 | 740 | BufferBitmap.Free; 741 | end; 742 | 743 | procedure TPTZGlyphButton.CMMouseEnter(var Message: TMessage); 744 | begin 745 | inherited; 746 | 747 | If (FFadeInSteps <= 0) or (FFocusColor = FColor) then EXIT; 748 | 749 | if FTimer <> nil then FTimer.Free; 750 | 751 | FMouseEntered := True; 752 | FTimerLock := False; 753 | FDirection := 1; 754 | FFadeStep := 0; 755 | 756 | FTimerStart := GetTickCount64(); 757 | FTimer := TTimer.Create(Self); 758 | FTimer.Interval := FFadeInStepDelay; 759 | FTimer.OnTimer := OnTimer; 760 | end; 761 | 762 | procedure TPTZGlyphButton.CMMouseLeave(var Message: TMessage); 763 | begin 764 | inherited; 765 | 766 | If (FFadeOutSteps <= 0) or (FFocusColor = FColor) then EXIT; 767 | if FMouseEntered = False then EXIT; 768 | FMouseEntered := False; 769 | 770 | if FTimer <> nil then FTimer.Free; 771 | 772 | if FMouseDown then 773 | begin 774 | FDirection := -10; 775 | FFadeStep := 0; 776 | end 777 | else 778 | begin 779 | FDirection := -1; 780 | FFadeStep := 0; 781 | end; 782 | 783 | FTimerStart := GetTickCount64(); 784 | FTimer := TTimer.Create(Self); 785 | FTimer.Interval := FFadeOutStepDelay; 786 | FTimer.OnTimer := OnTimer; 787 | FMouseDown := False; 788 | end; 789 | 790 | procedure TPTZGlyphButton.WMLButtonDown(var Message: TWMLButtonDown); 791 | begin 792 | inherited; 793 | 794 | FMouseDown := True; 795 | If (FClickSteps <= 0) or (FClickColor = FColor) then EXIT; 796 | FMouseEntered := True; 797 | 798 | if FTimer <> nil then FTimer.Free; 799 | FDirection := 2; 800 | FFadeStep := 0; 801 | 802 | FTimerStart := GetTickCount64(); 803 | FTimer := TTimer.Create(Self); 804 | FTimer.Interval := FClickSteps; 805 | FTimer.OnTimer := OnTimer; 806 | end; 807 | 808 | procedure TPTZGlyphButton.WMLButtonUp(var Message: TWMLButtonUp); 809 | begin 810 | inherited; 811 | 812 | FMouseDown := False; 813 | If (FClickSteps <= 0) or (FClickColor = FColor) then EXIT; 814 | 815 | if FTimer <> nil then FTimer.Free; 816 | FDirection := -2; 817 | FFadeStep := 0; 818 | 819 | FTimerStart := GetTickCount64(); 820 | FTimer := TTimer.Create(Self); 821 | FTimer.Interval := FClickSteps; 822 | FTimer.OnTimer := OnTimer; 823 | end; 824 | 825 | 826 | procedure Register; 827 | begin 828 | RegisterComponents('Macecraft', [TPTZGlyphButton]); 829 | end; 830 | 831 | 832 | 833 | 834 | 835 | end. 836 | -------------------------------------------------------------------------------- /PTZPanel.pas: -------------------------------------------------------------------------------- 1 | unit PTZPanel; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | interface 6 | 7 | 8 | uses 9 | madExcept, Windows, Messages, SysUtils, Classes, 10 | Graphics, Controls, Forms, Math, 11 | Vcl.Themes, 12 | GDIPAPI, GDIPOBJ, GDIPUTIL, 13 | ExtCtrls, StdCtrls; 14 | 15 | 16 | type 17 | TPTZPanel = class(TCustomPanel) 18 | private 19 | FCreated : Boolean; 20 | FColor : TColor; 21 | FBorderColor : TColor; 22 | FBorderWidth : Integer; 23 | FCornerRadius : Integer; 24 | FUpdateLock : Integer; 25 | 26 | FLastInitPaintState : String; 27 | FBackgroundColor : Cardinal; 28 | FPen : TGPPen; 29 | 30 | procedure Init_PaintHelpers(); 31 | 32 | procedure SetColor(NewColor : TColor); 33 | procedure SetBorderColor(NewBorderColor : TColor); 34 | procedure SetBorderWidth(NewBorderWidth : Integer); 35 | procedure SetCornerRadius(NewCornerRadius: Integer); 36 | procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; 37 | protected 38 | procedure Paint; override; 39 | public 40 | constructor Create(AOwner: TComponent); override; 41 | destructor Destroy; override; 42 | 43 | procedure EndUpdate(); 44 | procedure BeginUpdate(); 45 | published 46 | property Color : TColor read FColor write SetColor; 47 | property BorderColor : TColor read FBorderColor write SetBorderColor; 48 | property BorderWidth : Integer read FBorderWidth write SetBorderWidth; 49 | property CornerRadius : Integer read FCornerRadius write SetCornerRadius; 50 | 51 | property Align; 52 | property Visible; 53 | property OnClick; 54 | property OnDblClick; 55 | property OnMouseDown; 56 | property OnMouseMove; 57 | property OnMouseUp; 58 | property OnMouseEnter; 59 | property OnMouseLeave; 60 | property OnResize; 61 | 62 | property ParentColor; 63 | property ParentBackground; 64 | property PopupMenu; 65 | 66 | end; 67 | 68 | procedure Register; 69 | 70 | implementation 71 | 72 | 73 | procedure Register; 74 | begin 75 | RegisterComponents('Macecraft', [TPTZPanel]); 76 | end; 77 | 78 | constructor TPTZPanel.Create(AOwner: TComponent); 79 | begin 80 | FUpdateLock := 1; 81 | inherited Create(AOwner); 82 | 83 | Self.BevelInner := bvNone; 84 | Self.BevelOuter := bvNone; 85 | Self.BevelKind := bkNone; 86 | Self.BorderStyle := bsNone; 87 | Self.DoubleBuffered := True; 88 | Self.ParentBackground := False; 89 | Self.Color := clWhite; 90 | 91 | FPen := nil; 92 | FBorderColor := RGB(216, 226, 238); 93 | FBorderWidth := 1; 94 | FCornerRadius := 30; 95 | 96 | FCreated := True; 97 | FUpdateLock := 0; 98 | end; 99 | 100 | 101 | destructor TPTZPanel.Destroy; 102 | begin 103 | inherited; 104 | 105 | If FPen <> nil then FPen.Free; 106 | end; 107 | 108 | 109 | procedure TPTZPanel.SetColor(NewColor : TColor); 110 | begin 111 | if FColor <> NewColor then 112 | begin 113 | FColor := NewColor; 114 | If FUpdateLock = 0 then Invalidate; 115 | end; 116 | end; 117 | 118 | procedure TPTZPanel.SetBorderColor(NewBorderColor : TColor); 119 | begin 120 | if FBorderColor <> NewBorderColor then 121 | begin 122 | FBorderColor := NewBorderColor; 123 | If FUpdateLock = 0 then Invalidate; 124 | end; 125 | end; 126 | 127 | procedure TPTZPanel.SetBorderWidth(NewBorderWidth : Integer); 128 | begin 129 | if FBorderWidth <> NewBorderWidth then 130 | begin 131 | FBorderWidth := NewBorderWidth; 132 | If FUpdateLock = 0 then Invalidate; 133 | end; 134 | end; 135 | 136 | procedure TPTZPanel.SetCornerRadius(NewCornerRadius: Integer); 137 | begin 138 | if FCornerRadius <> NewCornerRadius then 139 | begin 140 | FCornerRadius := NewCornerRadius; 141 | If FUpdateLock = 0 then Invalidate; 142 | end; 143 | end; 144 | 145 | procedure TPTZPanel.WMEraseBkgnd(var Message: TWmEraseBkgnd); 146 | begin 147 | { Only erase background if we're not doublebuffering or painting to memory. } 148 | if not FDoubleBuffered or 149 | {$IF DEFINED(CLR)} 150 | (Message.OriginalMessage.WParam = Message.OriginalMessage.LParam) then 151 | {$ELSE} 152 | (TMessage(Message).WParam = WParam(TMessage(Message).LParam)) then 153 | {$ENDIF} 154 | begin 155 | if StyleServices.Enabled and Assigned(Parent) and (csParentBackground in ControlStyle) then 156 | begin 157 | if Parent.DoubleBuffered then 158 | PerformEraseBackground(Self, Message.DC) 159 | else 160 | StyleServices.DrawParentBackground(Handle, Message.DC, nil, False); 161 | end 162 | else 163 | FillRect(Message.DC, ClientRect, Brush.Handle); 164 | end; 165 | Message.Result := 1; 166 | end; 167 | 168 | 169 | procedure TPTZPanel.Init_PaintHelpers; 170 | Var 171 | CurState : String; 172 | begin 173 | 174 | if (FCreated = False) or (Self = nil) or (Application = nil) then EXIT; // just in case 175 | 176 | // We need to re-create the pens and brushes every time color data changes, hence the CurState checks: 177 | CurState := IntToStr(Self.Color) +':'+ IntToStr(FBorderColor) + ':' + IntToStr(FBorderWidth); 178 | 179 | if (FPen <> nil) and (CurState <> FLastInitPaintState) then 180 | begin 181 | FPen.Free; 182 | FPen := nil; 183 | end; 184 | 185 | if (FPen = nil) or (FLastInitPaintState = '') then 186 | begin 187 | FBackgroundColor := MakeColor( GetRValue(Self.Color), GetGValue(Self.Color), GetBValue(Self.Color) ); 188 | FPen := TGPPen.Create(MakeColor(GetRValue(FBorderColor),GetGValue(FBorderColor),GetBValue(FBorderColor)), FBorderWidth); 189 | 190 | FLastInitPaintState := CurState; 191 | End; 192 | 193 | End; 194 | 195 | procedure TPTZPanel.BeginUpdate(); 196 | begin 197 | Inc(FUpdateLock); 198 | End; 199 | 200 | procedure TPTZPanel.EndUpdate(); 201 | begin 202 | Dec(FUpdateLock); 203 | If FUpdateLock = 0 then Self.Invalidate; 204 | End; 205 | 206 | procedure TPTZPanel.Paint; 207 | var 208 | Graphics : TGPGraphics; 209 | path : TGPGraphicsPath; 210 | l, t, w, h, d : integer; 211 | begin 212 | 213 | If (FCreated = False) or (Self = nil) or (Application = nil) then EXIT; 214 | 215 | Inherited; 216 | 217 | if (Self.Canvas = nil) or (Self.Canvas.Handle < 10) or (Self.Handle < 10) or (Self.Canvas.HandleAllocated = False) then EXIT; 218 | 219 | Try 220 | If FUpdateLock > 0 then EXIT; 221 | Init_PaintHelpers(); 222 | Graphics := nil; 223 | Except 224 | Exit; 225 | End; 226 | 227 | Try 228 | Try 229 | Graphics := TGPGraphics.Create(Canvas.Handle); 230 | Graphics.SetSmoothingMode(SmoothingModeAntiAlias); 231 | Graphics.SetInterpolationMode(InterpolationModeHighQualityBicubic); 232 | Graphics.SetTextRenderingHint(TextRenderingHintAntiAliasGridFit); 233 | 234 | Graphics.Clear( FBackgroundColor ); 235 | Except 236 | EXIT; 237 | End; 238 | 239 | if FBorderWidth > 0 then 240 | begin 241 | If FCornerRadius > 1 then 242 | begin 243 | path := TGPGraphicsPath.Create; 244 | l := 0; //FBorderWidth; 245 | t := 0; //FBorderWidth; 246 | w := Self.ClientWidth - l*2 -1; 247 | h := Self.ClientHeight - t*2 -1; 248 | d := FCornerRadius div 2; 249 | 250 | // the lines beween the arcs are automatically added by the path 251 | path.AddArc(l, t, d, d, 180, 90); // topleft 252 | path.AddArc(l + w - d, t, d, d, 270, 90); // topright 253 | path.AddArc(l + w - d, t + h - d, d, d, 0, 90); // bottomright 254 | path.AddArc(l, t + h - d, d, d, 90, 90); // bottomleft 255 | path.CloseFigure(); 256 | 257 | Graphics.DrawPath(FPen, Path); 258 | Path.Free; 259 | End else 260 | begin 261 | Graphics.DrawRectangle(FPen, 0, 0, Self.Width-1, Self.Height-1); 262 | End; 263 | end; 264 | 265 | Finally 266 | If Graphics <> nil then Graphics.Free; 267 | End; 268 | 269 | End; 270 | 271 | 272 | end. 273 | -------------------------------------------------------------------------------- /PTZProgressBar.pas: -------------------------------------------------------------------------------- 1 | unit PTZProgressBar; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | interface 6 | 7 | uses 8 | madExcept, System.SysUtils, System.Classes, System.Contnrs, 9 | Vcl.Controls, Vcl.ExtCtrls, Vcl.Graphics, Winapi.Messages, 10 | Winapi.Windows, Winapi.GDIPAPI, Winapi.GDIPOBJ; 11 | 12 | type 13 | TPTZProgressBar = class(TCustomPanel) 14 | private 15 | FBackColor : TColor; 16 | FValue : Integer; 17 | FMinValue : Integer; 18 | FMaxValue : Integer; 19 | 20 | procedure SetBackColor(NewColor: TColor); 21 | protected 22 | procedure WMEraseBkGnd(var Message: TMessage); message WM_ERASEBKGND; 23 | procedure SetValue(NewValue: Integer); 24 | procedure Paint; override; 25 | public 26 | constructor Create(AOwner: TComponent); override; 27 | destructor Free; 28 | 29 | published 30 | property Value : Integer read FValue write SetValue; 31 | property MaxValue : Integer read FMaxValue write FMaxValue; 32 | property MinValue : Integer read FMinValue write FMinValue; 33 | 34 | property BackgroundColor: TColor read FBackColor write SetBackColor; 35 | 36 | property Align; 37 | end; 38 | 39 | procedure Register; 40 | 41 | implementation 42 | 43 | 44 | procedure Register; 45 | begin 46 | RegisterComponents('Macecraft', [TPTZProgressBar]); 47 | end; 48 | 49 | 50 | constructor TPTZProgressBar.Create(AOwner: TComponent); 51 | begin 52 | inherited; 53 | 54 | FBackColor := clBtnFace; 55 | FValue := 0; 56 | FMinValue := 0; 57 | FMaxValue := 100; 58 | end; 59 | 60 | destructor TPTZProgressBar.Free; 61 | begin 62 | end; 63 | 64 | procedure TPTZProgressBar.SetBackColor(NewColor: TColor); 65 | begin 66 | if FBackColor <> NewColor then 67 | begin 68 | FBackColor := NewColor; 69 | Invalidate; 70 | end; 71 | end; 72 | 73 | procedure TPTZProgressBar.WMEraseBkGnd(var Message: TMessage); 74 | begin 75 | Message.Result := 1; 76 | end; 77 | 78 | procedure TPTZProgressBar.SetValue(NewValue: Integer); 79 | begin 80 | if FValue <> NewValue then 81 | begin 82 | FValue := NewValue; 83 | if FValue < FMinValue then FValue := FMinValue; 84 | if FValue > FMaxValue then FValue := FMaxValue; 85 | Invalidate; 86 | end; 87 | end; 88 | 89 | procedure TPTZProgressBar.Paint; 90 | var 91 | BufferBitmap: TGPBitmap; 92 | BmpGraphics: TGPGraphics; 93 | CanvasGraphics: TGPGraphics; 94 | BackgroundBrush: TGPBrush; 95 | ProgressBrush1: TGPLinearGradientBrush; 96 | ProgressBrush2: TGPLinearGradientBrush; 97 | P1, P2, P3: TGPPointF; 98 | Color1, Color2, Color3: TGPColor; 99 | Half: Single; 100 | CurVal : Single; 101 | begin 102 | 103 | try 104 | BufferBitmap := TGPBitmap.Create(Width, Height, PixelFormat32bppARGB); 105 | CanvasGraphics := TGPGraphics.Create(Canvas.Handle); 106 | BmpGraphics := TGPGraphics.Create(BufferBitmap); 107 | 108 | BmpGraphics.SetPageUnit(UnitPixel); 109 | BackgroundBrush := TGPSolidBrush.Create(MakeColor(255, GetRValue(ColorToRGB(FBackColor)),GetGValue(ColorToRGB(FBackColor)),GetBValue(ColorToRGB(FBackColor)))); 110 | BmpGraphics.FillRectangle(BackgroundBrush, 0, 0, Width, Height); 111 | 112 | //BmpGraphics.SetSmoothingMode(SmoothingModeHighQuality); 113 | //BmpGraphics.SetInterpolationMode(InterpolationModeHighQualityBicubic); 114 | 115 | CurVal := FValue; 116 | 117 | { 118 | if FMaxValue > 0 then 119 | begin 120 | if FValue < FMaxValue then CurVal := Round(FValue / FMaxValue * 100) 121 | else CurVal := 100; 122 | End else CurVal := 0; 123 | } 124 | P1.X := 0; 125 | P1.Y := Height / 2; 126 | P2.X := Width * CurVal / 200.0 + 1; 127 | P2.Y := Height / 2; 128 | P3.X := Width * CurVal / 100.0 + 2; 129 | P3.Y := Height / 2; 130 | Color1 := MakeColor(255, 16,75,160); // MakeColor(255,0,0,180); 131 | Color2 := MakeColor(255,255,20,100); 132 | Color3 := MakeColor(255,255,200,0); 133 | 134 | Half := Width * FValue / 200.0; 135 | ProgressBrush1 := TGPLinearGradientBrush.Create(P1, P2, Color1, Color2); 136 | P2.X := Width * FValue / 200.0 - 1; 137 | ProgressBrush2 := TGPLinearGradientBrush.Create(P2, P3, Color2, Color3); 138 | 139 | BmpGraphics.FillRectangle(ProgressBrush1, 0.0, 0.0, Half, Height); 140 | BmpGraphics.FillRectangle(ProgressBrush2, Half, 0.0, Half, Height); 141 | 142 | CanvasGraphics.DrawImage(BufferBitmap, 0, 0, Width, Height); 143 | 144 | CanvasGraphics.Free; 145 | BmpGraphics.Free; 146 | ProgressBrush1.Free; 147 | ProgressBrush2.Free; 148 | BackgroundBrush.Free; 149 | 150 | BufferBitmap.Free; 151 | finally 152 | end; 153 | 154 | end; 155 | 156 | 157 | end. 158 | -------------------------------------------------------------------------------- /PTZStdCtrls.pas: -------------------------------------------------------------------------------- 1 | unit PTZStdCtrls; 2 | 3 | interface 4 | 5 | uses 6 | WinAPI.Windows, WinAPI.Messages, 7 | System.Types, System.Classes, 8 | Vcl.Controls, Vcl.StdCtrls, Vcl.Forms, 9 | Vcl.Themes; 10 | 11 | type 12 | TPTZAutoSize = (ptzNone, ptzWidth, ptzHeight, ptzBoth); 13 | TPTZAutoSizeSet = set of TPTZAutoSize; 14 | 15 | const 16 | PTZ_AUTOSIZE_DEFAULT = ptzBoth; 17 | 18 | type 19 | TPTZCheckBox = class(TCheckBox) 20 | private 21 | FPTZAutoSize: TPTZAutoSize; 22 | FAutoSizing: boolean; 23 | FSquareSize: integer; 24 | FMinHeight: integer; 25 | procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; 26 | procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; 27 | procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; 28 | protected 29 | procedure AdjustAutoSizeDo(AutoSizeSet: TPTZAutoSizeSet = [ptzWidth, ptzHeight, ptzBoth]); 30 | procedure SetPTZAutoSize(const AValue: TPTZAutoSize); virtual; 31 | function CanResize(var NewWidth, NewHeight: Integer): Boolean; override; 32 | public 33 | constructor Create(AOwner: TComponent); override; 34 | procedure AdjustAutoSize(); 35 | published 36 | property PTZAutoSize: TPTZAutoSize read FPTZAutoSize write SetPTZAutoSize default PTZ_AUTOSIZE_DEFAULT; 37 | property MinHeight : Integer read FMinHeight write FMinHeight default 0; 38 | property OnMouseUp; 39 | property OnKeyUp; 40 | end; 41 | 42 | TPTZRadioButton = class(TRadioButton) 43 | private 44 | FPTZAutoSize: TPTZAutoSize; 45 | FAutoSizing: boolean; 46 | FSquareSize: integer; 47 | FMinHeight: integer; 48 | procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; 49 | procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; 50 | procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND; 51 | protected 52 | procedure AdjustAutoSizeDo(AutoSizeSet: TPTZAutoSizeSet = [ptzWidth, ptzHeight, ptzBoth]); 53 | procedure SetPTZAutoSize(const AValue: TPTZAutoSize); virtual; 54 | function CanResize(var NewWidth, NewHeight: Integer): Boolean; override; 55 | public 56 | constructor Create(AOwner: TComponent); override; 57 | procedure AdjustAutoSize(); 58 | published 59 | property PTZAutoSize: TPTZAutoSize read FPTZAutoSize write SetPTZAutoSize default PTZ_AUTOSIZE_DEFAULT; 60 | property MinHeight : Integer read FMinHeight write FMinHeight default 0; 61 | property OnMouseUp; 62 | property OnKeyUp; 63 | end; 64 | 65 | procedure Register(); 66 | 67 | implementation 68 | 69 | uses 70 | System.Math, 71 | VCL.Dialogs, System.SysUtils; 72 | 73 | // COMMENTS ON IMPLEMENTATION: 74 | // 1. Functionality, common to both TPTZCheckBox and TPTZRadioButton, is collected in the helper class TPTZHelper. 75 | // 2. Resize events are controlled with overriding TControl.CanResize(). NB! TControl.CanAutoSize() is not appropriate 76 | // here, as it is connected to VCL's TControl.AutoSize property. 77 | 78 | {**************************************************************} 79 | {* TPTZHelper *} 80 | {**************************************************************} 81 | 82 | type 83 | TPTZHelper = class helper for TWinControl 84 | private 85 | function ptzCalcAutoSize(AnAutoSize: TPTZAutoSize; ASquareSize: integer): TSize; 86 | procedure ptzCorrectResizeRequest(AnAutoSize: TPTZAutoSize; var NewWidth, NewHeight: integer); 87 | procedure ptzSetBounds(AnAutoSize: TPTZAutoSize; ASquareSize: integer; AMinHeight: integer); 88 | end; 89 | 90 | { TPTZHelper } 91 | 92 | function TPTZHelper.ptzCalcAutoSize(AnAutoSize: TPTZAutoSize; ASquareSize: integer): TSize; 93 | var 94 | DC: HDC; 95 | TextMetric: TTextMetric; 96 | TextSize: TSize; 97 | Padding: integer; 98 | begin 99 | DC := CreateCompatibleDC(0); 100 | if DC = 0 then RaiseLastOSError(); 101 | try 102 | if SelectObject(DC, Font.Handle) = 0 then 103 | RaiseLastOSError(); 104 | if not GetTextMetrics(DC, TextMetric) or not GetTextExtentPoint32(DC, PChar(Caption), Length(Caption), TextSize) then 105 | RaiseLastOSError(); 106 | finally 107 | DeleteDC(DC); 108 | end; 109 | 110 | // OK, we have correct TextMetric and TextSize now 111 | 112 | Padding := TextMetric.tmAveCharWidth div 2; 113 | 114 | if AnAutoSize in [ptzWidth, ptzBoth] then 115 | result.cx := ASquareSize + TextSize.cx + Padding 116 | else 117 | result.cx := Width; 118 | 119 | if AnAutoSize in [ptzHeight, ptzBoth] then 120 | result.cy := Max(ASquareSize, TextSize.cy) 121 | else 122 | result.cy := Height; 123 | 124 | // Just in case 125 | result.cx := result.cx +2; 126 | result.cy := result.cy +2; 127 | 128 | end; 129 | 130 | procedure TPTZHelper.ptzCorrectResizeRequest(AnAutoSize: TPTZAutoSize; var NewWidth, NewHeight: integer); 131 | begin 132 | if AnAutoSize in [ptzWidth, ptzBoth] then 133 | NewWidth := Width; 134 | if AnAutoSize in [ptzHeight, ptzBoth] then 135 | NewHeight := Height; 136 | end; 137 | 138 | procedure TPTZHelper.ptzSetBounds(AnAutoSize: TPTZAutoSize; ASquareSize: integer; AMinHeight: integer); 139 | var 140 | h : Integer; 141 | begin 142 | with ptzCalcAutoSize(AnAutoSize, ASquareSize) do 143 | begin 144 | h := cy; 145 | if h < AMinHeight then h := AMinHeight; 146 | SetBounds(Left, Top, cx, h); 147 | end; 148 | end; 149 | 150 | {**************************************************************} 151 | {* TPTZCheckBox *} 152 | {**************************************************************} 153 | 154 | constructor TPTZCheckBox.Create(AOwner: TComponent); 155 | begin 156 | inherited; 157 | FSquareSize := Height; 158 | FPTZAutoSize := PTZ_AUTOSIZE_DEFAULT; 159 | try 160 | FAutoSizing := true; 161 | ptzSetBounds(FPTZAutoSize, FSquareSize, FMinHeight); 162 | finally 163 | FAutoSizing := false; 164 | end; 165 | end; 166 | 167 | procedure TPTZCheckBox.AdjustAutoSize(); 168 | begin 169 | AdjustAutoSizeDo(); 170 | end; 171 | 172 | procedure TPTZCheckBox.AdjustAutoSizeDo(AutoSizeSet: TPTZAutoSizeSet = [ptzWidth, ptzHeight, ptzBoth]); 173 | begin 174 | if PTZAutoSize in AutoSizeSet then 175 | try 176 | FAutoSizing := true; 177 | ptzSetBounds(PTZAutoSize, FSquareSize, FMinHeight); 178 | finally 179 | FAutoSizing := false; 180 | end; 181 | end; 182 | 183 | function TPTZCheckBox.CanResize(var NewWidth, NewHeight: Integer): Boolean; 184 | begin 185 | if not FAutoSizing then 186 | ptzCorrectResizeRequest(PTZAutoSize, NewWidth, NewHeight); 187 | result := inherited; 188 | result := result or (NewWidth <> Width) or (NewHeight <> Height); 189 | end; 190 | 191 | procedure TPTZCheckBox.CMFontChanged(var Message: TMessage); 192 | begin 193 | inherited; 194 | AdjustAutoSizeDo(); 195 | end; 196 | 197 | procedure TPTZCheckBox.CMTextChanged(var Message: TMessage); 198 | begin 199 | inherited; 200 | AdjustAutoSizeDo([ptzWidth, ptzBoth]); 201 | end; 202 | 203 | procedure TPTZCheckBox.WMEraseBkgnd(var Message: TWmEraseBkgnd); 204 | begin 205 | { Only erase background if we're not doublebuffering or painting to memory. } 206 | if not FDoubleBuffered or 207 | {$IF DEFINED(CLR)} 208 | (Message.OriginalMessage.WParam = Message.OriginalMessage.LParam) then 209 | {$ELSE} 210 | (TMessage(Message).WParam = WParam(TMessage(Message).LParam)) then 211 | {$ENDIF} 212 | begin 213 | if StyleServices.Enabled and Assigned(Parent) and (csParentBackground in ControlStyle) then 214 | begin 215 | if Parent.DoubleBuffered then 216 | PerformEraseBackground(Self, Message.DC) 217 | else 218 | StyleServices.DrawParentBackground(Handle, Message.DC, nil, False); 219 | end 220 | else 221 | FillRect(Message.DC, ClientRect, Brush.Handle); 222 | end; 223 | Message.Result := 1; 224 | end; 225 | 226 | procedure TPTZCheckBox.SetPTZAutoSize(const AValue: TPTZAutoSize); 227 | begin 228 | if FPTZAutoSize <> AValue then 229 | begin 230 | ptzSetBounds(AValue, FSquareSize, FMinHeight); 231 | FPTZAutoSize := AValue; 232 | end; 233 | end; 234 | 235 | 236 | {**************************************************************} 237 | {* TPTZRadioButton *} 238 | {**************************************************************} 239 | 240 | constructor TPTZRadioButton.Create(AOwner: TComponent); 241 | begin 242 | inherited; 243 | FSquareSize := Height; 244 | FPTZAutoSize := PTZ_AUTOSIZE_DEFAULT; 245 | try 246 | FAutoSizing := true; 247 | ptzSetBounds(FPTZAutoSize, FSquareSize, FMinHeight); 248 | finally 249 | FAutoSizing := false; 250 | end; 251 | end; 252 | 253 | procedure TPTZRadioButton.AdjustAutoSize(); 254 | begin 255 | AdjustAutoSizeDo(); 256 | end; 257 | 258 | procedure TPTZRadioButton.AdjustAutoSizeDo(AutoSizeSet: TPTZAutoSizeSet); 259 | begin 260 | if PTZAutoSize in AutoSizeSet then 261 | try 262 | FAutoSizing := true; 263 | ptzSetBounds(PTZAutoSize, FSquareSize, FMinHeight); 264 | finally 265 | FAutoSizing := false; 266 | end; 267 | end; 268 | 269 | function TPTZRadioButton.CanResize(var NewWidth, NewHeight: Integer): Boolean; 270 | begin 271 | if not FAutoSizing then 272 | ptzCorrectResizeRequest(PTZAutoSize, NewWidth, NewHeight); 273 | result := inherited; 274 | result := result or (NewWidth <> Width) or (NewHeight <> Height); 275 | end; 276 | 277 | procedure TPTZRadioButton.CMFontChanged(var Message: TMessage); 278 | begin 279 | inherited; 280 | AdjustAutoSizeDo(); 281 | end; 282 | 283 | procedure TPTZRadioButton.CMTextChanged(var Message: TMessage); 284 | begin 285 | inherited; 286 | AdjustAutoSizeDo([ptzWidth, ptzBoth]); 287 | end; 288 | 289 | procedure TPTZRadioButton.WMEraseBkgnd(var Message: TWmEraseBkgnd); 290 | begin 291 | { Only erase background if we're not doublebuffering or painting to memory. } 292 | if not FDoubleBuffered or 293 | {$IF DEFINED(CLR)} 294 | (Message.OriginalMessage.WParam = Message.OriginalMessage.LParam) then 295 | {$ELSE} 296 | (TMessage(Message).WParam = WParam(TMessage(Message).LParam)) then 297 | {$ENDIF} 298 | begin 299 | if StyleServices.Enabled and Assigned(Parent) and (csParentBackground in ControlStyle) then 300 | begin 301 | if Parent.DoubleBuffered then 302 | PerformEraseBackground(Self, Message.DC) 303 | else 304 | StyleServices.DrawParentBackground(Handle, Message.DC, nil, False); 305 | end 306 | else 307 | FillRect(Message.DC, ClientRect, Brush.Handle); 308 | end; 309 | Message.Result := 1; 310 | end; 311 | 312 | procedure TPTZRadioButton.SetPTZAutoSize(const AValue: TPTZAutoSize); 313 | begin 314 | if FPTZAutoSize <> AValue then 315 | begin 316 | ptzSetBounds(AValue, FSquareSize, FMinHeight); 317 | FPTZAutoSize := AValue; 318 | end; 319 | end; 320 | 321 | {**************************************************************} 322 | {* Components registration *} 323 | {**************************************************************} 324 | 325 | procedure Register(); 326 | begin 327 | RegisterComponents('Macecraft', [TPTZCheckBox, TPTZRadioButton]); 328 | end; 329 | 330 | end. 331 | -------------------------------------------------------------------------------- /PTZSymbolButton.pas: -------------------------------------------------------------------------------- 1 | unit PTZSymbolButton; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | interface 6 | 7 | {.$DEFINE Debug_ExplicitMadExceptUse} 8 | 9 | uses 10 | {$IFDEF Debug_ExplicitMadExceptUse} madExcept, {$ENDIF} 11 | System.SysUtils, System.Classes, Vcl.Controls, Vcl.StdCtrls, 12 | Vcl.ExtCtrls, Vcl.Graphics, Winapi.Messages, Winapi.Windows, Math; 13 | 14 | type 15 | TPTZSymbol = (ptzRestore, ptzMaximize, ptzMinimize, ptzClose); 16 | 17 | TPTZSymbolButton = class(TCustomControl) 18 | private 19 | FFadeStep: Integer; 20 | FDirection: Integer; 21 | FMouseDown: Boolean; 22 | FTimer: TTimer; 23 | FLastMouseEvent: UInt64; 24 | 25 | { Private declarations } 26 | FFadeInSteps: Integer; 27 | FFadeInStepDelay: Integer; 28 | FFadeOutSteps: Integer; 29 | FFadeOutStepDelay: Integer; 30 | FClickSteps: Integer; 31 | FClickStepDelay: Integer; 32 | FBorderWidth: Integer; 33 | FColor: TColor; 34 | FBorderColor: TColor; 35 | FFocusBorderColor: TColor; 36 | FFocusColor: TColor; 37 | FSymbolColor: TColor; 38 | FSymbolFocusColor: TColor; 39 | FClickBorderColor: TColor; 40 | FClickColor: TColor; 41 | FSymbol: TPTZSymbol; 42 | FSymbolSize: Integer; 43 | FCurrentColor: TColor; // the currently drawn background color 44 | 45 | procedure SetColor(NewColor: TColor); 46 | procedure SetFocusColor(NewColor: TColor); 47 | procedure SetBorderColor(NewColor: TColor); 48 | procedure SetFocusBorderColor(NewColor: TColor); 49 | procedure SetSymbolColor(NewColor: TColor); 50 | procedure SetFocusSymbolColor(NewColor: TColor); 51 | procedure SetClickBorderColor(NewColor: TColor); 52 | procedure SetClickColor(NewColor: TColor); 53 | procedure SetBorderWidth(NewWidth: Integer); 54 | procedure SetSymbol(NewSymbol: TPTZSymbol); 55 | procedure SetSymbolSize(NewSymbolSize: Integer); 56 | protected 57 | procedure OnTimer(Sender: TObject); 58 | { Protected declarations } 59 | procedure WMEraseBkGnd(var Message: TMessage); message WM_ERASEBKGND; 60 | procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; 61 | procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; 62 | procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; 63 | procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; 64 | procedure Paint; override; 65 | public 66 | { Public declarations } 67 | constructor Create(AOwner: TComponent); override; 68 | destructor Free; 69 | published 70 | { Published declarations } 71 | 72 | property Align; 73 | property OnClick; 74 | property Visible; 75 | property OnMouseMove; 76 | 77 | property FadeInSteps: Integer read FFadeInSteps write FFadeInSteps; 78 | property FadeInStepDelay: Integer read FFadeInStepDelay write FFadeInStepDelay; 79 | property FadeOutSteps: Integer read FFadeOutSteps write FFadeOutSteps; 80 | property FadeOutStepDelay: Integer read FFadeOutStepDelay write FFadeOutStepDelay; 81 | property ClickSteps: Integer read FClickSteps write FClickSteps; 82 | property ClickStepDelay: Integer read FClickStepDelay write FClickStepDelay; 83 | property BorderWidth: Integer read FBorderWidth write SetBorderWidth; 84 | property CurrentColor: TColor read FCurrentColor; 85 | 86 | property Color: TColor read FColor write SetColor; 87 | property FocusColor: TColor read FFocusColor write SetFocusColor; 88 | property BorderColor: TColor read FBorderColor write SetBorderColor; 89 | property FocusBorderColor: TColor read FFocusBorderColor write SetFocusBorderColor; 90 | property SymbolColor: TColor read FSymbolColor write SetSymbolColor; 91 | property SymbolFocusColor: TColor read FSymbolFocusColor write SetFocusSymbolColor; 92 | 93 | property ClickBorderColor: TColor read FClickBorderColor write SetClickBorderColor; 94 | property ClickColor: TColor read FClickColor write SetClickColor; 95 | property Symbol: TPTZSymbol read FSymbol write SetSymbol; 96 | property SymbolSize: Integer read FSymbolSize write SetSymbolSize; 97 | end; 98 | 99 | procedure Register; 100 | 101 | implementation 102 | 103 | 104 | // Allows drawing of fading in colors, for example from white to grays to black 105 | // Note: Indexing starts at zero! 106 | function CalculateFadeinColor(StartColor, EndColor : TColor; CurrentStep, FinalStep : Integer) : TColor; 107 | var 108 | Steps : Integer; 109 | Start_R : Byte; 110 | Start_G : Byte; 111 | Start_B : Byte; 112 | End_R : Byte; 113 | End_G : Byte; 114 | End_B : Byte; 115 | Final_R : Byte; 116 | Final_G : Byte; 117 | Final_B : Byte; 118 | begin 119 | if CurrentStep <= 0 then EXIT(StartColor); 120 | if CurrentStep >= FinalStep then EXIT(EndColor); 121 | If StartColor = EndColor then EXIT(EndColor); 122 | 123 | Start_R := (StartColor and $000000ff); 124 | Start_G := (StartColor and $0000ff00) shr 8; 125 | Start_B := (StartColor and $00ff0000) shr 16; 126 | End_R := (EndColor and $000000ff); 127 | End_G := (EndColor and $0000ff00) shr 8; 128 | End_B := (EndColor and $00ff0000) shr 16; 129 | Final_R := Start_R; 130 | Final_G := Start_G; 131 | Final_B := Start_B; 132 | Steps := FinalStep; 133 | if Start_R < End_R then Final_R := Final_R + Round(((End_R-Start_R) / Steps) * CurrentStep) 134 | else Final_R := Final_R - Round(((Start_R-End_R) / Steps) * CurrentStep); 135 | if Start_G < End_G then Final_G := Final_G + Round(((End_G-Start_G) / Steps) * CurrentStep) 136 | else Final_G := Final_G - Round(((Start_G-End_G) / Steps) * CurrentStep); 137 | if Start_B < End_B then Final_B := Final_B + Round(((End_B-Start_B) / Steps) * CurrentStep) 138 | else Final_B := Final_B - Round(((Start_B-End_B) / Steps) * CurrentStep); 139 | Result := RGB(Final_R, Final_G, Final_B); 140 | end; 141 | 142 | 143 | constructor TPTZSymbolButton.Create(AOwner: TComponent); 144 | begin 145 | inherited; 146 | FFadeInSteps := 10; 147 | FFadeInStepDelay := 25; 148 | FFadeOutSteps := 10; 149 | FFadeOutStepDelay := 25; 150 | FClickSteps := 10; 151 | FClickStepDelay := 25; 152 | 153 | FCurrentColor := Self.Color; 154 | FLastMouseEvent := 0; 155 | FDirection := 1; 156 | FFadeStep := 0; 157 | FTimer := nil; 158 | FMouseDown := False; 159 | FSymbolSize := 8; 160 | FSymbol := ptzClose; 161 | end; 162 | 163 | destructor TPTZSymbolButton.Free; 164 | begin 165 | if FTimer <> nil then 166 | begin 167 | FTimer.Free; 168 | end; 169 | end; 170 | 171 | procedure TPTZSymbolButton.WMEraseBkGnd(var Message: TMessage); 172 | begin 173 | Message.Result := 1; 174 | end; 175 | 176 | procedure TPTZSymbolButton.OnTimer(Sender: TObject); 177 | begin 178 | 179 | if FDirection = 1 then 180 | begin 181 | if FFadeStep < FFadeInSteps then 182 | begin 183 | FFadeStep := FFadeStep + 1; 184 | Invalidate; 185 | end 186 | else 187 | begin 188 | FTimer.Free; 189 | FTimer := nil; 190 | end; 191 | end 192 | else if FDirection = 2 then 193 | begin 194 | if FFadeStep < FClickSteps then 195 | begin 196 | FFadeStep := FFadeStep + 1; 197 | Invalidate; 198 | end 199 | else 200 | begin 201 | FTimer.Free; 202 | FTimer := nil; 203 | end; 204 | end 205 | else if FDirection = -1 then 206 | begin 207 | if FFadeStep < FFadeOutSteps then 208 | begin 209 | FFadeStep := FFadeStep + 1; 210 | Invalidate; 211 | end 212 | else 213 | begin 214 | FTimer.Free; 215 | FTimer := nil; 216 | end; 217 | end 218 | else if FDirection = -2 then 219 | begin 220 | if FFadeStep < FClickSteps then 221 | begin 222 | FFadeStep := FFadeStep + 1; 223 | Invalidate; 224 | end 225 | else 226 | begin 227 | FTimer.Free; 228 | FTimer := nil; 229 | end; 230 | end; 231 | 232 | end; 233 | 234 | procedure TPTZSymbolButton.SetColor(NewColor: TColor); 235 | begin 236 | if NewColor <> FColor then 237 | begin 238 | FColor := NewColor; 239 | end; 240 | end; 241 | 242 | procedure TPTZSymbolButton.SetBorderColor(NewColor: TColor); 243 | begin 244 | if NewColor <> FBorderColor then 245 | begin 246 | FBorderColor := NewColor; 247 | end; 248 | end; 249 | 250 | procedure TPTZSymbolButton.SetFocusBorderColor(NewColor: TColor); 251 | begin 252 | if NewColor <> FFocusBorderColor then 253 | begin 254 | FFocusBorderColor := NewColor; 255 | end; 256 | end; 257 | 258 | procedure TPTZSymbolButton.SetFocusColor(NewColor: TColor); 259 | begin 260 | if NewColor <> FFocusColor then 261 | begin 262 | FFocusColor := NewColor; 263 | end; 264 | end; 265 | 266 | procedure TPTZSymbolButton.SetClickBorderColor(NewColor: TColor); 267 | begin 268 | if NewColor <> FClickBorderColor then 269 | begin 270 | FClickBorderColor := NewColor; 271 | end; 272 | end; 273 | 274 | procedure TPTZSymbolButton.SetClickColor(NewColor: TColor); 275 | begin 276 | if NewColor <> FClickColor then 277 | begin 278 | FClickColor := NewColor; 279 | end; 280 | end; 281 | 282 | procedure TPTZSymbolButton.SetSymbolColor(NewColor: TColor); 283 | begin 284 | if NewColor <> FSymbolColor then 285 | begin 286 | FSymbolColor := NewColor; 287 | end; 288 | end; 289 | 290 | procedure TPTZSymbolButton.SetFocusSymbolColor(NewColor: TColor); 291 | begin 292 | if NewColor <> FSymbolFocusColor then 293 | begin 294 | FSymbolFocusColor := NewColor; 295 | end; 296 | end; 297 | 298 | procedure TPTZSymbolButton.SetBorderWidth(NewWidth: Integer); 299 | begin 300 | if NewWidth <> FBorderWidth then 301 | begin 302 | FBorderWidth := NewWidth; 303 | Invalidate; 304 | end; 305 | end; 306 | 307 | procedure TPTZSymbolButton.SetSymbol(NewSymbol: TPTZSymbol); 308 | begin 309 | if NewSymbol <> FSymbol then 310 | begin 311 | FSymbol := NewSymbol; 312 | Invalidate; 313 | end; 314 | end; 315 | 316 | procedure TPTZSymbolButton.SetSymbolSize(NewSymbolSize: Integer); 317 | begin 318 | if NewSymbolSize <> FSymbolSize then 319 | begin 320 | FSymbolSize := NewSymbolSize; 321 | Invalidate; 322 | end; 323 | end; 324 | 325 | procedure TPTZSymbolButton.Paint; 326 | var 327 | BufferBitmap: Vcl.Graphics.TBitmap; 328 | ForeColor: TColor; 329 | BorderColor: TColor; 330 | SymbolColor: TColor; 331 | EntireRect: TRect; 332 | Shift: Integer; 333 | begin 334 | 335 | BufferBitmap := Vcl.Graphics.TBitmap.Create(); 336 | BufferBitmap.Width := Width; 337 | BufferBitmap.Height := Height; 338 | 339 | ForeColor := FColor; // anti hint 340 | BorderColor := FBorderColor; 341 | SymbolColor := FSymbolColor; 342 | 343 | // hack fix: 344 | If (FDirection <> 1) and ((FLastMouseEvent < 10) or (GetTickCount64() - FLastMouseEvent > 1000)) then FDirection := 0; 345 | 346 | if FDirection = 1 then 347 | begin 348 | ForeColor := CalculateFadeinColor(FColor, FFocusColor, FFadeStep, FFadeInSteps); 349 | BorderColor := CalculateFadeinColor(FBorderColor, FFocusBorderColor, FFadeStep, FFadeInSteps); 350 | SymbolColor := CalculateFadeinColor(FSymbolColor, FSymbolFocusColor, FFadeStep, FFadeInSteps); 351 | end 352 | else if FDirection = 2 then 353 | begin 354 | ForeColor := CalculateFadeinColor(FFocusColor, FClickColor, FFadeStep, FClickSteps); 355 | BorderColor := CalculateFadeinColor(FFocusBorderColor, FClickBorderColor, FFadeStep, FClickSteps); 356 | SymbolColor := FSymbolFocusColor; 357 | end 358 | else if FDirection = -1 then 359 | begin 360 | ForeColor := CalculateFadeinColor(FFocusColor, FColor, FFadeStep, FFadeOutSteps); 361 | BorderColor := CalculateFadeinColor(FFocusBorderColor, FBorderColor, FFadeStep, FFadeOutSteps); 362 | SymbolColor := CalculateFadeinColor(FSymbolFocusColor, FSymbolColor, FFadeStep, FFadeOutSteps); 363 | end 364 | else if FDirection = -2 then 365 | begin 366 | ForeColor := CalculateFadeinColor(FClickColor, FFocusColor, FFadeStep, FClickSteps); 367 | BorderColor := CalculateFadeinColor(FClickBorderColor, FFocusBorderColor, FFadeStep, FClickSteps); 368 | SymbolColor := FSymbolFocusColor; 369 | end 370 | else if FDirection = -10 then 371 | begin 372 | ForeColor := CalculateFadeinColor(FColor, FClickColor, FFadeStep, FClickSteps); 373 | BorderColor := CalculateFadeinColor(FBorderColor, FClickBorderColor, FFadeStep, FClickSteps); 374 | SymbolColor := CalculateFadeinColor(FSymbolFocusColor, FSymbolColor, FFadeStep, FClickSteps); 375 | end; 376 | 377 | FCurrentColor := ForeColor; 378 | EntireRect.Left := 0; 379 | EntireRect.Top := 0; 380 | EntireRect.Width := Width; 381 | EntireRect.Height := Height; 382 | BufferBitmap.Canvas.Brush.Color := BorderColor; 383 | BufferBitmap.Canvas.FillRect(EntireRect); 384 | 385 | EntireRect.Left := BorderWidth; 386 | EntireRect.Top := BorderWidth; 387 | EntireRect.Width := Width - 2 * BorderWidth; 388 | EntireRect.Height := Height - 2 * BorderWidth; 389 | BufferBitmap.Canvas.Brush.Color := ForeColor; 390 | BufferBitmap.Canvas.FillRect(EntireRect); 391 | BufferBitmap.Canvas.Pen.Color := SymbolColor; 392 | 393 | EntireRect.Left := (Width - FSymbolSize) div 2; 394 | EntireRect.Top := (Height - FSymbolSize) div 2; 395 | EntireRect.Width := FSymbolSize; 396 | EntireRect.Height := FSymbolSize; 397 | 398 | if FSymbol = ptzClose then 399 | begin 400 | BufferBitmap.Canvas.MoveTo(EntireRect.Left, EntireRect.Top); 401 | BufferBitmap.Canvas.LineTo(EntireRect.Right + 1, EntireRect.Bottom + 1); 402 | BufferBitmap.Canvas.MoveTo(EntireRect.Left, EntireRect.Bottom); 403 | BufferBitmap.Canvas.LineTo(EntireRect.Right + 1, EntireRect.Top - 1); 404 | end 405 | else if FSymbol = ptzMinimize then 406 | begin 407 | BufferBitmap.Canvas.MoveTo(EntireRect.Left, EntireRect.Bottom); 408 | BufferBitmap.Canvas.LineTo(EntireRect.Right + 1, EntireRect.Bottom); 409 | end 410 | else if FSymbol = ptzMaximize then 411 | begin 412 | BufferBitmap.Canvas.MoveTo(EntireRect.Left, EntireRect.Bottom); 413 | BufferBitmap.Canvas.LineTo(EntireRect.Right + 1, EntireRect.Bottom); 414 | BufferBitmap.Canvas.LineTo(EntireRect.Right + 1, EntireRect.Top); 415 | BufferBitmap.Canvas.LineTo(EntireRect.Left, EntireRect.Top); 416 | BufferBitmap.Canvas.LineTo(EntireRect.Left, EntireRect.Bottom); 417 | end 418 | else if FSymbol = ptzRestore then 419 | begin 420 | Shift := Max(2, FSymbolSize div 8); 421 | 422 | BufferBitmap.Canvas.MoveTo(EntireRect.Left, EntireRect.Bottom); 423 | BufferBitmap.Canvas.LineTo(EntireRect.Right - Shift + 1, EntireRect.Bottom); 424 | BufferBitmap.Canvas.LineTo(EntireRect.Right - Shift + 1, EntireRect.Top + Shift); 425 | BufferBitmap.Canvas.LineTo(EntireRect.Left, EntireRect.Top + Shift); 426 | BufferBitmap.Canvas.LineTo(EntireRect.Left, EntireRect.Bottom); 427 | 428 | BufferBitmap.Canvas.MoveTo(EntireRect.Left + Shift, EntireRect.Top + Shift); 429 | BufferBitmap.Canvas.LineTo(EntireRect.Left + Shift, EntireRect.Top); 430 | BufferBitmap.Canvas.LineTo(EntireRect.Right + 1, EntireRect.Top); 431 | BufferBitmap.Canvas.LineTo(EntireRect.Right + 1, EntireRect.Bottom - Shift); 432 | BufferBitmap.Canvas.LineTo(EntireRect.Right - Shift + 1, EntireRect.Bottom - Shift); 433 | end; 434 | 435 | Canvas.Draw(0, 0, BufferBitmap); 436 | 437 | BufferBitmap.Free; 438 | 439 | end; 440 | 441 | procedure TPTZSymbolButton.CMMouseEnter(var Message: TMessage); 442 | begin 443 | inherited; 444 | 445 | if FTimer <> nil then 446 | begin 447 | FTimer.Free; 448 | end; 449 | 450 | FLastMouseEvent := GetTickCount64(); 451 | FDirection := 1; 452 | FFadeStep := 0; 453 | FTimer := TTimer.Create(Self); 454 | FTimer.Interval := FFadeInStepDelay; 455 | FTimer.OnTimer := OnTimer; 456 | end; 457 | 458 | procedure TPTZSymbolButton.CMMouseLeave(var Message: TMessage); 459 | begin 460 | inherited; 461 | 462 | if FTimer <> nil then 463 | begin 464 | FTimer.Free; 465 | end; 466 | 467 | if FMouseDown then 468 | FDirection := -10 469 | else 470 | FDirection := -1; 471 | 472 | FFadeStep := 0; 473 | 474 | FTimer := TTimer.Create(Self); 475 | FTimer.Interval := FFadeOutStepDelay; 476 | FTimer.OnTimer := OnTimer; 477 | FMouseDown := False; 478 | end; 479 | 480 | procedure TPTZSymbolButton.WMLButtonDown(var Message: TWMLButtonDown); 481 | begin 482 | inherited; 483 | 484 | FMouseDown := True; 485 | if FTimer <> nil then 486 | begin 487 | FTimer.Free; 488 | end; 489 | 490 | FLastMouseEvent := GetTickCount64(); 491 | FDirection := 2; 492 | FFadeStep := 0; 493 | 494 | FTimer := TTimer.Create(Self); 495 | FTimer.Interval := FClickSteps; 496 | FTimer.OnTimer := OnTimer; 497 | end; 498 | 499 | procedure TPTZSymbolButton.WMLButtonUp(var Message: TWMLButtonUp); 500 | begin 501 | inherited; 502 | 503 | FMouseDown := False; 504 | if FTimer <> nil then 505 | begin 506 | FTimer.Free; 507 | end; 508 | 509 | FLastMouseEvent := GetTickCount64(); 510 | FDirection := -2; 511 | FFadeStep := 0; 512 | 513 | FTimer := TTimer.Create(Self); 514 | FTimer.Interval := FClickSteps; 515 | FTimer.OnTimer := OnTimer; 516 | end; 517 | 518 | procedure Register; 519 | begin 520 | RegisterComponents('Macecraft', [TPTZSymbolButton]); 521 | end; 522 | 523 | end. 524 | -------------------------------------------------------------------------------- /PTZWinControlButton.pas: -------------------------------------------------------------------------------- 1 | unit PTZWinControlButton; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | interface 6 | 7 | uses 8 | System.Classes, System.UITypes, Winapi.Messages, Vcl.Controls, Vcl.Graphics, 9 | Vcl.ExtCtrls, GDIPAPI, GDIPOBJ; 10 | 11 | const 12 | CFadeSteps = 4; 13 | 14 | type 15 | TPTZWinControlButtonType = (btMinimize, btMaximize, btRestore, btClose); 16 | 17 | TPTZWinControlButton = class(TGraphicControl) 18 | private 19 | fIdlePaintColor: TColor; 20 | fHighlightedPaintColor: TColor; 21 | fActualDrawColor: TColor; 22 | fButtonType: TPTZWinControlButtonType; 23 | 24 | fBackgroundBrush: TGPBrush; 25 | fIsMouseInShape: Boolean; 26 | 27 | fFadePhase: Integer; 28 | fFadeTimer: TTimer; 29 | fFadeStep: Byte; 30 | 31 | fShapeSize: Integer; 32 | fShapeMarginTop: Integer; 33 | fShapeMarginLeft: Integer; 34 | 35 | procedure SetHighlightedPaintColor(const Value: TColor); 36 | procedure SetIdlePaintColor(const Value: TColor); 37 | procedure SetButtonType(const Value: TPTZWinControlButtonType); 38 | procedure SetShapeSize(const Value: Integer); 39 | procedure SetShapeMarginLeft(const Value: Integer); 40 | procedure SetShapeMarginTop(const Value: Integer); 41 | protected 42 | procedure Paint; override; 43 | procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED; 44 | procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; 45 | procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; 46 | 47 | procedure DoOnFadeTimer(Sender: TObject); 48 | public 49 | constructor Create(aOwner: TComponent); override; 50 | destructor Destroy; override; 51 | published 52 | property Color; 53 | property ShapeSize: Integer read fShapeSize write SetShapeSize default 14; 54 | property ShapeMarginLeft: Integer read fShapeMarginLeft write SetShapeMarginLeft default -1; 55 | property ShapeMarginTop: Integer read fShapeMarginTop write SetShapeMarginTop default -1; 56 | property SymbolColor: TColor read fIdlePaintColor write SetIdlePaintColor default $A8A8A8; 57 | property SymbolFocusColor: TColor read fHighlightedPaintColor write SetHighlightedPaintColor default clWhite; 58 | property ButtonType: TPTZWinControlButtonType read fButtonType write SetButtonType; 59 | property OnClick; 60 | end; 61 | 62 | Procedure Register; 63 | 64 | 65 | implementation 66 | 67 | uses 68 | System.SysUtils, System.Math, Winapi.Windows; 69 | 70 | { TPTZWinControlButton } 71 | 72 | procedure TPTZWinControlButton.CMColorChanged(var Message: TMessage); 73 | begin 74 | FreeAndNil(fBackgroundBrush); 75 | end; 76 | 77 | procedure TPTZWinControlButton.CMMouseEnter(var Message: TMessage); 78 | begin 79 | inherited; 80 | fFadeTimer.Enabled := True; 81 | fIsMouseInShape := True; 82 | end; 83 | 84 | procedure TPTZWinControlButton.CMMouseLeave(var Message: TMessage); 85 | begin 86 | inherited; 87 | fFadeTimer.Enabled := True; 88 | fIsMouseInShape := False; 89 | end; 90 | 91 | constructor TPTZWinControlButton.Create(aOwner: TComponent); 92 | begin 93 | inherited; 94 | fShapeSize := 14; 95 | fShapeMarginTop := -1; 96 | fShapeMarginLeft := -1; 97 | fFadePhase := 0; 98 | fFadeStep := 0; 99 | fIsMouseInShape := False; 100 | 101 | fIdlePaintColor := $A8A8A8; 102 | fActualDrawColor := fIdlePaintColor; 103 | fHighlightedPaintColor := clWhite; 104 | Color := clDkGray; 105 | 106 | fBackgroundBrush := nil; 107 | 108 | fFadeTimer := TTimer.Create(nil); 109 | fFadeTimer.Interval := 60; 110 | fFadeTimer.Enabled := False; 111 | fFadeTimer.OnTimer := DoOnFadeTimer; 112 | 113 | Width := 20; 114 | Height := 20; 115 | end; 116 | 117 | destructor TPTZWinControlButton.Destroy; 118 | begin 119 | FreeAndNil(fBackgroundBrush); 120 | inherited; 121 | end; 122 | 123 | procedure TPTZWinControlButton.DoOnFadeTimer(Sender: TObject); 124 | begin 125 | if fFadeStep = 0 then 126 | begin 127 | fFadeStep := Max(Max( 128 | GetRValue(fHighlightedPaintColor) - GetRValue(fIdlePaintColor), 129 | GetGValue(fHighlightedPaintColor) - GetGValue(fIdlePaintColor)), 130 | GetBValue(fHighlightedPaintColor) - GetBValue(fIdlePaintColor) 131 | ) div CFadeSteps; 132 | end; 133 | 134 | if fIsMouseInShape then 135 | begin 136 | Inc(fFadePhase); 137 | if fFadePhase >= CFadeSteps - 1 then 138 | begin 139 | fActualDrawColor := fHighlightedPaintColor; 140 | fFadeTimer.Enabled := False; 141 | end 142 | else 143 | begin 144 | fActualDrawColor := MakeColor( 145 | Min( GetRValue(fIdlePaintColor) + fFadePhase * fFadeStep, 255), 146 | Min( GetGValue(fIdlePaintColor) + fFadePhase * fFadeStep, 255), 147 | Min( GetBValue(fIdlePaintColor) + fFadePhase * fFadeStep, 255) 148 | ); 149 | end; 150 | end 151 | else 152 | begin 153 | Dec(fFadePhase); 154 | if fFadePhase <= 0 then 155 | begin 156 | fActualDrawColor := fIdlePaintColor; 157 | fFadeTimer.Enabled := False; 158 | end 159 | else 160 | begin 161 | fActualDrawColor := MakeColor( 162 | Min( GetRValue(fIdlePaintColor) + fFadePhase * fFadeStep, 255), 163 | Min( GetGValue(fIdlePaintColor) + fFadePhase * fFadeStep, 255), 164 | Min( GetBValue(fIdlePaintColor) + fFadePhase * fFadeStep, 255) 165 | ); 166 | end; 167 | end; 168 | Invalidate; 169 | end; 170 | 171 | procedure TPTZWinControlButton.SetButtonType(const Value: TPTZWinControlButtonType); 172 | begin 173 | if fButtonType <> Value then 174 | begin 175 | fButtonType := Value; 176 | Invalidate; 177 | end; 178 | end; 179 | 180 | procedure TPTZWinControlButton.SetHighlightedPaintColor(const Value: TColor); 181 | begin 182 | if fHighlightedPaintColor <> Value then 183 | begin 184 | fHighlightedPaintColor := Value; 185 | fFadeStep := 0; 186 | Invalidate; 187 | end; 188 | end; 189 | 190 | procedure TPTZWinControlButton.SetIdlePaintColor(const Value: TColor); 191 | begin 192 | if fIdlePaintColor <> Value then 193 | begin 194 | fIdlePaintColor := Value; 195 | fActualDrawColor := Value; 196 | fFadeStep := 0; 197 | Invalidate; 198 | end; 199 | end; 200 | 201 | procedure TPTZWinControlButton.SetShapeMarginLeft(const Value: Integer); 202 | begin 203 | if fShapeMarginTop <> Value then 204 | begin 205 | fShapeMarginTop := Value; 206 | Invalidate; 207 | end; 208 | end; 209 | 210 | procedure TPTZWinControlButton.SetShapeMarginTop(const Value: Integer); 211 | begin 212 | if fShapeMarginTop <> Value then 213 | begin 214 | fShapeMarginTop := Value; 215 | Invalidate; 216 | end; 217 | end; 218 | 219 | procedure TPTZWinControlButton.SetShapeSize(const Value: Integer); 220 | begin 221 | if fShapeSize <> Value then 222 | begin 223 | fShapeSize := Value; 224 | Invalidate; 225 | end; 226 | end; 227 | 228 | procedure TPTZWinControlButton.Paint; 229 | var 230 | canvasGraphics : TGPGraphics; 231 | bufferBitmap : TGPBitmap; 232 | bmpGraphics : TGPGraphics; 233 | bufferBitmapBg : TGPBitmap; 234 | bmpGraphicsBg : TGPGraphics; 235 | pen : TGPPen; 236 | drawSize : Integer; 237 | leftMargin : Integer; 238 | topMargin : Integer; 239 | y : Single; 240 | penSize : Single; 241 | points : TPointFDynArray; 242 | 243 | procedure SetSquarePoints(aOffset, aSize, aCornerSize: Single); 244 | begin 245 | points[0].X := aOffset; 246 | points[0].Y := aOffset + aCornerSize; 247 | points[1].X := aOffset + aCornerSize; 248 | points[1].Y := aOffset; 249 | points[2].X := aOffset + aSize - aCornerSize; 250 | points[2].Y := aOffset; 251 | points[3].X := aOffset + aSize; 252 | points[3].Y := aOffset + aCornerSize; 253 | points[4].X := aOffset + aSize; 254 | points[4].Y := aOffset + aSize - aCornerSize; 255 | points[5].X := aOffset + aSize - aCornerSize; 256 | points[5].Y := aOffset + aSize; 257 | points[6].X := aOffset + aCornerSize; 258 | points[6].Y := aOffset + aSize; 259 | points[7].X := aOffset; 260 | points[7].Y := aOffset + aSize - aCornerSize; 261 | end; 262 | begin 263 | inherited; 264 | 265 | if ShapeSize <= 1 then 266 | Exit; 267 | 268 | drawSize := ShapeSize * 3; 269 | penSize := 1.6 * drawSize / 12; 270 | // if fButtonType in [btMinimize, btClose] then 271 | // penSize := penSize * 1.5; 272 | 273 | if fBackgroundBrush = nil then 274 | begin 275 | fBackgroundBrush := TGPSolidBrush.Create(MakeColor(GetRValue(Color),GetGValue(Color),GetBValue(Color))); 276 | end; 277 | 278 | Canvas.Lock; 279 | try 280 | pen := TGPPen.Create(MakeColor(GetRValue(fActualDrawColor),GetGValue(fActualDrawColor),GetBValue(fActualDrawColor)), penSize); 281 | canvasGraphics := TGPGraphics.Create(Canvas.Handle); 282 | 283 | bufferBitmapBg := TGPBitmap.Create(Width, Height, PixelFormat32bppARGB); 284 | bmpGraphicsBg := TGPGraphics.Create(BufferBitmapBg); 285 | bmpGraphicsBg.FillRectangle(FBackgroundBrush, 0, 0, Width, Height); 286 | 287 | bufferBitmap := TGPBitmap.Create(DrawSize, DrawSize, PixelFormat32bppARGB); 288 | bmpGraphics := TGPGraphics.Create(BufferBitmap); 289 | bmpGraphics.FillRectangle(FBackgroundBrush, 0, 0, DrawSize, DrawSize); 290 | 291 | bmpGraphics.SetSmoothingMode(SmoothingModeHighQuality); 292 | bmpGraphics.SetInterpolationMode(InterpolationModeHighQualityBicubic); 293 | 294 | { if fIsMouseInShape then 295 | pen := fHightlightedPen 296 | else 297 | pen := fIdlePen; } 298 | 299 | if fButtonType = btMinimize then 300 | begin 301 | y := DrawSize / 2 - 1; 302 | bmpGraphics.DrawLine(pen, 0, y, drawSize, y); 303 | end 304 | else 305 | if fButtonType = btMaximize then 306 | begin 307 | SetLength(points, 8); 308 | SetSquarePoints(penSize / 2 + 1, drawSize - penSize - 2, penSize * 1.0); 309 | bmpGraphics.DrawPolygon(pen, PGPPointF(@points[0]), 8); 310 | end 311 | else 312 | if fButtonType = btRestore then 313 | begin 314 | SetLength(points, 8); 315 | SetSquarePoints(penSize / 2 + 0.75, drawSize - penSize * 3, penSize * 0.65); 316 | bmpGraphics.DrawPolygon(pen, PGPPointF(@points[0]), 8); 317 | SetSquarePoints(penSize / 2 + 0.75 + 1.75 * pensize, drawSize - penSize * 3, penSize * 0.75); 318 | bmpGraphics.DrawPolygon(pen, PGPPointF(@points[0]), 8); 319 | end 320 | else 321 | if fButtonType = btClose then 322 | begin 323 | bmpGraphics.DrawLine(pen, penSize * 0.5, penSize * 0.5, DrawSize - penSize * 0.5, DrawSize - penSize * 0.5); 324 | bmpGraphics.DrawLine(pen, DrawSize - penSize * 0.5, penSize * 0.5, penSize * 0.5, DrawSize - penSize * 0.5); 325 | end; 326 | 327 | leftMargin := ShapeMarginLeft; 328 | if leftMargin < 0 then 329 | begin 330 | leftMargin := (Width - ShapeSize) div 2; 331 | if leftMargin < 0 then 332 | leftMargin := 0; 333 | end; 334 | 335 | topMargin := ShapeMarginTop; 336 | if topMargin < 0 then 337 | begin 338 | topMargin := (Height - ShapeSize) div 2; 339 | if topMargin < 0 then 340 | topMargin := 0; 341 | end; 342 | 343 | canvasGraphics.DrawImage(bufferBitmapBg, 0, 0, Width, Height); 344 | canvasGraphics.DrawImage(bufferBitmap, leftMargin, topMargin, ShapeSize, ShapeSize); 345 | 346 | bmpGraphicsBg.Free; 347 | bufferBitmapBg.Free; 348 | bmpGraphics.Free; 349 | bufferBitmap.Free; 350 | 351 | canvasGraphics.Free; 352 | 353 | pen.Free; 354 | finally 355 | Canvas.Unlock; 356 | end; 357 | end; 358 | 359 | 360 | procedure Register; 361 | begin 362 | RegisterComponents('Macecraft', [TPTZWinControlButton]); 363 | end; 364 | 365 | 366 | end. 367 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # UpdateFixer 2 | 3 | Update Fixer is a lightweight app to fix Windows Update not working. 4 | Update Fixer version 1.2 5 | By Jouni Flemming (Macecraft Software) 6 | Copyright 2023 Jouni Flemming 7 | 8 | Official website: https://winupdatefixer.com/ 9 | Source code license: GNU General Public License v3 10 | https://www.gnu.org/licenses/gpl-3.0.en.html 11 | 12 | Official Github: https://github.com/jv16x/UpdateFixer/ 13 | 14 | 15 | You can contact me: jouni@winupdatefixer.com or jouni.flemming@macecraft.com 16 | If you do, please include “Update Fixer” in the subject line. 17 | 18 | 19 | Disclaimer: 20 | This source code is provided “as is” without any guarantees of any kind 21 | with the exception that we guarantee the Update Fixer application does not 22 | include any malware or other such hidden malicious functionality. 23 | 24 | 25 | This project uses MadExcept exception handler by http://madshi.net/ 26 | Simply remove the MadExcept references if you wish to compile without it. 27 | 28 | 29 | This project also uses a few custom UI components, namely: 30 | PTZPanel, PTZStdCtrls, PTZSymbolButton, PTZWinControlButton, ColorPanel, 31 | GUIPanel, GUIPanelHVList, PTZGlyphButton, PTZProgressBar. 32 | 33 | You can remove these and replace the controls with standard VCL controls if you wish. 34 | 35 | 36 | The program has two main steps in its operation 37 | 38 | 1) In the Analysis step - implemented mostly via the Analyze_xxx functions - 39 | we attempt to detect common problems in the system that can cause Windows Update to fail. 40 | One such common problem is that the System Services relating to Windows Update are disabled. 41 | 42 | 2) In the processing step - implemented mostly via the Process_xxx functions - 43 | we process, i.e. fix the found issues. 44 | Notice that the process step only does changes as authorized by the user by selecting 45 | from the UI which fixing operations should be performed. 46 | It is possible that the user does not select all the found issues to be fixed, 47 | or that the user chooses to fix all the issues, even in those that were not actually detected. 48 | In such case, user input is interpreted to mean to change the settings of the specific item to its defaults. 49 | 50 | 51 | The fixing process uses three techniques: in-exe commands, mainly Windows API calls, 52 | running of batch files and running of PowerShell files. 53 | 54 | Doing this in these three ways was noted in testing to be the most robust way of performing the fixes. 55 | 56 | In other words, in some testing systems, simply attempting to do a fix by executing Windows API 57 | calls within the exe file alone did not work, but attempting to do the same fix by using a 58 | batch file or a PowerShell script file did, or vice versa. 59 | A more elegant way of performing all the fixes would naturally to implement everything without 60 | the need to use any batch or PowerShell script files, but I didn't have the time to do so. 61 | My main goal was to make this work (i.e. be able to fix Windows Update even when the official 62 | Windows Update Troubleshooter couldn't), not to make it work and work in the most elegant way possible 63 | 64 | Anyone reviewing this code is free to let me know of fixes and improvements how all this 65 | can be done without the use of Batch/PowerShell script files. 66 | 67 | 68 | ** Change Log ** 69 | 70 | Changes since version 1.1 71 | 72 | 1) The app window can now be resized in its results show view. 73 | 2) Improved the Debug_GenerateDebugLog directive support and debug log content. 74 | 3) Split Process_Init_Pas() into two functions and fixed many bugs there. 75 | 4) Removed Debug_ExceptionMessages directive. Debug_GenerateDebugLog is better anyway. 76 | 5) Removed DEBUG_WRITE_LOG, because Debug_GenerateDebugLog is better anyway. 77 | 78 | 79 | Changes since version 1.0 80 | 81 | 1) Removed the use of encrypted strings in order to improve code readability. They were used to 82 | prevent VirusTotal false positives. I'm going to ass-u-me that since the program is now open source, 83 | it will no longer be flagged with such false positive detections. 84 | 2) Replaced all of the hard-coded 'c:\windows\' references with %WINDIR%. While this makes very little difference 85 | for any actual use case, it's still a better way to do it. 86 | 3) Other minor code cleanup and maintenance, and added some more comments to document the code. 87 | -------------------------------------------------------------------------------- /UpdateFixer.dpr: -------------------------------------------------------------------------------- 1 | program UpdateFixer; 2 | 3 | uses 4 | madExcept, 5 | madLinkDisAsm, 6 | madListHardware, 7 | madListProcesses, 8 | madListModules, 9 | Vcl.Forms, 10 | MainFormUnit in 'MainFormUnit.pas' {MainForm}, 11 | PTZPanel in '..\jv16 PowerTools\_DEV\Components\CustomXE\PTZPanel.pas', 12 | PTZStdCtrls in '..\jv16 PowerTools\_DEV\Components\CustomXE\PTZStdCtrls.pas', 13 | PTZSymbolButton in '..\jv16 PowerTools\_DEV\Components\CustomXE\PTZSymbolButton.pas', 14 | PTZWinControlButton in '..\jv16 PowerTools\_DEV\Components\CustomXE\PTZWinControlButton.pas', 15 | ColorPanel in '..\FindAll\ColorPanel.pas', 16 | GUIPanel in '..\jv16 PowerTools\_DEV\Components\PT UI Panels\GUIPanel.pas', 17 | GUIPanelHVList in '..\jv16 PowerTools\_DEV\Components\PT UI Panels\GUIPanelHVList.pas', 18 | PTZGlyphButton in '..\jv16 PowerTools\_DEV\Components\CustomXE\PTZGlyphButton.pas', 19 | uMiniStringTools in '..\System Examiner\uMiniStringTools.pas', 20 | FastStringCaseUtils in 'C:\Code\PT CommonCode\FastStringCaseUtils.pas', 21 | PTZProgressBar in '..\jv16 PowerTools\_DEV\Components\CustomXE\PTZProgressBar.pas', 22 | InternetUtils in '..\jv16 PowerTools\_DEV\_AutoUpdate\InternetUtils.pas', 23 | Win64bitDetector in 'C:\Code\PT CommonCode\Win64bitDetector.pas', 24 | Vcl.Themes, 25 | Vcl.Styles; 26 | 27 | {$R *.res} 28 | 29 | begin 30 | Application.Initialize; 31 | Application.MainFormOnTaskbar := True; 32 | Application.CreateForm(TMainForm, MainForm); 33 | Application.Run; 34 | end. 35 | -------------------------------------------------------------------------------- /UpdateFixer.dproj: -------------------------------------------------------------------------------- 1 | program UpdateFixer; 2 | 3 | uses 4 | madExcept, 5 | madLinkDisAsm, 6 | madListHardware, 7 | madListProcesses, 8 | madListModules, 9 | Vcl.Forms, 10 | MainFormUnit in 'MainFormUnit.pas' {MainForm}, 11 | PTZPanel in 'PTZPanel.pas', 12 | PTZStdCtrls in 'PTZStdCtrls.pas', 13 | PTZSymbolButton in 'PTZSymbolButton.pas', 14 | PTZWinControlButton in 'PTZWinControlButton.pas', 15 | ColorPanel in 'ColorPanel.pas', 16 | GUIPanel in 'GUIPanel.pas', 17 | GUIPanelHVList in 'GUIPanelHVList.pas', 18 | PTZGlyphButton in 'PTZGlyphButton.pas', 19 | uMiniStringTools in 'uMiniStringTools.pas', 20 | FastStringCaseUtils in 'FastStringCaseUtils.pas', 21 | PTZProgressBar in 'PTZProgressBar.pas', 22 | InternetUtils in 'InternetUtils.pas', 23 | Win64bitDetector in 'Win64bitDetector.pas', 24 | Vcl.Themes, 25 | Vcl.Styles; 26 | 27 | {$R *.res} 28 | 29 | begin 30 | Application.Initialize; 31 | Application.MainFormOnTaskbar := True; 32 | Application.CreateForm(TMainForm, MainForm); 33 | Application.Run; 34 | end. -------------------------------------------------------------------------------- /Win64bitDetector.pas: -------------------------------------------------------------------------------- 1 | unit Win64bitDetector; 2 | 3 | {$R-,T-,X+,H+,B-,O+,Q-} 4 | 5 | interface 6 | 7 | Uses 8 | madExcept, Windows, Messages; 9 | 10 | 11 | type 12 | TWow64DisableWow64FsRedirection = function ( var Wow64FsEnableRedirection: LongBool): LongBool; StdCall; 13 | TWow64RevertWow64FsRedirection = function ( var Wow64FsEnableRedirection: LongBool): LongBool; StdCall; 14 | 15 | 16 | Procedure Detect64bitWindows(); 17 | function Is64bitWindows() : Boolean; 18 | 19 | Procedure Wow64_DisableRedirection(); 20 | Procedure Wow64_RestoreRedirection(); 21 | 22 | Var 23 | GLOBAL_Wow64FsEnableRedirection : LongBool; 24 | GLOBAL_Wow64RedirectionDisabled : Boolean = False; 25 | GLOBAL_Wow64RevertWow64FsRedirection : TWow64RevertWow64FsRedirection = nil; 26 | GLOBAL_Wow64DisableWow64FsRedirection : TWow64DisableWow64FsRedirection = nil; 27 | GLOBAL_is64bitWindows : Integer = -1; //0 = No, 1 = Yes, -1 = Not checked yet 28 | 29 | implementation 30 | 31 | 32 | Procedure Detect64bitWindows(); 33 | var 34 | hHandle : THandle; 35 | Begin 36 | 37 | Try 38 | GLOBAL_is64bitWindows := -1; 39 | GLOBAL_Wow64DisableWow64FsRedirection := nil; 40 | GLOBAL_Wow64RevertWow64FsRedirection := nil; 41 | 42 | If Is64bitWindows() then 43 | begin 44 | hHandle := GetModuleHandle('kernel32.dll'); 45 | @GLOBAL_Wow64RevertWow64FsRedirection := GetProcAddress(hHandle, PAnsiChar(AnsiString('Wow64RevertWow64FsRedirection'))); 46 | @GLOBAL_Wow64DisableWow64FsRedirection := GetProcAddress(hHandle, PAnsiChar(AnsiString('Wow64DisableWow64FsRedirection'))); 47 | End; 48 | Except 49 | Exit; 50 | End; 51 | 52 | 53 | End; 54 | 55 | Procedure Wow64_DisableRedirection(); 56 | Begin 57 | 58 | Try 59 | If Is64bitWindows() and 60 | Assigned(GLOBAL_Wow64RevertWow64FsRedirection) and 61 | Assigned(GLOBAL_Wow64DisableWow64FsRedirection) then 62 | begin 63 | GLOBAL_Wow64DisableWow64FsRedirection(GLOBAL_Wow64FsEnableRedirection); 64 | GLOBAL_Wow64RedirectionDisabled := True; 65 | End; 66 | Except 67 | Exit; 68 | End; 69 | 70 | End; 71 | 72 | Procedure Wow64_RestoreRedirection(); 73 | Begin 74 | 75 | if GLOBAL_Wow64RedirectionDisabled = False then Exit; 76 | 77 | Try 78 | If Is64bitWindows() and 79 | Assigned(GLOBAL_Wow64RevertWow64FsRedirection) and 80 | Assigned(GLOBAL_Wow64DisableWow64FsRedirection) then 81 | begin 82 | GLOBAL_Wow64RevertWow64FsRedirection(GLOBAL_Wow64FsEnableRedirection); 83 | GLOBAL_Wow64RedirectionDisabled := False; 84 | End; 85 | Except 86 | Exit; 87 | End; 88 | 89 | End; 90 | 91 | function Is64bitWindows() : Boolean; 92 | type 93 | TIsWow64Process = function( // Type of IsWow64Process API fn 94 | Handle: THandle; 95 | var Res: BOOL 96 | ): BOOL; stdcall; 97 | var 98 | IsWow64Result: BOOL; // result from IsWow64Process 99 | IsWow64Process: TIsWow64Process; // IsWow64Process fn reference 100 | begin 101 | 102 | 103 | if GLOBAL_is64bitWindows = 1 then 104 | begin 105 | Result := True; 106 | Exit; 107 | end Else 108 | Begin 109 | if GLOBAL_is64bitWindows = 0 then 110 | begin 111 | Result := False; 112 | Exit; 113 | end; 114 | End; 115 | 116 | Try 117 | // Try to load required function from kernel32 118 | IsWow64Process := GetProcAddress(GetModuleHandle('kernel32'), PAnsiChar(AnsiString('IsWow64Process')) ); 119 | 120 | if Assigned(IsWow64Process) then 121 | begin 122 | // Function is implemented: call it 123 | if not IsWow64Process(GetCurrentProcess, IsWow64Result) then 124 | begin 125 | Result := False; //internal error 126 | Exit; 127 | End; 128 | 129 | // Return result of function 130 | Result := IsWow64Result; 131 | end 132 | else 133 | // Function not implemented: can't be running on Wow64 134 | Result := False; 135 | Except 136 | Result := False; 137 | End; 138 | 139 | if Result then GLOBAL_is64bitWindows := 1 140 | else GLOBAL_is64bitWindows := 0; 141 | 142 | end; 143 | 144 | initialization 145 | 146 | GLOBAL_is64bitWindows := -1; 147 | 148 | 149 | end. 150 | --------------------------------------------------------------------------------