PocketMine-MP  1.4 - API 1.10.0
 All Classes Namespaces Functions Variables Pages
CommandReader.php
1 <?php
2 
3 /*
4  *
5  * ____ _ _ __ __ _ __ __ ____
6  * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7  * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8  * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9  * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10  *
11  * This program is free software: you can redistribute it and/or modify
12  * it under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation, either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * @author PocketMine Team
17  * @link http://www.pocketmine.net/
18  *
19  *
20 */
21 
22 namespace pocketmine\command;
23 
25 
26 class CommandReader extends Thread{
27  private $readline;
28 
30  protected $buffer;
31 
35  public function __construct(\Threaded $threaded){
36  $this->buffer = $threaded;
37  $this->start();
38  }
39 
40  private function readLine(){
41  if(!$this->readline){
42  $line = trim(fgets(fopen("php://stdin", "r")));
43  }else{
44  $line = trim(readline("> "));
45  if($line != ""){
46  readline_add_history($line);
47  }
48  }
49 
50  return $line;
51  }
52 
58  public function getLine(){
59  if($this->buffer->count() !== 0){
60  return $this->buffer->synchronized(function (){
61  return $this->buffer->shift();
62  });
63  }
64 
65  return null;
66  }
67 
68  public function run(){
69  $opts = getopt("", ["disable-readline"]);
70  if(extension_loaded("readline") and !isset($opts["disable-readline"])){
71  $this->readline = true;
72  }else{
73  $this->readline = false;
74  }
75 
76  $lastLine = microtime(true);
77  while(true){
78  if(($line = $this->readLine()) !== ""){
79  $this->buffer->synchronized(function (\Threaded $buffer, $line){
80  $buffer[] = preg_replace("#\\x1b\\x5b([^\\x1b]*\\x7e|[\\x40-\\x50])#", "", $line);
81  }, $this->buffer, $line );
82  }elseif((microtime(true) - $lastLine) <= 0.1){ //Non blocking! Sleep to save CPU
83  usleep(40000);
84  }
85 
86  $lastLine = microtime(true);
87  }
88  }
89 }
__construct(\Threaded $threaded)