|
1 | 1 | <?php
|
| 2 | + |
2 | 3 | namespace PhpGui\Widget;
|
3 | 4 |
|
4 |
| -class Checkbutton extends AbstractWidget { |
5 |
| - protected function create(): void { |
| 5 | +use PhpGui\ProcessTCL; |
| 6 | + |
| 7 | +class Checkbutton extends AbstractWidget |
| 8 | +{ |
| 9 | + private $callback; |
| 10 | + private $variable; |
| 11 | + |
| 12 | + public function __construct(string $parentId, array $options = []) |
| 13 | + { |
| 14 | + parent::__construct($parentId, $options); |
| 15 | + $this->callback = $options['command'] ?? null; |
| 16 | + $this->variable = "cb_var_" . $this->id; |
| 17 | + $this->create(); |
| 18 | + } |
| 19 | + |
| 20 | + protected function create(): void |
| 21 | + { |
6 | 22 | $text = $this->options['text'] ?? 'Checkbutton';
|
7 |
| - $this->tcl->evalTcl("checkbutton .{$this->parentId}.{$this->id} -text \"{$text}\""); |
| 23 | + $extra = $this->getOptionString(); |
| 24 | + |
| 25 | + // Initialize variable and register callback if provided |
| 26 | + $this->tcl->evalTcl("set {$this->variable} 0"); |
| 27 | + |
| 28 | + if ($this->callback) { |
| 29 | + ProcessTCL::getInstance()->registerCallback($this->id, $this->callback); |
| 30 | + $this->tcl->evalTcl("checkbutton .{$this->parentId}.{$this->id} -text \"{$text}\" -variable {$this->variable} -command {php::executeCallback {$this->id}} {$extra}"); |
| 31 | + } else { |
| 32 | + $this->tcl->evalTcl("checkbutton .{$this->parentId}.{$this->id} -text \"{$text}\" -variable {$this->variable} {$extra}"); |
| 33 | + } |
8 | 34 | }
|
9 |
| - |
10 |
| - public function setChecked(bool $state): void { |
| 35 | + |
| 36 | + public function setChecked(bool $state): void |
| 37 | + { |
11 | 38 | $value = $state ? 1 : 0;
|
12 |
| - $this->tcl->evalTcl("set {$this->id} $value"); |
| 39 | + $this->tcl->evalTcl("set {$this->variable} $value"); |
| 40 | + } |
| 41 | + |
| 42 | + public function isChecked(): bool |
| 43 | + { |
| 44 | + return (bool)$this->tcl->evalTcl("set {$this->variable}"); |
13 | 45 | }
|
14 |
| - |
15 |
| - public function isChecked(): bool { |
16 |
| - $this->tcl->evalTcl("set _val [set {$this->id}]"); |
17 |
| - return (bool)$this->tcl->getResult(); |
| 46 | + |
| 47 | + public function toggle(): void |
| 48 | + { |
| 49 | + $this->setChecked(!$this->isChecked()); |
| 50 | + } |
| 51 | + |
| 52 | + protected function getOptionString(): string |
| 53 | + { |
| 54 | + $opts = ""; |
| 55 | + foreach ($this->options as $key => $value) { |
| 56 | + if (in_array($key, ['text', 'command'])) continue; |
| 57 | + $opts .= " -$key \"$value\""; |
| 58 | + } |
| 59 | + return $opts; |
18 | 60 | }
|
19 | 61 | }
|
0 commit comments