code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php return array ( 'id' => 'orange_spv_c500_ver1_subopver4125_subua', 'fallback' => 'orange_spv_c500_ver1_subopver4125', 'capabilities' => array ( 'max_data_rate' => '40', ), );
cuckata23/wurfl-data
data/orange_spv_c500_ver1_subopver4125_subua.php
PHP
mit
195
<?php namespace TodoMove\Intercessor; use TodoMove\Intercessor\Traits\Metable; class Folder { use \TodoMove\Intercessor\Traits\Identifiable, Metable; protected $name; /** @var Folder */ protected $parent = null; /** @var Folder[] */ protected $children = []; /** @var Project[] */ protected $projects = []; public function __construct($name = null) { $this->name($name); $this->defaultId(); } public function name($name = null) { if (is_null($name)) { return $this->name; } $this->name = $name; return $this; } public function parent(Folder $parent = null) { if (is_null($parent)) { return $this->parent; } $this->parent = $parent; return $this; } public function children(array $children = null) { if (is_null($children)) { return $this->children; } $this->children = $children; return $this; } public function child(Folder $child) { $this->children[] = $child; return $this; } public function projects(array $projects = null) { if (is_null($projects)) { return $this->projects; } $this->projects = $projects; return $this; } public function project(Project $project) { $this->projects[] = $project; return $this; } }
TodoMove/intercessor
src/TodoMove/Intercessor/Folder.php
PHP
mit
1,483
#include <Rcpp.h> using namespace Rcpp; // underflow prevention: if the argument to log is so small // we get -Inf, we just give back 0. inline double xlogy(double x, double y) { double lg = log(y); return (lg == R_NegInf) ? 0 : x * lg; } // [[Rcpp::export]] double jsdiv_v(NumericVector P, NumericVector Q) { int n = P.size(); if (Q.size() != n) { stop("P and Q must be of same length"); } double total = 0; double PQ_mean; for (int i = 0; i < n; i++) { PQ_mean = (P[i] + Q[i]) / 2; if (P[i] != 0) { total += xlogy(P[i], P[i] / PQ_mean); } if (Q[i] != 0) { total += xlogy(Q[i], Q[i] / PQ_mean); } } return total / 2; } // [[Rcpp::export]] NumericMatrix jsdiv_m(NumericMatrix x, NumericMatrix y) { int n = x.nrow(), m = y.nrow(); if (y.ncol() != x.ncol()) { stop("x and y must have the same number of columns"); } NumericMatrix result(n, m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { result(i, j) = jsdiv_v(x(i, _), y(j, _)); } } return result; } // TODO an RcppEigen version for sparse matrices would be nice
agoldst/dfrtopics
src/JS_divergence.cpp
C++
mit
1,214
<?php namespace Hail\Debugger; use Psr\Http\Message\ResponseInterface; use Psr\Log\LoggerInterface; use Psr\Log\LoggerTrait; use Psr\Log\LogLevel; /** * ChromeLogger console logger. * * @see https://craig.is/writing/chrome-logger * @see https://developer.mozilla.org/en-US/docs/Tools/Web_Console/Console_messages#Server */ class ChromeLogger implements LoggerInterface { use LoggerTrait; protected const VERSION = '4.1.0'; protected const COLUMN_LOG = 'log'; protected const COLUMN_BACKTRACE = 'backtrace'; protected const COLUMN_TYPE = 'type'; protected const CLASS_NAME = 'type'; protected const HEADER_NAME = 'X-ChromeLogger-Data'; public const LOG = 'log'; public const WARN = 'warn'; public const ERROR = 'error'; public const INFO = 'info'; // TODO add support for groups and tables? public const GROUP = 'group'; public const GROUP_END = 'groupEnd'; public const GROUP_COLLAPSED = 'groupCollapsed'; public const TABLE = 'table'; public const DATETIME_FORMAT = 'Y-m-d\\TH:i:s\\Z'; // ISO-8601 UTC date/time format public const LIMIT_WARNING = 'Beginning of log entries omitted - total header size over Chrome\'s internal limit!'; /** * @var int header size limit (in bytes, defaults to 240KB) */ protected $limit = 245760; /** * @var array[][] */ protected $entries = []; /** * Logs with an arbitrary level. * * @param mixed $level * @param string $message * @param array $context * * @return void */ public function log($level, $message, array $context = []): void { $this->entries[] = [$level, $message, $context]; } /** * Allows you to override the internal 240 KB header size limit. * * (Chrome has a 250 KB limit for the total size of all headers.) * * @see https://cs.chromium.org/chromium/src/net/http/http_stream_parser.h?q=ERR_RESPONSE_HEADERS_TOO_BIG&sq=package:chromium&dr=C&l=159 * * @param int $limit header size limit (in bytes) */ public function setLimit(int $limit): void { $this->limit = $limit; } /** * @return int header size limit (in bytes) */ public function getLimit(): int { return $this->limit; } /** * Adds headers for recorded log-entries in the ChromeLogger format, and clear the internal log-buffer. * * (You should call this at the end of the request/response cycle in your PSR-7 project, e.g. * immediately before emitting the Response.) * * @param ResponseInterface $response * * @return ResponseInterface */ public function writeToResponse(ResponseInterface $response): ResponseInterface { if ($this->entries !== []) { $value = $this->getHeaderValue(); $this->entries = []; return $response->withHeader(self::HEADER_NAME, $value); } return $response; } /** * Emit the header for recorded log-entries directly using `header()`, and clear the internal buffer. * * (You can use this in a non-PSR-7 project, immediately before you start emitting the response body.) * * @throws \RuntimeException if you've already started emitting the response body * * @return void */ public function emitHeader(): void { if (\headers_sent()) { throw new \RuntimeException('unable to emit ChromeLogger header: headers have already been sent'); } \header(self::HEADER_NAME . ': ' . $this->getHeaderValue()); $this->entries = []; } /** * @return string raw value for the X-ChromeLogger-Data header */ protected function getHeaderValue(): string { $data = $this->createData($this->entries); $value = $this->encodeData($data); if (\strlen($value) > $this->limit) { $data['rows'][] = $this->createEntryData( [LogLevel::WARNING, self::LIMIT_WARNING, []] ); // NOTE: the strategy here is to calculate an estimated overhead, based on the number // of rows - because the size of each row may vary, this isn't necessarily accurate, // so we may need repeat this more than once. while (\strlen($value) > $this->limit) { $num_rows = \count($data['rows']); // current number of rows $row_size = \strlen($value) / $num_rows; // average row-size $max_rows = (int) \floor(($this->limit * 0.95) / $row_size); // 5% under the likely max. number of rows $excess = \max(1, $num_rows - $max_rows); // Remove excess rows and try encoding again: $data['rows'] = \array_slice($data['rows'], $excess); $value = $this->encodeData($data); } } return $value; } /** * Encodes the ChromeLogger-compatible data-structure in JSON/base64-format * * @param array $data header data * * @return string */ protected function encodeData(array $data): string { $json = \json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); return \base64_encode($json); } /** * Internally builds the ChromeLogger-compatible data-structure from internal log-entries. * * @param array[][] $entries * * @return array */ protected function createData(array $entries): array { $rows = []; foreach ($entries as $entry) { $rows[] = $this->createEntryData($entry); } return [ 'version' => self::VERSION, 'columns' => [self::COLUMN_LOG, self::COLUMN_TYPE, self::COLUMN_BACKTRACE], 'rows' => $rows, ]; } /** * Encode an individual LogEntry in ChromeLogger-compatible format * * @param array $entry * * @return array log entry in ChromeLogger row-format */ protected function createEntryData(array $entry): array { // NOTE: "log" level type is deliberately omitted from the following map, since // it's the default entry-type in ChromeLogger, and can be omitted. static $LEVELS = [ LogLevel::DEBUG => self::LOG, LogLevel::INFO => self::INFO, LogLevel::NOTICE => self::INFO, LogLevel::WARNING => self::WARN, LogLevel::ERROR => self::ERROR, LogLevel::CRITICAL => self::ERROR, LogLevel::ALERT => self::ERROR, LogLevel::EMERGENCY => self::ERROR, ]; $row = []; [$level, $message, $context] = $entry; $data = [ \str_replace('%', '%%', Dumper::interpolate($message, $context)), ]; if (\count($context)) { $context = $this->sanitize($context); $data = \array_merge($data, $context); } $row[] = $data; $row[] = $LEVELS[$level] ?? self::LOG; if (isset($context['exception'])) { // NOTE: per PSR-3, this reserved key could be anything, but if it is an Exception, we // can use that Exception to obtain a stack-trace for output in ChromeLogger. $exception = $context['exception']; if ($exception instanceof \Throwable) { $row[] = $exception->__toString(); } } // Optimization: ChromeLogger defaults to "log" if no entry-type is specified. if ($row[1] === self::LOG) { if (\count($row) === 2) { unset($row[1]); } else { $row[1] = ''; } } return $row; } /** * Internally marshall and sanitize context values, producing a JSON-compatible data-structure. * * @param mixed $data any PHP object, array or value * @param true[] $processed map where SPL object-hash => TRUE (eliminates duplicate objects from data-structures) * * @return mixed marshalled and sanitized context */ protected function sanitize($data, array &$processed = []) { if (\is_array($data)) { /** * @var array $data */ foreach ($data as $name => $value) { $data[$name] = $this->sanitize($value, $processed); } return $data; } if (\is_object($data)) { /** * @var object $data */ $class_name = \get_class($data); $hash = \spl_object_hash($data); if (isset($processed[$hash])) { // NOTE: duplicate objects (circular references) are omitted to prevent recursion. return [self::CLASS_NAME => $class_name]; } $processed[$hash] = true; if ($data instanceof \JsonSerializable) { // NOTE: this doesn't serialize to JSON, it only marshalls to a JSON-compatible data-structure $data = $this->sanitize($data->jsonSerialize(), $processed); } elseif ($data instanceof \DateTimeInterface) { $data = $this->extractDateTimeProperties($data); } elseif ($data instanceof \Throwable) { $data = $this->extractExceptionProperties($data); } else { $data = $this->sanitize($this->extractObjectProperties($data), $processed); } return \array_merge([self::CLASS_NAME => $class_name], $data); } if (\is_scalar($data)) { return $data; // bool, int, float } if (\is_resource($data)) { $resource = \explode('#', (string) $data); return [ self::CLASS_NAME => 'resource<' . \get_resource_type($data) . '>', 'id' => \array_pop($resource), ]; } return null; // omit any other unsupported types (e.g. resource handles) } /** * @param \DateTimeInterface $datetime * * @return array */ protected function extractDateTimeProperties(\DateTimeInterface $datetime): array { $utc = \date_create_from_format('U', $datetime->format('U'), \timezone_open('UTC')); return [ 'datetime' => $utc->format(self::DATETIME_FORMAT), 'timezone' => $datetime->getTimezone()->getName(), ]; } /** * @param object $object * * @return array */ protected function extractObjectProperties($object): array { $properties = []; $reflection = new \ReflectionObject($object); // obtain public, protected and private properties of the class itself: foreach ($reflection->getProperties() as $property) { if ($property->isStatic()) { continue; // omit static properties } $property->setAccessible(true); $properties["\${$property->name}"] = $property->getValue($object); } // obtain any inherited private properties from parent classes: while ($reflection = $reflection->getParentClass()) { foreach ($reflection->getProperties(\ReflectionProperty::IS_PRIVATE) as $property) { $property->setAccessible(true); $properties["{$reflection->name}::\${$property->name}"] = $property->getValue($object); } } return $properties; } /** * @param \Throwable $exception * * @return array */ protected function extractExceptionProperties(\Throwable $exception): array { $previous = $exception->getPrevious(); return [ '$message' => $exception->getMessage(), '$file' => $exception->getFile(), '$code' => $exception->getCode(), '$line' => $exception->getLine(), '$previous' => $previous ? $this->extractExceptionProperties($previous) : null, ]; } }
flyinghail/Hail-Framework
src/Debugger/ChromeLogger.php
PHP
mit
12,162
module NIDAG # Exports a set of Articles in different formats class Exporter end end
NIDAG/ACE
lib/Exporter.rb
Ruby
mit
101
<?php class HeaderRequest{ public $id_user = null; public $token = null; public $businessRequest = null; } ?>
miguelfreelancer56577/WineRestServicesPHP
application/beans/HeaderRequest.php
PHP
mit
117
require 'httparty' module DeepThought module Notifier def self.notify(user, message) begin HTTParty.post("#{user.notification_url}", :body => {:message => message}.to_json, :headers => {'Content-Type' => 'application/json'}) rescue 'poop' end end end end
redhotvengeance/deep_thought
lib/deep_thought/notifier.rb
Ruby
mit
302
<?php namespace spec\Money\Provider; use Money\Provider; use Money\Currency; use Money\Exception\UnsupportedCurrency; use PhpSpec\ObjectBehavior; class BatchSpec extends ObjectBehavior { function it_is_initializable() { $this->shouldHaveType('Money\Provider\Batch'); $this->shouldHaveType('Money\Provider'); } function it_should_have_providers(Provider $provider) { $this->hasProvider($provider)->shouldReturn(false); $this->addProvider($provider); $this->hasProvider($provider)->shouldReturn(true); } function it_should_be_able_to_get_a_rate(Provider $provider1, Provider $provider2) { $rate = 1.25; $baseCurrency = new Currency('EUR'); $counterCurrency = new Currency('USD'); $e = new UnsupportedCurrency($baseCurrency); $provider1->getRate($baseCurrency, $counterCurrency)->willThrow($e); $provider2->getRate($baseCurrency, $counterCurrency)->willReturn($rate); $this->addProvider($provider1); $this->addProvider($provider2); $this->getRate($baseCurrency, $counterCurrency)->shouldReturn($rate); } function it_should_throw_an_exception_when_called_without_providers() { $baseCurrency = new Currency('EUR'); $counterCurrency = new Currency('USD'); $this->shouldThrow('RuntimeException')->duringGetRate($baseCurrency, $counterCurrency); } function it_should_throw_an_exception_when_all_provider_fails(Provider $provider1, Provider $provider2) { $rate = 1.25; $baseCurrency = new Currency('EUR'); $counterCurrency = new Currency('USD'); $e = new UnsupportedCurrency($baseCurrency); $provider1->getRate($baseCurrency, $counterCurrency)->willThrow($e); $provider2->getRate($baseCurrency, $counterCurrency)->willThrow($e); $this->addProvider($provider1); $this->addProvider($provider2); $this->shouldThrow($e)->duringGetRate($baseCurrency, $counterCurrency); } function it_should_throw_an_exception_when_rate_cannot_be_determined(Provider $provider) { $rate = 1.25; $baseCurrency = new Currency('EUR'); $counterCurrency = new Currency('USD'); $provider->getRate($baseCurrency, $counterCurrency)->willReturn(null); $this->addProvider($provider); $this->shouldThrow('RuntimeException')->duringGetRate($baseCurrency, $counterCurrency); } }
indigophp/money
spec/Money/Provider/BatchSpec.php
PHP
mit
2,484
using Myxini.Recognition.Raw; using System; using System.Collections.Generic; namespace Myxini.Recognition.Image { public class CellDescriptor { const int CELL_SIZE = 8; private class Gradient { public static readonly int BIN = 9; public static readonly double ORIENTATION = Math.PI / BIN; public Gradient() { this.Histogram = new float[BIN]; } public float this[int index] { get { return this.Histogram[index]; } set { this.Histogram[index] = value; } } public float this[float n] { get { return this.Histogram[(int)Math.Floor(n / (Math.PI / ORIENTATION))]; } set { this.Histogram[(int)Math.Floor(n / (Math.PI / ORIENTATION))] = value; } } private float[] Histogram; } private static Gradient calculateGradient(GrayImage image) { var gradient = new Gradient(); var orientation = Math.PI / Gradient.BIN; for (int y = 1; y < (image.Height - 1); ++y) { for (int x = 1; x < (image.Width - 1); ++x) { var fx = image.GetElement(x + 1, y) - image.GetElement(x - 1, y); var fy = image.GetElement(x, y + 1) - image.GetElement(x, y - 1); float magnitude = (float)Math.Sqrt(fx * fx + fy * fy); float angle = (float)Math.Atan2(fy, fx); if (angle < 0) { angle += (float)Math.PI; } else if (angle == Math.PI) { angle = 0.0f; } gradient[angle] += magnitude; } } return gradient; } private static Gradient[] DescriptHOG(GrayImage image) { var size = image.BoundingBox.BoundingSize; Size low_resolution_size = new Size(size.Width / CELL_SIZE, size.Height / CELL_SIZE); Func<Point, Point> remap_function = (Point input)=> { return new Point( input.X * CELL_SIZE, input.Y * CELL_SIZE ); }; Rectangle mapped_rect = new Rectangle(0, 0, CELL_SIZE, CELL_SIZE); Gradient[] output = new Gradient[low_resolution_size.Width * low_resolution_size.Height]; for (int y = 0; y < low_resolution_size.Height; ++y) { for (int x = 0; x < low_resolution_size.Width; ++x) { Point point = new Point(x, y); Point mapped_point = remap_function(point); mapped_rect.X = mapped_point.X; mapped_rect.Y = mapped_point.Y; output[y * low_resolution_size.Width + x] = calculateGradient(image.RegionOfImage(mapped_rect) as GrayImage); } } return output; } public static GrayImage DescriptImage(GrayImage image) { var size = image.BoundingBox.BoundingSize; var hog = DescriptHOG(image); // normalize histogram float max_grad = float.MinValue; foreach (var gradient in hog) { for (int c = 0; c < Gradient.BIN; ++c) { if (max_grad < gradient[c]) { max_grad = gradient[c]; } } } foreach (var gradient in hog) { for (int c = 0; c < Gradient.BIN; ++c) { gradient[c] = gradient[c] / max_grad; } } Size low_resolution_size = new Size(size.Width / CELL_SIZE, size.Height / CELL_SIZE); var gray_bitmap = new byte[low_resolution_size.Width * low_resolution_size.Height]; for (int y = 0; y < low_resolution_size.Height; ++y ) { for(int x = 0; x < low_resolution_size.Width; ++x ) { float sum = 0.0f; var index = y * low_resolution_size.Width + x; for (int c = 0; c < Gradient.BIN; ++c) { sum += hog[index][c]; } if (sum > 0.2) { gray_bitmap[index] = 255; } else { gray_bitmap[index] = 0; } } } return new GrayImage(gray_bitmap, low_resolution_size.Width, low_resolution_size.Height); } public static int mapPoint(int p) { return p / CELL_SIZE; } } }
myxini/block-program
block-program/Detection/Image/CellDescriptor.cs
C#
mit
3,701
using System; namespace Embark.Storage { internal sealed class DocumentKeySource { internal DocumentKeySource(long lastKey) { this.lastKey = lastKey; } long lastKey = 0; object syncRoot = new object(); public long GetNewKey() { var newKey = DateTime.Now.Ticks; lock(syncRoot) { if (newKey > lastKey) lastKey = newKey; else lastKey += 1; return lastKey; } } } }
chasingbob/embark
Embark/Storage/DocumentKeySource.cs
C#
mit
574
/*Owner & Copyrights: Vance King Saxbe. A.*//*Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @vsaxbe@yahoo.com. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/ $stream = file_get_contents('BVICLAST.txt'); $avgp = "13.90"; $high = "13.90"; $low = "13.75"; echo "&L=".$stream."&N=BVIC&"; $temp = file_get_contents("BVICTEMP.txt", "r"); if ($stream != $temp ) { $mhigh = ($avgp + $high)/2; $mlow = ($avgp + $low)/2; $llow = ($low - (($avgp - $low)/2)); $hhigh = ($high + (($high - $avgp)/2)); if ( $stream > $temp ) { if ( ($stream > $mhigh ) && ($stream < $high)) { echo "&sign=au" ; } if ( ($stream < $mlow ) && ($stream > $low)) { echo "&sign=ad" ; } if ( $stream < $llow ) { echo "&sign=as" ; } if ( $stream > $hhigh ) { echo "&sign=al" ; } if ( ($stream < $hhigh) && ($stream > $high)) { echo "&sign=auu" ; } if ( ($stream > $llow) && ($stream < $low)) { echo "&sign=add" ; } //else { echo "&sign=a" ; } } if ( $stream < $temp ) { if ( ($stream >$mhigh) && ($stream < $high)) { echo "&sign=bu" ; } if ( ($stream < $mlow) && ($stream > $low)) { echo "&sign=bd" ; } if ( $stream < $llow ) { echo "&sign=bs" ; } if ( $stream > $hhigh ) { echo "&sign=bl" ; } if ( ($stream < $hhigh) && ($stream > $high)) { echo "&sign=buu" ; } if ( ($stream > $llow) && ($stream < $low)) { echo "&sign=bdd" ; } // else { echo "&sign=b" ; } } $my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filename= 'BVIC.txt'; $file = fopen($filename, "a+" ); fwrite( $file, $stream.":".$time."\r\n" ); fclose( $file ); if (($stream > $mhigh ) && ($temp<= $mhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($stream - $low) * (200000/$stream); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :".$stream. ":Approaching:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream < $mhigh ) && ($temp>= $mhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $stream) * (200000/$stream); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream.":Moving Down:PHIGH:".$high.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream > $mlow ) && ($temp<= $mlow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($stream - $low) * (200000/$stream); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :".$stream. ":Moving Up:PLOW:".$low.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream < $mlow ) && ($temp>= $mlow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $stream) * (200000/$stream); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream.":Approaching:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream > $high ) && ($temp<= $high )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($stream - $low) * (200000/$stream); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :".$stream. ":Breaking:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream > $hhigh ) && ($temp<= $hhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $risk = ($stream - $low) * (200000/$stream); $risk = (int)$risk; $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :".$stream. ":Moving Beyond:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream < $hhigh ) && ($temp>= $hhigh )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream. ":Coming near:PHIGH:".$high.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream < $high ) && ($temp>= $high )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream. ":Retracing:PHIGH:".$high."\r\n"); fclose( $filedash ); } if (($stream < $llow ) && ($temp>= $llow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $stream) * (200000/$stream); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream.":Breaking Beyond:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream < $low ) && ($temp>= $low )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $stream) * (200000/$stream); $risk = (int)$risk; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream.":Breaking:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream > $llow ) && ($temp<= $llow )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream.":Coming near:PLOW:".$low.":short Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream > $low ) && ($temp<= $low )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :". $stream.":Retracing:PLOW:".$low."\r\n"); fclose( $filedash ); } if (($stream > $avgp ) && ($temp<= $avgp )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($stream - $low) * (200000/$stream); $risk = (int)$risk; $avgp = number_format($avgp, 2, '.', ''); $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :".$stream. ":Sliding up:PAVG:".$avgp.":Buy Cost:".$risk."\r\n"); fclose( $filedash ); } if (($stream < $avgp ) && ($temp>= $avgp )) {$my_time = date('h:i:s',time()); $seconds2add = 19800; $new_time= strtotime($my_time); $new_time+=$seconds2add; $risk = ($high - $stream) * (200000/$stream); $risk = (int)$risk; $avgp = number_format($avgp, 2, '.', ''); $time = date('h:i:s',$new_time); $filedash = fopen("C:\wamp\www\alert.txt", "a+"); $wrote = fputs($filedash, "Britvic :".$stream. ":Sliding down:PAVG:".$avgp.":Short Cost:".$risk."\r\n"); fclose( $filedash ); } } $filedash = fopen("BVICTEMP.txt", "w"); $wrote = fputs($filedash, $stream); fclose( $filedash ); //echo "&chg=".$json_output['cp']."&"; ?> /*email to provide support at vancekingsaxbe@powerdominionenterprise.com, businessaffairs@powerdominionenterprise.com, For donations please write to fundraising@powerdominionenterprise.com*/
VanceKingSaxbeA/FTSE-Engine
App/BVIC.php
PHP
mit
8,633
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NumberComparer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NumberComparer")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3dfb458c-5b48-4322-a990-0a5442742635")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
DJBuro/Telerik
C#1/ConsoleInputOutput/NumberComparer/Properties/AssemblyInfo.cs
C#
mit
1,404
import { Controller } from "./controller.js"; import { loadShaders, samples } from "./samples.js"; import { View } from "./view.js"; export function init() { window.onload = () => doInit(); } function doInit() { const controller = new Controller(); const view = new View("canvas-gl", samples, { levelOfDetails: controller.levelOfDetails(), programSample: controller.programSample() .map(index => samples[index]) .then(loadShaders), program: controller.program(), mesh: controller.mesh(), mouseXBinding: controller.mouseXBinding(), mouseYBinding: controller.mouseYBinding(), mouseXY: controller.mouseXY() }); }
ghadeeras/ghadeeras.github.io
src/webgl-lab/toy.ts
TypeScript
mit
708
import { FETCH_AUTHOR, UPDATE_AUTHOR } from 'shared/constants/actions'; const INITIAL_STATE = { author: {}, errorMessage: '' }; export default function (state = INITIAL_STATE, action) { switch (action.type) { case FETCH_AUTHOR.SUCCESS: // author -> { id, email, name, image, description, introduction } return { author: action.payload.author, errorMessage: '' }; case UPDATE_AUTHOR.SUCCESS: return { ...state, author: {}, errorMessage: '' }; case UPDATE_AUTHOR.FAILURE: return { ...state, errorMessage: action.payload.errorMessage }; default: return state; } }
tsurupin/portfolio
frontend/src/shared/reducers/authors.js
JavaScript
mit
626
'use strict' // Load requirements const slack = require('slack') const path = require('path') // Load utilities const i18n = require('../locale') const logger = require('../log') // Data directory const dataDir = path.join(__dirname, '../../../data/') // User tracking and handling module.exports = { // User flags to avoid, edit these depending on your privileges flags: [ // 'is_admin', // 'is_owner', // 'is_primary_owner', // 'is_restricted', 'is_ultra_restricted', 'is_bot' ], // Load the user blacklist blacklist: require(path.join(dataDir, 'blacklist')), // Contains the list of tracked users users: {}, // Check if id or username is on the blacklist blacklisted: function (user) { return this.blacklist.some((handle) => { return handle === user.id || handle === user.name }) }, // Check if a user is restricted restricted: function (user) { return this.flags.some((flag) => { return user[flag] === true }) }, // Add a user to the track list add: function (user, ignore) { // DEBUG logger.verbose(i18n.t('users.add.added'), user.name) // Add to object for tracking this.users[user.id] = { id: user.id, name: user.name, real_name: user.real_name, short_name: (user.real_name || '').split(' ')[0], emoji: (user.profile.status_emoji || '').replace(/:/g, ''), text: user.profile.status_text || '', ignore: ignore || false } }, // Load the available users load: function () { return new Promise((resolve, reject) => { // Get the list from the slack API slack.users.list({token: process.env.SLACK_TOKEN}, (err, data) => { // Check for errors if (err !== null) { return reject(new Error(i18n.t('users.load.errors.slack', err.message))) } // Check for a response if (data.ok !== true) { return reject(new Error(i18n.t('users.load.errors.invalid'))) } // Loop members and add them to ze list data.members.forEach((user) => { if (!this.restricted(user)) this.add(user) }) // resolve the promise with data return resolve(this.users) }) }) } }
jHoldroyd/trollmoji
app/libs/users/index.js
JavaScript
mit
2,250
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using RobsonROX.Util.Collections; namespace RobsonROX.Util.Extensions { // ReSharper disable once InconsistentNaming // ReSharper disable PossibleMultipleEnumeration /// <summary> /// Métodos de extensão para IEnumerable /// </summary> public static class IEnumerableExtensions { /// <summary> /// Retorna uma versão paginável da coleção /// </summary> /// <param name="source">Coleção a ser paginável</param> /// <param name="pageSize">Tamanho da página</param> /// <typeparam name="T">Tipo contido pela coleção</typeparam> /// <returns>Uma instância de <see cref="PagedEnumerable{T}"/> contendo a coleção fornecida</returns> [DebuggerStepThrough] public static IPagedEnumerable<T> AsPagedEnumerable<T>(this IEnumerable<T> source, int pageSize) { return new PagedEnumerable<T>(source, pageSize); } /// <summary> /// Executa o delegate especificado para todos os itens da coleção fornecida /// </summary> /// <param name="source">Coleção a ser iterada</param> /// <param name="action">Delegate representando a ação a ser executada</param> /// <typeparam name="T">Tipo dos itens da coleção fornecida</typeparam> /// <returns>Coleção fornecida como source</returns> [DebuggerStepThrough] public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action) { foreach (var item in source) action(item); return source; } /// <summary> /// Executa o delegate especificado para todos os itens da coleção fornecida, permitindo interromper a iteração /// </summary> /// <param name="source">Coleção a ser iterada</param> /// <param name="breakableFunc">Delegate representando a ação a ser executada. Caso o delegate retorne false, interrompe a iteração</param> /// <typeparam name="T">Tipo dos itens da coleção fornecida</typeparam> /// <returns>Coleção fornecida como source</returns> [DebuggerStepThrough] public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Func<T, bool> breakableFunc) { foreach (var item in source) if(!breakableFunc(item)) break; return source; } /// <summary> /// Filtra uma lista com base no critério apresentado pelo selector /// </summary> /// <param name="source">Lista a ser filtrada</param> /// <param name="keySelector">Função que indica qual o critério de filtragem</param> /// <typeparam name="TSource">Tipo de lista de origem</typeparam> /// <typeparam name="TKey">Tipo do valor retornado pela função de critério</typeparam> /// <returns>Lista contendo apenas os itens únicos de acordo com os critérios retornados pela função para cada elemento da lista de origem</returns> [DebuggerStepThrough] public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { var set = new HashSet<TKey>(); return source.Where(s => set.Add(keySelector(s))); } } }
RobsonROX/Util
Util/Extensions/IEnumerableExtensions.cs
C#
mit
3,431
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from typing import TYPE_CHECKING, Any, Dict, Union from ansiblelint.rules import AnsibleLintRule if TYPE_CHECKING: from typing import Optional from ansiblelint.file_utils import Lintable class MercurialHasRevisionRule(AnsibleLintRule): id = 'hg-latest' shortdesc = 'Mercurial checkouts must contain explicit revision' description = ( 'All version control checkouts must point to ' 'an explicit commit or tag, not just ``latest``' ) severity = 'MEDIUM' tags = ['idempotency'] version_added = 'historic' def matchtask( self, task: Dict[str, Any], file: 'Optional[Lintable]' = None ) -> Union[bool, str]: return bool( task['action']['__ansible_module__'] == 'hg' and task['action'].get('revision', 'default') == 'default' )
ansible/ansible-lint
src/ansiblelint/rules/MercurialHasRevisionRule.py
Python
mit
1,951
// // CoronaApplication.java // TemplateApp // // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // package com.wonhada.EnterpriseExample; /** * Extends the Application class to receive Corona runtime events and to extend the Lua API. * <p> * Only one instance of this class will be created by the Android OS. It will be created before this application's * activity is displayed and will persist after the activity is destroyed. The name of this class must be set in the * AndroidManifest.xml file's "application" tag or else an instance of this class will not be created on startup. */ public class CoronaApplication extends android.app.Application { /** Called when your application has started. */ @Override public void onCreate() { // Set up a Corona runtime listener used to add custom APIs to Lua. com.ansca.corona.CoronaEnvironment.addRuntimeListener(new CoronaApplication.CoronaRuntimeEventHandler()); } /** Receives and handles Corona runtime events. */ private class CoronaRuntimeEventHandler implements com.ansca.corona.CoronaRuntimeListener { /** * Called after the Corona runtime has been created and just before executing the "main.lua" file. * This is the application's opportunity to register custom APIs into Lua. * <p> * Warning! This method is not called on the main thread. * @param runtime Reference to the CoronaRuntime object that has just been loaded/initialized. * Provides a LuaState object that allows the application to extend the Lua API. */ @Override public void onLoaded(com.ansca.corona.CoronaRuntime runtime) { com.naef.jnlua.NamedJavaFunction[] luaFunctions; // Fetch the Lua state from the runtime. com.naef.jnlua.LuaState luaState = runtime.getLuaState(); // Add a module named "myTests" to Lua having the following functions. luaFunctions = new com.naef.jnlua.NamedJavaFunction[] { new GetSDCardPathFunction() }; luaState.register("nativeApp", luaFunctions); luaState.pop(1); } /** * Called just after the Corona runtime has executed the "main.lua" file. * <p> * Warning! This method is not called on the main thread. * @param runtime Reference to the CoronaRuntime object that has just been started. */ @Override public void onStarted(com.ansca.corona.CoronaRuntime runtime) { } /** * Called just after the Corona runtime has been suspended which pauses all rendering, audio, timers, * and other Corona related operations. This can happen when another Android activity (ie: window) has * been displayed, when the screen has been powered off, or when the screen lock is shown. * <p> * Warning! This method is not called on the main thread. * @param runtime Reference to the CoronaRuntime object that has just been suspended. */ @Override public void onSuspended(com.ansca.corona.CoronaRuntime runtime) { } /** * Called just after the Corona runtime has been resumed after a suspend. * <p> * Warning! This method is not called on the main thread. * @param runtime Reference to the CoronaRuntime object that has just been resumed. */ @Override public void onResumed(com.ansca.corona.CoronaRuntime runtime) { } /** * Called just before the Corona runtime terminates. * <p> * This happens when the Corona activity is being destroyed which happens when the user presses the Back button * on the activity, when the native.requestExit() method is called in Lua, or when the activity's finish() * method is called. This does not mean that the application is exiting. * <p> * Warning! This method is not called on the main thread. * @param runtime Reference to the CoronaRuntime object that is being terminated. */ @Override public void onExiting(com.ansca.corona.CoronaRuntime runtime) { } } }
englekk/CoronaEnterpriseTemplate
src/android/src/com/wonhada/EnterpriseExample/CoronaApplication.java
Java
mit
3,873
package iternada import ( "errors" ) var ( errNilReceiver = errors.New("Nil Receiver") )
reiver/go-iter
nada/errors.go
GO
mit
95
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'rspec' require 'asn_translate' # Requires supporting files with custom matchers and macros, etc, # in ./support/ and its subdirectories. Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} RSpec.configure do |config| end
seeingidog/asn_translate
spec/spec_helper.rb
Ruby
mit
363
/* * Adjust display of page based on search results */ function findSearchResults(data, dataLength) { $("#duplicate_box").remove(); var userString = $("#searchForm #searchField").val(); var minSearchLength = 1; if (userString.length >= minSearchLength) { //this calls search() inside itself var numResults = populateResults(userString, dataLength, data); // If "results" is empty, activate the "add new client" button. if (numResults > 0) { // We've found some results, but we may still have to add a // new client (maybe a person with the same name as an // existing client). The "add new client" button will be // activated, but with a caveat. caveatText = "None Of The Above -- Add New Client"; $("#addNewClient").text(caveatText); } else { // No need for the caveat. $("#addNewClient").text(noCaveatText); } // If we're over the minimum length, we may add a new client. $("#searchForm #addNewClient").prop("disabled", false); } else if (userString.length == 0) { $("#searchForm #results").empty(); $("#addNewClient").text(noCaveatText); $("#searchForm #addNewClient").prop("disabled", true); } }; /* * Takes a user-entered string and returns the number of matching * entries. Along the way it fills in the result divs. */ function populateResults(userString, data_length, dataset) { var newHits = search(userString, data_length, dataset); // Create an array to hold indices of all the latest hits. If an // old hit isn't found in here, it gets removed. var newHitIndices = []; for (var i=0; i<newHits.length; i++) { newHitIndices.push(newHits[i].index); } var oldHits = $("#searchForm #results .hit"); oldHits.each(function() { // Remember these are not objects of class Hit; // they're DOM elements (of class "hit"). var oldHitIndex = $(this).data("entity-index"); for (var i=newHits.length-1; i>=0; i--) { if (oldHitIndex == newHits[i].index) { // There is already a <div> in the results field that // matches the one just returned; replace it with an // updated version (like a longer match string). $(this).empty(); $(this).replaceWith(getSummaryDiv(newHits[i])); newHits.splice(i, 1); // remove the match from "newHits" } } // Finally, if the entity of an old hit is no longer // represented in new hits, mark it for removal from the // results area. if ($.inArray(oldHitIndex, newHitIndices) < 0) { $(this).addClass("removeMe"); } }); // Now remove from the "results" div... $("#searchForm #results .hit.removeMe").remove(); // And add all newHits... for (var i=0; i<newHits.length; i++) { $("#searchForm #results").append(getSummaryDiv(newHits[i])); } // Return the number of matching entities. return $("#searchForm #results > .hit").length; }; function Entity() { // Start by setting all values to the empty string. for (var i=0; i<propertyListLength; i++) { this[propertyList[i]] = ""; } // Set some default values. this.personalId = -1; this.picture = "unknown.png"; // Use the names stored in the search form as default vals. // Usually they'll be overwritten, but not if this is a new client. this.firstName = $("#searchForm #firstName").val(); this.lastName = $("#searchForm #lastName").val(); }; function Hit(entity) { this.index = entity.personalId; this.removeMe = false; // Used when comparing to already-matched records. this.picture = entity.picture; this.firstName = entity.firstName; this.lastName = entity.lastName; this.gender = entity.gender; this.dob = entity.dob ? getFormattedDOB(entity.dob) : ""; this.age = entity.dob ? getYearsOld(entity.dob) : ""; }; function getFormattedDOB(date) { return moment(date).format('DD MMM YYYY'); }; function getYearsOld(date) { return moment().diff(date, 'years'); }; /* Hit factory holds a dictionary of hits (with entity indices as keys) that match user input. */ function HitFactory() { this.hits = {}; }; HitFactory.prototype.getHit = function(entity) { var hit = null; if (this.hits.hasOwnProperty(entity.personalId)) { hit = this.hits[entity.personalId]; } else { hit = new Hit(entity); this.hits[entity.personalId] = hit; } return hit; }; HitFactory.prototype.killHit = function(entity) { if (this.hits.hasOwnProperty(entity.index)) { delete this.hits[entity.index]; } }; HitFactory.prototype.allTheHits = function() { var hitList = []; for (index in this.hits) { hitList.push(this.hits[index]); } return hitList; }; /* * Takes a user-entered string and returns the set of matching * clients, as "hit" objects. */ function search(userString, data_length, dataset) { // First Trim any non-alphanumerics from the ends of the user's input. userString = userString.replace(/^[^\w]+/i, "").replace(/[^\w]+$/i, ""); // Then split the user's string on non-alphanumeric sequences. This // eliminates a dot after a middle initial, a comma if name is // entered as "Doe, John" (or as "Doe , John"), etc. userSubstrings = userString.split(/\s+[^\w]+\s*|\s*[^\w]+\s+|\s+/); // Store the first and second user substrings into some hidden form // fields. They might be used later if a new client is created. $("#searchForm #firstName").val(userSubstrings[0]); $("#searchForm #lastName").val(userSubstrings.length > 1 ? userSubstrings[1] : ""); // The hit factory will generate new a Hit object or return an // already instantiated one with the requested index. var hitFactory = new HitFactory(); var entity = null; var result = null; var matchLength = 0; var hit = null; // Turn the user's input into a list of regexes that will try to match against our matching terms. var userRegexes = $.map(userSubstrings, function(userSubstring) { return new RegExp("^" + userSubstring, "i"); }); // This is the list of "matching terms" we will try to match to user input. var matchingTerms = ["firstName", "lastName"]; for (var i=0; i<data_length; i++) { entity = dataset[i]; // Make a copies of "userRegexes" and "matchingTerms" that we can // alter as we search. var userRegexesCopy = userRegexes.slice(0); var matchingTermsCopy = matchingTerms.slice(0); while (userRegexesCopy.length > 0) { var userRegex = userRegexesCopy.shift(); var matchFound = false; for (var j=0; j < matchingTermsCopy.length; ) { if (entity[matchingTermsCopy[j]] !== null){ result = entity[matchingTermsCopy[j]].match(userRegex); } else { result = null; } if (result !== null) { // We found a match. Figure out how long it is. matchLength = result[0].length; // If the match is perfect OR if there are no more // user-entered search terms after this one, we may mark it // as a hit. if (matchLength == entity[matchingTermsCopy[j]].length || userRegexesCopy.length == 0) { hit = hitFactory.getHit(entity); hit[matchingTermsCopy[j]] = "<span class='marked'>" + entity[matchingTermsCopy[j]].substr(0, matchLength) + "</span>" + entity[matchingTermsCopy[j]].substr(matchLength); matchFound = true; // Remove this matching term from consideration when // processing other user search terms by splicing it out // of our copy of matching terms. matchingTermsCopy.splice(j, 1); // Since "matchingTermsCopy" is now shorter by 1, continue // the loop without incrementing the counter. continue; } } j++; } if (matchFound == false) { // If any part of the user-entered search terms failed to find // a match, previous matches don't matter. The entity should // not appear in the list of hits. hitFactory.killHit(entity); break; } } } return hitFactory.allTheHits(); }; function getSummaryDiv(hit) { var summaryDiv = $("<div class='hit'></div>"); if (hit.picture){ var picture = $("<div class='picture'><img src=\"img/" + hit.picture + "\"></div>"); } var text = $("<div class='text'></div>"); var fullName = $("<div class='summaryElement'><span>" + hit.firstName + " " + hit.lastName + "</span></div>"); var clear = $("<div class='clear'></div>"); var dob = $("<div class='summaryElement'><span class='label'>DOB: </span><span>" + hit.dob + "</span></div>"); var age = $("<div class='summaryElement'><span class='label'>age: </span><span>" + getYearsOld(hit.dob) + "</span></div>"); summaryDiv.append(picture); text.append(fullName); text.append(clear); text.append(dob); text.append(age); summaryDiv.append(text); summaryDiv.data("entity-index", hit.index); return summaryDiv; };
OpenTechStrategies/openhmis-intake
public/js/search.js
JavaScript
mit
10,538
@extends('layouts.app') @section('title') Edit Ad @endsection @section('content') <div class="row"> @include('ads._nav', ['_active' => null]) <div class="col-9"> <h2>Edit @null($ad) "{{ $ad->name }}" @else New @endnull</h2> <div class="row mt-4"> <div class="col-md-8"> <form action="{{ route('ads.ad.save') }}" method="post" enctype="multipart/form-data"> <div class="row"> <div class="col-6"> <fieldset class="form-group"> <label for="name">Name</label> <input type="text" id="name" class="form-control" name="name" value="{{ old('name', $ad->name ?? "") }}"> <p class="text-muted">Internal name only.</p> </fieldset> </div> <div class="col-6"> <fieldset class="form-group"> <label for="campaign">Campaign</label> <select name="campaign" class="form-control" id="campaign"> @foreach($campaigns as $campaign) <option value="{{ $campaign->id }}" @if($ad->campaign ?? 0 == $campaign->id) selected @endif >{{ $campaign->name }}</option> @endforeach </select> <p class="text-muted">Which campaign we should attach this to.</p> </fieldset> </div> </div> <hr> <div class="row"> <div class="col-6"> <fieldset class="form-group"> <label for="img_url">Image URL</label> <input type="text" class="form-control" id="img_url" name="img_url" value="{{ old('img_url', $ad->img_url ?? "") }}"> <p class="text-muted">The url to the image being displayed. Uploading an image (<i class="fa fa-arrow-right"></i>) will fill this in for you.</p> </fieldset> </div> <div class="col-6"> <fieldset class="form-group"> <label for="image">Upload Image</label> <input type="file" class="form-control form-control-file" id="image" name="image"> <p class="text-muted">Uploading an image will overwrite the saved url (<i class="fa fa-arrow-left"></i>).</p> </fieldset> </div> </div> <fieldset class="form-group"> <label for="img_href">Image Link</label> <input type="text" id="img_href" class="form-control" name="img_href" value="{{ old('img_href', $ad->img_href ?? "") }}"> <p class="text-muted">Where the image links to.</p> </fieldset> <fieldset class="form-group"> <label for="img_alt">Image Alt Text</label> <input type="text" id="img_alt" class="form-control" name="img_alt" value="{{ old('img_alt', $ad->img_alt ?? "") }}"> <p class="text-muted">Text shown when the image doesn't load, or a user hovers over the image.</p> </fieldset> <hr> <fieldset class="form-group"> <label for="sponsor">Sponsor Name</label> <input type="text" id="sponsor" class="form-control" name="sponsor" value="{{ old('sponsor', $ad->sponsor ?? "") }}"> <p class="text-muted">The name of the organization who sponsored the ad.</p> </fieldset> <fieldset class="form-group"> <label for="sponsor_href">Sponsor Link</label> <input type="text" id="sponsor_href" class="form-control" name="sponsor_href" value="{{ old('sponsor_href', $ad->sponsor_href ?? "") }}"> <p class="text-muted">The sponsor name can link to a separate location than the ad image itself.</p> </fieldset> <fieldset class="form-group"> {{ csrf_field() }} @null($ad) <input type="hidden" name="ad" value="{{ $ad->id }}"> @endnull <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save</button> </fieldset> </form> @null($ad) <form action="{{ route('ads.ad.delete') }}" method="post"> {{ method_field('DELETE') }} {{ csrf_field() }} <input type="hidden" name="ad" value="{{ $ad->id }}"> <button type="submit" class="btn btn-danger confirm-form"><i class="fa fa-trash"></i> Delete</button> </form> @endnull </div> <div class="col-md-4"> <div class="card" id="example-ad" style="position: fixed;"> <a href="{{ old('img_href', $ad->img_href ?? "#") }}" id="example-link"> <img class="card-img-top" id="example-img" style="max-height: 250px;" src="{{ old('img_url', $ad->img_url ?? "https://placehold.it/300x300?text=Your%20Image%20Here") }}" alt="{{ old('img_alt', $ad->img_alt ?? "Fun Fact...") }}"> </a> <div class="card-footer text-muted text-sm small"> <i class="fa fa-bullhorn text-primary"></i> Sponsored by <a href="{{ old('sponsor_href', $ad->sponsor_href ?? "#") }}" id="example-sponsor">{{ old('sponsor', $ad->sponsor ?? "You!") }}</a> </div> </div> </div> </div> </div> </div> @endsection @section('scripts') <script> $('#sponsor').on('keyup', function() { $('#example-sponsor').html($(this).val()); }); $('#sponsor_href').on('keyup', function() { $('#example-sponsor').attr('href', $(this).val()); }); $('#img_url').on('change', function() { $('#example-img').attr('src', $(this).val()); }); $('#img_href').on('keyup', function() { console.log("keypress"); $('#example-link').attr('href', $(this).val()); }); $('#img_alt').on('change', function() { $('#example-img').attr('alt', $(this).val()); }); </script> @endsection
CoasterPoll/CoasterPoll
resources/views/ads/ads/edit.blade.php
PHP
mit
7,337
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /** * @var yii\web\View $this * @var amnah\yii2\user\Module $module * @var amnah\yii2\user\models\User $user * @var amnah\yii2\user\models\Profile $profile * @var amnah\yii2\user\models\Role $role * @var yii\widgets\ActiveForm $form */ ?> <div class="user-form"> <?php $form = ActiveForm::begin([ 'enableAjaxValidation' => true, ]); ?> <?= $form->field($user, 'amount')->textInput(['maxlength' => 255]) ?> <div class="form-group"> <?= Html::submitButton($user->isNewRecord ? Yii::t('user', 'Create') : Yii::t('user', 'Update'), ['class' => $user->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?> </div>
sokolby/skl-yii2-admin
views/points/_form.php
PHP
mit
757
import { Component } from '@angular/core'; import { VideoPlayerService, VideoPlayerSignals } from '../video-player.service'; @Component({ moduleId: module.id, selector: 'fo-video-controls-ws', templateUrl: 'video-controls-ws.component.html', styleUrls: ['video-controls-ws.component.css'] }) export class VideoControlsWSComponent { constructor (private vpService: VideoPlayerService) { } emitPlay() { this.vpService.controlsSignals.emit(VideoPlayerSignals.play); } emitPause() { this.vpService.controlsSignals.emit(VideoPlayerSignals.pause); } emitStop() { this.vpService.controlsSignals.emit(VideoPlayerSignals.stop); } }
liveandie/angular-playground
src/client/app/videoPlayer/controls-w-service/video-controls-ws.component.ts
TypeScript
mit
664
package hu.progtech.cd2t100.asm; import java.lang.reflect.Type; import com.google.gson.InstanceCreator; class LocationInstanceCreator implements InstanceCreator<Location> { public Location createInstance(Type type) { return new Location(0, 0); } }
battila7/cd2t-100
cd2t-100-core/src/test/java/hu/progtech/cd2t100/asm/LocationInstanceCreator.java
Java
mit
262
#include "deps.h" // Not implemented: // SDL_ConvertSurface - need PixelFormat implementation // SDL_CreateRGBSurfaceFrom - need to think about memory management? clone? keep reference? // SDL_CreateRGBSurfaceWithFormatFrom - ditto // SDL_LoadBMP_RW // SDL_SaveBMP_RW // SDL_SetSurfacePalette - need palette implementation namespace sdl2_bindings { using namespace v8; METHOD(BlitScaled) { BEGIN(); UNWRAP(src, Surface, args[0]); SDL_Rect srcRect; SDL_Rect *srcRectPtr = nullptr; if (!args[1]->IsNull()) { extractRect(isolate, args[1]->ToObject(), &srcRect); srcRectPtr = &srcRect; } UNWRAP(dst, Surface, args[2]); SDL_Rect dstRect; SDL_Rect *dstRectPtr = nullptr; if (!args[3]->IsNull()) { extractRect(isolate, args[3]->ToObject(), &dstRect); dstRectPtr = &dstRect; } if (SDL_BlitScaled(src->surface_, srcRectPtr, dst->surface_, dstRectPtr) != 0) { THROW_SDL_ERROR(); } } // HELPER METHOD(BlitScaledCmp) { BEGIN(); UNWRAP(src, Surface, args[0]); INTARG(sx, 1); INTARG(sy, 2); INTARG(sw, 3); INTARG(sh, 4); UNWRAP(dst, Surface, args[5]); INTARG(dx, 6); INTARG(dy, 7); INTARG(dw, 8); INTARG(dh, 9); SDL_Rect srcRect = { .x = sx, .y = sy, .w = sw, .h = sh }; SDL_Rect dstRect = { .x = dx, .y = dy, .w = dw, .h = dh }; if (SDL_BlitScaled(src->surface_, &srcRect, dst->surface_, &dstRect) != 0) { THROW_SDL_ERROR(); } } METHOD(BlitSurface) { BEGIN(); UNWRAP(src, Surface, args[0]); SDL_Rect srcRect; SDL_Rect *srcRectPtr = nullptr; if (!args[1]->IsNull()) { extractRect(isolate, args[1]->ToObject(), &srcRect); srcRectPtr = &srcRect; } UNWRAP(dst, Surface, args[2]); SDL_Rect dstRect; SDL_Rect *dstRectPtr = nullptr; if (!args[3]->IsNull()) { extractRect(isolate, args[3]->ToObject(), &dstRect); dstRectPtr = &dstRect; } if (SDL_BlitSurface(src->surface_, srcRectPtr, dst->surface_, dstRectPtr) != 0) { THROW_SDL_ERROR(); } } // HELPER METHOD(BlitSurfaceAtPoint) { BEGIN(); UNWRAP(src, Surface, args[0]); UNWRAP(dst, Surface, args[1]); INTARG(x, 2); INTARG(y, 3); SDL_Rect dstRect; dstRect.x = x; dstRect.y = y; dstRect.w = src->surface_->w; dstRect.h = src->surface_->h; if (SDL_BlitSurface(src->surface_, nullptr, dst->surface_, &dstRect) != 0) { THROW_SDL_ERROR(); } } METHOD(ConvertPixels) { BEGIN(); INTARG(width, 0); INTARG(height, 1); UINT32ARG(srcFormat, 2); Local<ArrayBufferView> srcBuffer = Local<ArrayBufferView>::Cast(args[3]); void *src = srcBuffer->Buffer()->GetContents().Data(); INTARG(srcPitch, 4); UINT32ARG(dstFormat, 5); Local<ArrayBufferView> dstBuffer = Local<ArrayBufferView>::Cast(args[6]); void *dst = dstBuffer->Buffer()->GetContents().Data(); INTARG(dstPitch, 7); if (SDL_ConvertPixels(width, height, srcFormat, src, srcPitch, dstFormat, dst, dstPitch) < 0) { THROW_SDL_ERROR(); } } METHOD(ConvertSurfaceFormat) { BEGIN(); UNWRAP(surface, Surface, args[0]); UINT32ARG(format, 1); SDL_Surface *newSurface = SDL_ConvertSurfaceFormat(surface->surface_, format, 0); if (newSurface == nullptr) { THROW_SDL_ERROR(); } else { RETURN(Surface::NewInstance(isolate, newSurface, true)); } } METHOD(CreateRGBSurface) { BEGIN(); INTARG(width, 0); INTARG(height, 1); INTARG(depth, 2); UINT32ARG(rmask, 3); UINT32ARG(gmask, 4); UINT32ARG(bmask, 5); UINT32ARG(amask, 6); auto surface = SDL_CreateRGBSurface(0, width, height, depth, rmask, gmask, bmask, amask); if (surface == nullptr) { THROW_SDL_ERROR(); } else { RETURN(Surface::NewInstance(isolate, surface, true)); } } METHOD(CreateRGBSurfaceWithFormat) { BEGIN(); INTARG(width, 0); INTARG(height, 1); INTARG(depth, 2); UINT32ARG(format, 3); auto surface = SDL_CreateRGBSurfaceWithFormat(0, width, height, depth, format); if (surface == nullptr) { THROW_SDL_ERROR(); } else { RETURN(Surface::NewInstance(isolate, surface, true)); } } // SDL_CreateRGBSurfaceWithFormat METHOD(FillRect) { BEGIN(); UNWRAP(surface, Surface, args[0]); SDL_Rect rect; SDL_Rect *rectPtr = nullptr; if (!args[1]->IsNull()) { extractRect(isolate, args[1]->ToObject(), &rect); rectPtr = &rect; } UINT32ARG(color, 2); if (SDL_FillRect(surface->surface_, rectPtr, color) != 0) { THROW_SDL_ERROR(); } } METHOD(FillRects) { BEGIN(); UNWRAP(surface, Surface, args[0]); ARRAYARG(rects, 1); UINT32ARG(color, 2); int count = rects->Length(); SDL_Rect sdlRects[count]; for (int ix = 0; ix < count; ++ix) { extractRect(isolate, rects->Get(ix)->ToObject(), &sdlRects[ix]); } if (SDL_FillRects(surface->surface_, sdlRects, count, color) != 0) { THROW_SDL_ERROR(); } } METHOD(GetClipRect) { BEGIN(); UNWRAP(surface, Surface, args[0]); SDL_Rect out; SDL_GetClipRect(surface->surface_, &out); auto rect = MK_OBJECT(); populateRect(isolate, rect, &out); RETURN(rect); } METHOD(GetColorKey) { BEGIN(); UNWRAP(surface, Surface, args[0]); uint32_t colorKey; if (SDL_GetColorKey(surface->surface_, &colorKey) < 0) { THROW_SDL_ERROR(); } else { RETURN(MK_NUMBER(colorKey)); } } METHOD(GetSurfaceAlphaMod) { BEGIN(); UNWRAP(surface, Surface, args[0]); uint8_t alphaMod; if (SDL_GetSurfaceAlphaMod(surface->surface_, &alphaMod) < 0) { THROW_SDL_ERROR(); } else { RETURN(MK_NUMBER(alphaMod)); } } METHOD(GetSurfaceBlendMode) { BEGIN(); UNWRAP(surface, Surface, args[0]); SDL_BlendMode blendMode; if (SDL_GetSurfaceBlendMode(surface->surface_, &blendMode) < 0) { THROW_SDL_ERROR(); } else { RETURN(MK_NUMBER(blendMode)); } } METHOD(GetSurfaceColorMod) { BEGIN(); UNWRAP(surface, Surface, args[0]); uint8_t r, g, b; if (SDL_GetSurfaceColorMod(surface->surface_, &r, &g, &b) < 0) { THROW_SDL_ERROR(); } else { auto out = MK_OBJECT(); GET_CONTEXT(); SET_KEY(out, SYM(r), MK_NUMBER(r)); SET_KEY(out, SYM(g), MK_NUMBER(g)); SET_KEY(out, SYM(b), MK_NUMBER(b)); RETURN(out); } } METHOD(LoadBMP) { BEGIN(); STRINGARG(file, 0); auto surface = SDL_LoadBMP(*file); if (surface == nullptr) { THROW_SDL_ERROR(); } else { RETURN(Surface::NewInstance(isolate, surface, true)); } } METHOD(LockSurface) { BEGIN(); UNWRAP(surface, Surface, args[0]); if (SDL_LockSurface(surface->surface_) < 0) { THROW_SDL_ERROR(); } } METHOD(LowerBlit) { BEGIN(); UNWRAP(src, Surface, args[0]); SDL_Rect srcRect; SDL_Rect *srcRectPtr = nullptr; if (!args[1]->IsNull()) { extractRect(isolate, args[1]->ToObject(), &srcRect); srcRectPtr = &srcRect; } UNWRAP(dst, Surface, args[2]); SDL_Rect dstRect; SDL_Rect *dstRectPtr = nullptr; if (!args[3]->IsNull()) { extractRect(isolate, args[3]->ToObject(), &dstRect); dstRectPtr = &dstRect; } if (SDL_LowerBlit(src->surface_, srcRectPtr, dst->surface_, dstRectPtr) != 0) { THROW_SDL_ERROR(); } } // HELPER METHOD(LowerBlitAtPoint) { BEGIN(); UNWRAP(src, Surface, args[0]); UNWRAP(dst, Surface, args[1]); INTARG(x, 2); INTARG(y, 3); SDL_Rect dstRect; dstRect.x = x; dstRect.y = y; dstRect.w = src->surface_->w; dstRect.h = src->surface_->h; if (SDL_LowerBlit(src->surface_, nullptr, dst->surface_, &dstRect) != 0) { THROW_SDL_ERROR(); } } METHOD(LowerBlitScaled) { BEGIN(); UNWRAP(src, Surface, args[0]); SDL_Rect srcRect; SDL_Rect *srcRectPtr = nullptr; if (!args[1]->IsNull()) { extractRect(isolate, args[1]->ToObject(), &srcRect); srcRectPtr = &srcRect; } UNWRAP(dst, Surface, args[2]); SDL_Rect dstRect; SDL_Rect *dstRectPtr = nullptr; if (!args[3]->IsNull()) { extractRect(isolate, args[3]->ToObject(), &dstRect); dstRectPtr = &dstRect; } if (SDL_LowerBlitScaled(src->surface_, srcRectPtr, dst->surface_, dstRectPtr) != 0) { THROW_SDL_ERROR(); } } // HELPER METHOD(LowerBlitScaledCmp) { BEGIN(); UNWRAP(src, Surface, args[0]); INTARG(sx, 1); INTARG(sy, 2); INTARG(sw, 3); INTARG(sh, 4); UNWRAP(dst, Surface, args[5]); INTARG(dx, 6); INTARG(dy, 7); INTARG(dw, 8); INTARG(dh, 9); SDL_Rect srcRect = { .x = sx, .y = sy, .w = sw, .h = sh }; SDL_Rect dstRect = { .x = dx, .y = dy, .w = dw, .h = dh }; if (SDL_LowerBlitScaled(src->surface_, &srcRect, dst->surface_, &dstRect) != 0) { THROW_SDL_ERROR(); } } METHOD(MustLock) { BEGIN(); UNWRAP(surface, Surface, args[0]); RETURN(MK_BOOL(SDL_MUSTLOCK(surface->surface_))); } METHOD(SaveBMP) { BEGIN(); UNWRAP(surface, Surface, args[0]); STRINGARG(file, 1); if (SDL_SaveBMP(surface->surface_, *file) < 0) { THROW_SDL_ERROR(); } } METHOD(SetClipRect) { BEGIN(); UNWRAP(surface, Surface, args[0]); OBJECTARG(rect, 1); SDL_Rect sdlRect; extractRect(isolate, rect, &sdlRect); RETURN(MK_BOOL(SDL_SetClipRect(surface->surface_, &sdlRect))); } METHOD(SetColorKey) { BEGIN(); UNWRAP(surface, Surface, args[0]); BOOLARG(enable, 1); UINT32ARG(color, 2); if (SDL_SetColorKey(surface->surface_, enable ? SDL_TRUE : SDL_FALSE, color) < 0) { THROW_SDL_ERROR(); } } METHOD(SetSurfaceAlphaMod) { BEGIN(); UNWRAP(surface, Surface, args[0]); UINT32ARG(alphaMod, 1); if (SDL_SetSurfaceAlphaMod(surface->surface_, alphaMod) < 0) { THROW_SDL_ERROR(); } } METHOD(SetSurfaceBlendMode) { BEGIN(); UNWRAP(surface, Surface, args[0]); INTARG(blendMode, 1); if (SDL_SetSurfaceBlendMode(surface->surface_, (SDL_BlendMode)blendMode) < 0) { THROW_SDL_ERROR(); } } METHOD(SetSurfaceColorMod) { BEGIN(); UNWRAP(surface, Surface, args[0]); INTARG(r, 1); INTARG(g, 2); INTARG(b, 3); if (SDL_SetSurfaceColorMod(surface->surface_, r, g, b) < 0) { THROW_SDL_ERROR(); } } METHOD(SetSurfaceRLE) { BEGIN(); UNWRAP(surface, Surface, args[0]); INTARG(flag, 1); if (SDL_SetSurfaceRLE(surface->surface_, flag) < 0) { THROW_SDL_ERROR(); } } METHOD(UnlockSurface) { BEGIN(); UNWRAP(surface, Surface, args[0]); SDL_UnlockSurface(surface->surface_); } void InitSurfaceDrawingFunctions(Local<Object> exports) { NODE_SET_METHOD(exports, "blitScaled", BlitScaled); NODE_SET_METHOD(exports, "blitScaledCmp", BlitScaledCmp); NODE_SET_METHOD(exports, "blitSurface", BlitSurface); NODE_SET_METHOD(exports, "blitSurfaceAtPoint", BlitSurfaceAtPoint); NODE_SET_METHOD(exports, "convertPixels", ConvertPixels); NODE_SET_METHOD(exports, "convertSurfaceFormat", ConvertSurfaceFormat); NODE_SET_METHOD(exports, "createRGBSurface", CreateRGBSurface); NODE_SET_METHOD(exports, "createRGBSurfaceWithFormat", CreateRGBSurfaceWithFormat); NODE_SET_METHOD(exports, "fillRect", FillRect); NODE_SET_METHOD(exports, "fillRects", FillRect); NODE_SET_METHOD(exports, "getClipRect", GetClipRect); NODE_SET_METHOD(exports, "getColorKey", GetColorKey); NODE_SET_METHOD(exports, "getSurfaceAlphaMod", GetSurfaceAlphaMod); NODE_SET_METHOD(exports, "getSurfaceBlendMode", GetSurfaceBlendMode); NODE_SET_METHOD(exports, "getSurfaceColorMod", GetSurfaceColorMod); NODE_SET_METHOD(exports, "loadBMP", LoadBMP); NODE_SET_METHOD(exports, "lockSurface", LockSurface); NODE_SET_METHOD(exports, "lowerBlit", LowerBlit); NODE_SET_METHOD(exports, "lowerBlitAtPoint", LowerBlitAtPoint); NODE_SET_METHOD(exports, "lowerBlitScaled", LowerBlitScaled); NODE_SET_METHOD(exports, "lowerBlitScaledCmp", LowerBlitScaledCmp); NODE_SET_METHOD(exports, "mustLock", MustLock); NODE_SET_METHOD(exports, "saveBMP", SaveBMP); NODE_SET_METHOD(exports, "setClipRect", SetClipRect); NODE_SET_METHOD(exports, "setColorKey", SetColorKey); NODE_SET_METHOD(exports, "setSurfaceAlphaMod", SetSurfaceAlphaMod); NODE_SET_METHOD(exports, "setSurfaceBlendMode", SetSurfaceBlendMode); NODE_SET_METHOD(exports, "setSurfaceColorMod", SetSurfaceColorMod); NODE_SET_METHOD(exports, "setSurfaceRLE", SetSurfaceRLE); NODE_SET_METHOD(exports, "unlockSurface", UnlockSurface); } }
jaz303/node-sdl2-bindings
src/functions/surface_drawing.cc
C++
mit
11,676
# frozen_string_literal: true require 'test_helper' class ExpectedRandomizationTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
remomueller/slice
test/models/expected_randomization_test.rb
Ruby
mit
166
using System; using System.Collections.Generic; using System.Linq; using System.IO; public class OddLInes { static void Main() { string[] textLines = File.ReadAllLines("input.txt"); List<string> oddLines = new List<string>(); for (int i = 0; i < textLines.Length; i++) { if (i % 2 == 0) { oddLines.Add(textLines[i]); } } File.WriteAllLines("output.txt", oddLines); } }
komitoff/Softuni-Programming-Fundamentals
FilesAndExceptions_Lab/E1.OddLines/OddLInes.cs
C#
mit
488
Rickshaw.namespace('Rickshaw.Graph.Axis.Y.Scaled'); Rickshaw.Graph.Axis.Y.Scaled = Rickshaw.Class.create( Rickshaw.Graph.Axis.Y, { initialize: function($super, args) { if (typeof(args.scale) === 'undefined') { throw new Error('Scaled requires scale'); } this.scale = args.scale; if (typeof(args.grid) === 'undefined') { this.grid = true; } else { this.grid = args.grid; } $super(args); }, _drawAxis: function($super, scale) { // Adjust scale's domain to compensate for adjustments to the // renderer's domain (e.g. padding). var domain = this.scale.domain(); var renderDomain = this.graph.renderer.domain().y; var extents = [ Math.min.apply(Math, domain), Math.max.apply(Math, domain)]; // A mapping from the ideal render domain [0, 1] to the extent // of the original scale's domain. This is used to calculate // the extents of the adjusted domain. var extentMap = d3.scaleLinear().domain([0, 1]).range(extents); var adjExtents = [ extentMap(renderDomain[0]), extentMap(renderDomain[1])]; // A mapping from the original domain to the adjusted domain. var adjustment = d3.scaleLinear().domain(extents).range(adjExtents); // Make a copy of the custom scale, apply the adjusted domain, and // copy the range to match the graph's scale. var adjustedScale = this.scale.copy() .domain(domain.map(adjustment)) .range(scale.range()); return $super(adjustedScale); }, _drawGrid: function($super, axis) { if (this.grid) { // only draw the axis if the grid option is true $super(axis); } } } );
butterflyhug/rickshaw
src/js/Rickshaw.Graph.Axis.Y.Scaled.js
JavaScript
mit
1,679
//Here is all the code that builds the list of objects on the right-hand //side of the Labelme tool. //The styles for this tools are defined inside: //annotationTools/css/object_list.css var IsHidingAllPolygons = false; var ProgressChecking = false; //var IsHidingAllFilled = true; var ListOffSet = 0; //This function creates and populates the list function RenderObjectList() { // If object list has been rendered, then remove it: var scrollPos = $("#anno_list").scrollTop(); if($('#anno_list').length) { $('#anno_list').remove(); } var html_str = '<div class="object_list" id="anno_list" style="border:0px solid black;z-index:0;" ondrop="drop(event, -1)" ondragenter="return dragEnter(event)" ondragover="return dragOver(event)">'; var Npolygons = LMnumberOfObjects(LM_xml); // name of image html_str += '<p style="font-size:14px;line-height:100%"><h>Image: <a href="javascript:GetThisURL();">'+main_media.file_info.im_name+'</a></h></p>'; if (!ProgressChecking){ //Checks progress by filling all polygons html_str += '<p style="font-size:12px;line-height:50%" id="check_progress" ><a href="javascript:CheckProgress();"><b>Check progress</b></a> (s)</p>'; } else {//Clear Progress check html_str += '<p style="font-size:12px;line-height:50%" id="end_check_progress"><a href="javascript:EndCheckProgress();" style="color:red"><b>Clear progress check</b></a> (h)</p>'; } if (IsHidingAllPolygons){ //Polygons hidden, press to show outlines permanently html_str += '<p style="font-size:12px;line-height:50%"><a id="hold_poly" href="javascript:ShowAllPolygons();"><b>Press to hold outlines</b></a></p>'; } else { //Outlines held status msg html_str += '<p style="font-size:12px;line-height:50%"><a id="poly_held" style="text-decoration:none; font-style:italic; color:#708090;">Outlines held (\'Hide all\' to release)</a></p>'; } //Hide all polygons html_str += '<p style="font-size:12px;line-height:50%"><a id="hide_all" href="javascript:HideAllPolygons();"><b>Hide all </b></a></p>'; // Create DIV html_str += '<u><i>'+ Npolygons +'</i> classes labeled in all:</u>'; html_str += '<ol>'; for(var i=0; i < Npolygons; i++) { html_str += '<div class="objectListLink" id="LinkAnchor' + i + '" style="z-index:1; margin-left:0em"> '; html_str += '<li>'; // show object name: html_str += '<a class="objectListLink" id="Link' + i + '" '+ 'href="javascript:main_handler.AnnotationLinkClick('+ i +');" '+ 'onmouseover="main_handler.AnnotationLinkMouseOver('+ i +');" ' + 'onmouseout="main_handler.AnnotationLinkMouseOut();" '; html_str += '>'; var obj_name = LMgetObjectField(LM_xml,i,'name'); html_str += obj_name; html_str += '</a>'; html_str += '</li></div>'; } html_str += '</ol><p><br/></p></div>'; // Attach annotation list to 'anno_anchor' DIV element: $('#anno_anchor').append(html_str); $('#Link'+add_parts_to).css('font-weight',700); // $('#anno_list').scrollTop(scrollPos); } function RemoveObjectList() { $('#anno_list').remove(); } function ChangeLinkColorBG(idx) { if(document.getElementById('Link'+idx)) { var isDeleted = parseInt($(LM_xml).children("annotation").children("object").eq(idx).children("deleted").text()); if(isDeleted) document.getElementById('Link'+idx).style.color = '#888888'; else document.getElementById('Link'+idx).style.color = '#0000FF'; var anid = main_canvas.GetAnnoIndex(idx); // If we're hiding all polygons, then remove rendered polygon from canvas: if(IsHidingAllPolygons && main_canvas.annotations[anid].hidden) { main_canvas.annotations[anid].DeletePolygon(); } } } function ChangeLinkColorFG(idx) { document.getElementById('Link'+idx).style.color = '#FF0000'; var anid = main_canvas.GetAnnoIndex(idx); // If we're hiding all polygons, then render polygon on canvas: if(IsHidingAllPolygons && main_canvas.annotations[anid].hidden) { main_canvas.annotations[anid].DrawPolygon(main_media.GetImRatio(), main_canvas.annotations[anid].GetPtsX(), main_canvas.annotations[anid].GetPtsY()); } } function HideAllPolygons() { if(!edit_popup_open) { IsHidingAllPolygons = true; ProgressChecking = false; // Delete all polygons from the canvas: for(var i = 0; i < main_canvas.annotations.length; i++) { main_canvas.annotations[i].DeletePolygon(); main_canvas.annotations[i].hidden = true; } // Create "show all" button: $('#poly_held').replaceWith('<a id="hold_poly" href="javascript:ShowAllPolygons();"><b>Press to hold outlines</b></a>'); $('#end_check_progress').replaceWith('<p style="font-size:12px;line-height:50%" id="check_progress" ><a href="javascript:CheckProgress();"><b>Check progress</b></a> (s)</p>'); } else { alert('Close edit popup bubble first'); } } function ShowAllPolygons() { if (ProgressChecking) return; //hold outline setting not allowed to be trigger when progress checking ongoing // Set global variable: IsHidingAllPolygons = false; ProgressChecking = false; // Render the annotations: main_canvas.UnhideAllAnnotations(); main_canvas.RenderAnnotations(); // swap hold poly with poly held $('#hold_poly').replaceWith('<a id="poly_held" style="text-decoration:none; font-style:italic; color:#708090;">Outlines held (\'Hide all\' to release)</a>'); } function CheckProgress() { ProgressChecking = true; //clear all polygons first if(!edit_popup_open) { // Delete all polygons from the canvas: for(var i = 0; i < main_canvas.annotations.length; i++) { main_canvas.annotations[i].DeletePolygon(); main_canvas.annotations[i].hidden = true; } } else { alert('Close edit popup bubble first'); } //reset annotations to take into account user editting labels while checking progress. main_canvas.annotations.length = 0; // Attach valid annotations to the main_canvas: for(var pp = 0; pp < LMnumberOfObjects(LM_xml); pp++) { // Attach to main_canvas: main_canvas.AttachAnnotation(new annotation(pp)); if (!video_mode && LMgetObjectField(LM_xml, pp, 'x') == null){ main_canvas.annotations[main_canvas.annotations.length -1].SetType(1); main_canvas.annotations[main_canvas.annotations.length -1].scribble = new scribble(pp); } } // Render the annotations: main_canvas.UnhideAllAnnotations(); main_canvas.RenderAnnotations(); //Fill all for (var i= 0; i < LMnumberOfObjects(LM_xml); i++){ main_canvas.annotations[i].FillPolygon(); } console.log("check progress"); // Create "hide all" button: $('#show_all_filled_button').replaceWith('<a id="hide_all_filled_button" href="javascript:HideAllFilled();">Hide back</a>'); $('#check_progress').replaceWith('<p style="font-size:12px;line-height:50%" id="end_check_progress"><a href="javascript:EndCheckProgress();" style="color:red"><b>Clear progress check</b></a> (h)</p>'); } function EndCheckProgress() { if(!edit_popup_open) { ProgressChecking = false; if(IsHidingAllPolygons){ // Delete all polygons from the canvas: for(var i = 0; i < main_canvas.annotations.length; i++) { main_canvas.annotations[i].DeletePolygon(); main_canvas.annotations[i].hidden = true; } } else {//if we are holding all polygons for(var i = 0; i < main_canvas.annotations.length; i++) { main_canvas.annotations[i].UnfillPolygon(); } } console.log("end check progress"); // Create "show all" button: $('#end_check_progress').replaceWith('<p style="font-size:12px;line-height:50%" id="check_progress" ><a href="javascript:CheckProgress();"><b>Check progress</b></a> (s)</p>'); } else { alert('Close edit popup bubble first'); } } //******************************************* //Private functions: //******************************************* //DRAG FUNCTIONS function drag(event, part_id) { // stores the object id in the data that is being dragged. event.dataTransfer.setData("Text", part_id); } function dragend(event, object_id) { event.preventDefault(); // Write XML to server: WriteXML(SubmitXmlUrl,LM_xml,function(){return;}); } function dragEnter(event) { event.preventDefault(); return true; } function dragOver(event) { event.preventDefault(); } function drop(event, object_id) { event.preventDefault(); var part_id=event.dataTransfer.getData("Text"); event.stopPropagation(); // modify part structure if(object_id!=part_id) { addPart(object_id, part_id); // redraw object list RenderObjectList(); } }
levan92/uLabel
annotationTools/js/object_list.js
JavaScript
mit
8,435
<?php namespace WebLoader\Nette; use Nette\DI\Container; use Nette\Http\IRequest; use WebLoader\Compiler; class LoaderFactory { /** @;var IRequest */ private $httpRequest; /** @var Container */ private $serviceLocator; /** @var array */ private $tempPaths; /** * @param array $tempPaths * @param IRequest $httpRequest * @param Container $serviceLocator */ public function __construct(array $tempPaths, IRequest $httpRequest, Container $serviceLocator) { $this->httpRequest = $httpRequest; $this->serviceLocator = $serviceLocator; $this->tempPaths = $tempPaths; } /** * @param string $name * @return \WebLoader\Nette\CssLoader */ public function createCssLoader($name) { /** @var Compiler $compiler */ $compiler = $this->serviceLocator->getService('webloader.css' . ucfirst($name) . 'Compiler'); return new CssLoader($compiler, $this->formatTempPath($name)); } /** * @param string $name * @return \WebLoader\Nette\JavaScriptLoader */ public function createJavaScriptLoader($name) { /** @var Compiler $compiler */ $compiler = $this->serviceLocator->getService('webloader.js' . ucfirst($name) . 'Compiler'); return new JavaScriptLoader($compiler, $this->formatTempPath($name)); } /** * @param string $name * @return string */ private function formatTempPath($name) { $lName = strtolower($name); $tempPath = isset($this->tempPaths[$lName]) ? $this->tempPaths[$lName] : Extension::DEFAULT_TEMP_PATH; return rtrim($this->httpRequest->getUrl()->basePath, '/') . '/' . $tempPath; } }
Jecma/JecmaBlog
vendor/janmarek/webloader/WebLoader/Nette/LoaderFactory.php
PHP
mit
1,559
// The MIT License (MIT) // // CoreTweet - A .NET Twitter Library supporting Twitter API 1.1 // Copyright (c) 2013-2015 CoreTweet Development Team // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace CoreTweet { /// <summary> /// Twitter parameter attribute. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class TwitterParameterAttribute : Attribute { /// <summary> /// Name of the parameter binding for. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Default value of the parameter. /// </summary> /// <value>The default value.</value> public object DefaultValue { get; set; } /// <summary> /// Initializes a new instance of the <see cref="CoreTweet.TwitterParameterAttribute"/> class. /// </summary> /// <param name="name">Name.</param> /// <param name="defaultValue">Default value.</param> public TwitterParameterAttribute(string name = null, object defaultValue = null) { Name = name; DefaultValue = defaultValue; } } /// <summary> /// Twitter parameters attribute. /// This is used for a class. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class TwitterParametersAttribute : Attribute {} }
haripo/CoreTweet
CoreTweet.Shared/Attribute.cs
C#
mit
2,476
define([ "knockout", // mappoint needs to be here first for addEventListener "../modules/mappoint", ], function (ko) { // create result object var result = { cityname : ko.observable(''), citydata : ko.observableArray([]) }; // subscribe to custom event window.addEventListener("getTitle", getWikipedia, false); // use for jsonp call to wikipedia var city ='', // oldValue oldValue = ''; // call function function getWikipedia (e) { // listen to custom event city = e.detail.title; // store data object var data = ''; // if city equals old value do nothing if (city === oldValue) { // do something when element is clicked twice console.log("you have allready clicked this " + city + " marker"); } // if city contains new value else { // check if city is in LocalStorage if (localStorage[city]) { // get localstorage item and store it data = JSON.parse(localStorage[city]); // populate observables result.citydata([data]); result.cityname(city); } else { // if no localstorage, sent request sentJSONPRequest(city); } // set city to old value oldValue = city; } } // found jsonp solution for wikipedia after trying it many times with xmlhttprequest and cors function jsonp(url, callback) { var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random()); // create callback and delete it window[callbackName] = function(data) { delete window[callbackName]; document.body.removeChild(script); callback(data); }; // add script var script = document.createElement('script'); script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName; // simple error handling (works in firefox and chrome) window.onerror = function (errorMsg, url, lineNumber) { alert('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber); }; document.body.appendChild(script); } // set api url var sentJSONPRequest = function (city) { // set url for jsonp request var url = 'http://en.wikipedia.org/w/api.php?action=opensearch&search=' + city + '&format=json&callback=?'; // call jsonp request jsonp(url, function(data) { // fill result with wikipedia object result.citydata([data[1]]); // use change in city for observable result.cityname(data[0]); // if localstorage support if (window.localStorage) { // store city object with data array localStorage[data[0]] = JSON.stringify(data[1]); } }); }; return result; });
JSchermers/neighborhoodmap
scripts/modules/api-call-wikipedia.js
JavaScript
mit
2,610
require 'spec_helper' describe Scraper do describe "#todos" do it "should return an array of Todo objects given a file" do path = File.dirname(__FILE__) + '/example' todos = Scraper.todos(path) todos.length.should == 2 end end end
Dillon-Benson/todo-reminder
spec/todo_reminder/scraper_spec.rb
Ruby
mit
262
class Solution { public: int minMoves(vector<int>& nums) { sort(nums.begin(), nums.end()); int ans = 0; for(int i = 1; i < nums.size(); i++){ ans += nums[i] - nums[0]; } return ans; } };
zfang399/LeetCode-Problems
453.cpp
C++
mit
247
// Copyright 2012 Room77, Inc. // Author: Uygar Oztekin #include "base/common.h" // intercept memory allocation failures and force a stack trace struct InitNewHandler { static void NewHandler () { cout << "\n*** Memory allocation Failed! About to segfault ***" << endl; // Cause a segfault. void* ptr = nullptr; // Create a var to get around enabled compiler warning. *static_cast<int*>(ptr) = 0; } InitNewHandler() { set_new_handler(InitNewHandler::NewHandler); } } auto_init_new_handler;
room77/77up
public/util/memory/new_handler.cc
C++
mit
514
namespace HockeyApp.DataExchange.Contracts { public interface IArenaImportService : IImportService { } }
ekonor/hokeyapp
net47/HockeyApp/HockeyApp.DataExchange/Contracts/IArenaImportService.cs
C#
mit
120
angular.module( 'remote.xbmc-service' , [] ) .service( 'XBMCService', function( $log,$http,Storage ){ //http://kodi.wiki/view/JSON-RPC_API/v6 var XBMC = this, settings = (new Storage("settings")).get(); url = 'http://' + settings.ip + '/', command = {id: 1, jsonrpc: "2.0" }; //url = 'http://localhost:8200/' function cmd(){ return _.cloneDeep( command ); } function sendRequest( data ){ $log.debug("Sending " , data , " to " , url + 'jsonrpc'); return $http.post( url + 'jsonrpc' , data ); } XBMC.sendText = function( text ){ var data = cmd(); data.params = { method: "Player.SendText", item: { text: text, done: true } }; return sendRequest( data ); } XBMC.input = function( what ){ var data = cmd(); switch( what ){ case 'back': data.method = "Input.Back"; break; case 'left': data.method = "Input.Left"; break; case 'right': data.method = "Input.right"; break; case 'up': data.method = "Input.Up"; break; case 'down': data.method = "Input.Down"; break; case 'select': data.method = "Input.Select"; break; case 'info': data.method = "Input.Info"; break; case 'context': data.method = "Input.ContextMenu"; break; } return sendRequest( data ); } XBMC.sendToPlayer = function( link ){ var data = cmd(); data.params = { method: "Player.Open", item: { file: link } }; return sendRequest( data ); } })
jamesanewman/remote-control
src/app/shared/xbmc.js
JavaScript
mit
1,448
#include "Calc.hpp" #include <cmath> #define PI 3.14159265 float Calc::radToDeg(float rad) { return rad * ( 180.f / PI); } float Calc::degToRad(float deg) { return deg * (PI / 180.f); } /* * Rotation around origin: * rotation matrix P * ( x' ) = ( cos a -sin a ) * ( x ) = cos a * x - sin a * y * ( y' ) ( sin a cos a ) ( y ) = sin a * x + cos a * y * Our Coordinate system has other axes (reversed y Axes) * So the rotation matrix is different: * * ( x' ) = ( cos a sin a ) * ( x ) = cos a * x + sin a * y * ( y' ) (-sin a cos a ) ( y ) =-sin a * x + cos a * y * * Rotation around specific Point: * The Point we want to rotate is called P and the point we * rotate around is called T. * -> -> * rotation matrix Vector: TP Vector: OT * ( x' ) = ( cos a -sin a ) * ( xp - xt) + ( xt ) * ( y' ) ( sin a cos a ) ( yp - yt) ( yt ) * ==> * x' = (cos a * (xp - xt) - sin a * (yp - yt)) + xt * y' = (sin a * (xp - xt) + cos a * (yp - yt)) + yt * In our coordinate system with the custom rotation matrix: * x' = ( cos a * (xp - xt) + sin a * (yp - yt)) + xt * y' = (-sin a * (xp - xt) + cos a * (yp - yt)) + yt * */ sf::Vector2f Calc::rotatePointAround(const sf::Vector2f Point, const sf::Vector2f TargetPoint, const float AngleDegree) { // First we need the angle in radians instead if degrees const float Angle = ( PI / 180) * AngleDegree; const float Xp = Point.x; const float Yp = Point.y; const float Xt = TargetPoint.x; const float Yt = TargetPoint.y; // Rotate the Point const float Xnew = ( ( std::cos(Angle) * (Xp - Xt) + std::sin(Angle) * (Yp - Yt) ) + Xt ); const float Ynew = ( (-std::sin(Angle) * (Xp - Xt) + std::cos(Angle) * (Yp - Yt) ) + Yt ); return { Xnew, Ynew }; } float Calc::clamp(const float Value, const float MinValue, const float MaxValue) { return std::max(MinValue, std::min(MaxValue, Value)); } sf::Vector2f Calc::degAngleToDirectionVector(float angle) { float angleRad{ degToRad(angle) }; float x{ std::cos(angleRad) }; float y{ std::sin(angleRad) }; return { x, y }; }
TmCrafz/ArenaSFML
src/Calc.cpp
C++
mit
2,165
# frozen_string_literal: true # Migration to create the `schedules` table used by Schedulable class CreateSchedules < ActiveRecord::Migration[5.1] def self.up create_table :schedules do |t| t.references :schedulable, polymorphic: true t.date :date t.time :time t.string :rule t.string :interval t.text :day t.text :day_of_week t.datetime :until t.integer :count t.timestamps end end def self.down drop_table :schedules end end
gemvein/date_book
db/migrate/20170807133847_create_schedules.rb
Ruby
mit
514
import Ember from "ember"; import { module, test } from 'qunit'; import startApp from '../helpers/start-app'; import { authenticateSession } from 'code-corps-ember/tests/helpers/ember-simple-auth'; import indexPage from '../pages/index'; let application; module('Acceptance: Logout', { beforeEach: function() { application = startApp(); }, afterEach: function() { Ember.run(application, 'destroy'); } }); test("Logging out", function(assert) { assert.expect(2); let user = server.create('user'); authenticateSession(application, { user_id: user.id }); indexPage.visit(); andThen(function() { assert.equal(indexPage.navMenu.userMenu.logOut.text, "Log out", "Page contains logout link"); indexPage.navMenu.userMenu.logOut.click(); }); andThen(function() { assert.equal(indexPage.navMenu.logIn.text, "Sign in", "Page contains login link"); }); });
eablack/code-corps-ember
tests/acceptance/logout-test.js
JavaScript
mit
892
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NXDO.RJava.Attributes { /// <summary> /// 标识 java 接口的类型名称。 /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public class JInterfaceAttribute : JClassAttribute { /// <summary> /// 设置 java 接口的类型名称 /// </summary> /// <param name="jInterfaceName">java 接口的类型名称</param> public JInterfaceAttribute(string jInterfaceName) : base(jInterfaceName) { } } /// <summary> /// 标识 java 类型名称,仅用于接口的实现。 /// <para>标识的 java 类型必须具无参的公共默认构造函数。</para> /// </summary> [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = true)] public class JEmitAttribute : JInterfaceAttribute { /// <summary> /// 标识 java 类型名称,用于接口实现 /// </summary> /// <param name="javaClassName"></param> public JEmitAttribute(string javaClassName) : base(javaClassName) { } } }
javasuki/RJava
NXDO.Mixed.V2015/NXDO.RJava/Attributes/JInterfaceAttribute.cs
C#
mit
1,248
<?php namespace Site\MainBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; use Symfony\Component\Validator\Constraints as Assert; /** * Site\MainBundle\Entity\ModuleMap * * @ORM\Table(name="module_map") * @ORM\Entity(repositoryClass="Site\MainBundle\Entity\Repository\ModuleMapRepository") */ class ModuleMap { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="text", nullable=true) */ protected $code; /** * @ORM\Column(type="text", nullable=true) */ protected $height; /** * @ORM\Column(type="boolean", nullable=true) */ protected $enable = true; /** * @ORM\OneToOne(targetEntity="Level", inversedBy="moduleMap", cascade={"persist", "remove"}) * @ORM\JoinColumn(name="level_id", referencedColumnName="id", nullable=true, onDelete="SET NULL") */ protected $level; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set code * * @param string $code * @return ModuleMap */ public function setCode($code) { $this->code = $code; return $this; } /** * Get code * * @return string */ public function getCode() { return $this->code; } /** * Set enable * * @param boolean $enable * @return ModuleMap */ public function setEnable($enable) { $this->enable = $enable; return $this; } /** * Get enable * * @return boolean */ public function getEnable() { return $this->enable; } /** * Set level * * @param \Site\MainBundle\Entity\Level $level * @return ModuleMap */ public function setLevel(\Site\MainBundle\Entity\Level $level = null) { $this->level = $level; return $this; } /** * Get level * * @return \Site\MainBundle\Entity\Level */ public function getLevel() { return $this->level; } /** * Set height * * @param string $height * @return ModuleMap */ public function setHeight($height) { $this->height = $height; return $this; } /** * Get height * * @return string */ public function getHeight() { return $this->height; } }
olegfox/landing
src/Site/MainBundle/Entity/ModuleMap.php
PHP
mit
2,549
var data = {videos-content: {}}
ulabspro/ilq
markup/components/videos-content/data/data.js
JavaScript
mit
31
(function ($) { // Navigation scrolls $('.navbar-nav li a').bind('click', function (event) { $('.navbar-nav li').removeClass('active'); $(this).closest('li').addClass('active'); var $anchor = $(this); var nav = $($anchor.attr('href')); if (nav.length) { $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); } }); // About section scroll $(".overlay-detail a").on('click', function (event) { event.preventDefault(); var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top }, 900, function () { window.location.hash = hash; }); }); //jQuery to collapse the navbar on scroll $(window).scroll(function () { if ($(".navbar-default").offset().top > 40) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); $('.navbar-collapse').on('show.bs.collapse', function () { $(".navbar-fixed-top").addClass("top-nav-collapse-shadow"); }) $('.navbar-collapse').on('hide.bs.collapse', function () { $(".navbar-fixed-top").removeClass("top-nav-collapse-shadow"); }) })(jQuery);
danurwenda/mariteam
dist/js/public/custom.js
JavaScript
mit
1,422
/* * PhraseService.java * * Copyright (C) 2018 [ A Legge Up ] * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ package com.aleggeup.confagrid.content; import java.util.List; import java.util.UUID; import com.aleggeup.confagrid.model.Phrase; public interface PhraseService { List<Phrase> findAll(); void save(Phrase phrase); Phrase phraseFromText(String text); long count(); Phrase findOne(UUID id); }
ALeggeUp/confagrid
application/confagrid-webapp/src/main/java/com/aleggeup/confagrid/content/PhraseService.java
Java
mit
514
import util from 'util' import mongoose from 'mongoose' import seedData from '../seedData' const debug = require('debug')('api:server:db') mongoose.Promise = require('bluebird') const host = process.env.MONGO_HOST || 'localhost' const database = process.env.MONGO_DATABASE || 'admin' const port = process.env.MONGO_PORT || 27017 const url = `mongodb://${host}:${port}/${database}` const configureMongo = () => { debug(`connecting to ${url}...`) mongoose.connect(url).then( () => seedData(), err => { debug(`unable to connect to database: ${err}`) setTimeout(configureMongo, 5000) } ) if (process.env.MONGO_DEBUG) { mongoose.set('debug', (collectionName, method, query, doc) => { debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc); }); } } export default configureMongo
ameier38/mindhypertrophy-api
src/server/db.js
JavaScript
mit
893
package cs2020; public interface IMazeSolverWithPower extends IMazeSolver { /** * Finds the shortest path from a given starting coordinate to an * ending coordinate with a fixed number of Powers given * * @param startRow * @param startCol * @param endRow * @param endCol * @param superpowers * @return minimum moves from start to end * @return null if there is no path from start to end * @throws Exception */ Integer pathSearch(int startRow, int startCol, int endRow, int endCol, int superpowers) throws Exception; }
burnflare/cs2020
Ps7/src/cs2020/IMazeSolverWithPower.java
Java
mit
569
package com.lms.dao; import java.util.List; import com.lms.jpa.Person; public interface DAOPerson { public boolean personExist(long personId); public void insertPerson(Person person); public void updatePerson(Person person); public void deletePerson(long personId); public Person fetchPersonInfo(long personId); public List<Person> fetchAllPerson(); }
deepshah22/spring-mvc
src/main/java/com/lms/dao/DAOPerson.java
Java
mit
410
import * as type from '../../../src/validators/type'; describe('type Unit Tests', () => { describe('isArray method', () => { describe('when the node does not exist in the package.json file', () => { test('true should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isArray(packageJson, 'devDependencies'); expect(response).toBe(true); }); }); describe('when the node exists in the package.json file and it is a string', () => { test('false should be returned', () => { const packageJson = { name: 'awesome-module', }; const response = type.isArray(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is a boolean', () => { test('false should be returned', () => { const packageJson = { name: true, }; const response = type.isArray(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is an object', () => { test('false should be returned', () => { const packageJson = { name: {}, }; const response = type.isArray(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is an array', () => { test('true should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isArray(packageJson, 'name'); expect(response).toBe(true); }); }); }); describe('isBoolean method', () => { describe('when the node does not exist in the package.json file', () => { test('true should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isBoolean(packageJson, 'devDependencies'); expect(response).toBe(true); }); }); describe('when the node exists in the package.json file and it is a string', () => { test('false should be returned', () => { const packageJson = { name: 'awesome-module', }; const response = type.isBoolean(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is a boolean', () => { test('true should be returned', () => { const packageJson = { name: true, }; const response = type.isBoolean(packageJson, 'name'); expect(response).toBe(true); }); }); describe('when the node exists in the package.json file and it is an object', () => { test('false should be returned', () => { const packageJson = { name: {}, }; const response = type.isBoolean(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is an array', () => { test('false should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isBoolean(packageJson, 'name'); expect(response).toBe(false); }); }); }); describe('isObject method', () => { describe('when the node does not exist in the package.json file', () => { test('true should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isObject(packageJson, 'devDependencies'); expect(response).toBe(true); }); }); describe('when the node exists in the package.json file and it is a string', () => { test('false should be returned', () => { const packageJson = { name: 'awesome-module', }; const response = type.isObject(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is a boolean', () => { test('false should be returned', () => { const packageJson = { name: true, }; const response = type.isObject(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is an object', () => { test('true should be returned', () => { const packageJson = { name: {}, }; const response = type.isObject(packageJson, 'name'); expect(response).toBe(true); }); }); describe('when the node exists in the package.json file and it is an array', () => { test('false should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isObject(packageJson, 'name'); expect(response).toBe(false); }); }); }); describe('isString method', () => { describe('when the node does not exist in the package.json file', () => { test('true should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isString(packageJson, 'devDependencies'); expect(response).toBe(true); }); }); describe('when the node exists in the package.json file and it is a string', () => { test('true should be returned', () => { const packageJson = { name: 'awesome-module', }; const response = type.isString(packageJson, 'name'); expect(response).toBe(true); }); }); describe('when the node exists in the package.json file and it is a boolean', () => { test('false should be returned', () => { const packageJson = { name: true, }; const response = type.isString(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is an object', () => { test('false should be returned', () => { const packageJson = { name: {}, }; const response = type.isString(packageJson, 'name'); expect(response).toBe(false); }); }); describe('when the node exists in the package.json file and it is an array', () => { test('false should be returned', () => { const packageJson = { name: ['awesome-module'], }; const response = type.isString(packageJson, 'name'); expect(response).toBe(false); }); }); }); });
tclindner/npm-package-json-lint
test/unit/validators/type.test.ts
TypeScript
mit
6,774
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); // GA tracking document.write('<script async src="https://www.googletagmanager.com/gtag/js?id=UA-64617433-10"></script><script>window.dataLayer = window.dataLayer || [];function gtag(){dataLayer.push(arguments);}gtag(\'js\', new Date()); gtag(\'config\', \'UA-64617433-10\'); </script>'); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err));
engagementgamelab/hygiene-with-chhota-bheem
website/client/src/main.ts
TypeScript
mit
669
package com.valarion.gameengine.events.menu.battlemenu; public interface ToolTip { public String getToolTip(); }
valarion/JAGE
JAGEgradle/JAGEmodules/src/main/java/com/valarion/gameengine/events/menu/battlemenu/ToolTip.java
Java
mit
120
// // LoginViewController.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2022 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using MonoTouch.Dialog; using UIKit; namespace ImapClientDemo.iOS { public class LoginViewController : DialogViewController { readonly EntryElement hostEntry, portEntry, userEntry, passwordEntry; readonly FoldersViewController foldersViewController; readonly CheckboxElement sslCheckbox; public LoginViewController () : base (UITableViewStyle.Grouped, null) { hostEntry = new EntryElement ("Host", "imap.gmail.com", "imap.gmail.com"); portEntry = new EntryElement ("Port", "993", "993") { KeyboardType = UIKeyboardType.NumberPad }; sslCheckbox = new CheckboxElement ("Use SSL", true); userEntry = new EntryElement ("Username", "Email / Username", ""); passwordEntry = new EntryElement ("Password", "password", "", true); Root = new RootElement ("IMAP Login") { new Section ("Server") { hostEntry, portEntry, sslCheckbox }, new Section ("Account") { userEntry, passwordEntry }, new Section { new StyledStringElement ("Login", Login) } }; foldersViewController = new FoldersViewController (); } async void Login () { hostEntry.FetchValue (); portEntry.FetchValue (); userEntry.FetchValue (); passwordEntry.FetchValue (); int.TryParse (portEntry.Value, out var port); try { if (Mail.Client.IsConnected) await Mail.Client.DisconnectAsync (true); // Note: for demo purposes, we're ignoring SSL validation errors (don't do this in production code) Mail.Client.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; // Connect to server await Mail.Client.ConnectAsync (hostEntry.Value, port, sslCheckbox.Value); try { // Authenticate now that we're connected await Mail.Client.AuthenticateAsync (userEntry.Value, passwordEntry.Value); // Show the folders view controller NavigationController.PushViewController (foldersViewController, true); } catch (Exception aex) { Console.WriteLine (aex); Mail.MessageBox ("Authentication Error", "Failed to Authenticate to server. If you are using GMail, then you probably " + "need to go into your GMail settings to enable \"less secure apps\" in order " + "to get this demo to work.\n\n" + "For a real Mail application, you'll want to add support for obtaining the " + "user's OAuth2 credentials to prevent the need for user's to enable this, but " + "that is beyond the scope of this demo." ); } } catch (Exception ex) { Console.WriteLine (ex); Mail.MessageBox ("Connection Error", "Failed to connect to server."); } } } }
jstedfast/MailKit
samples/ImapClientDemo.iOS/ImapClientDemo.iOS/LoginViewController.cs
C#
mit
3,892
<div class="container"> <div class="row"> <div class="box"> <div class="col-sm-3 text-left"> <h3><?php echo $results; ?></h3> <p><?php echo $totalvotes.": ".$kokku_haali ?></p> <div class="btn-group-vertical" role="group" aria-label="Vertical button group" id="list"> <a class="btn btn-default" id="koik" href="#"><?php echo $wholecountry; ?></a> <div class="btn-group" role="group"> <button id="btnGroupVerticalDrop2" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><?php echo $chooseregion; ?><span class="caret"></span> </button> <ul class="dropdown-menu" id="piirkonnad" aria-labelledby="btnGroupVerticalDrop2"> <?php foreach($piirkonnad as $k){ echo "<li><a href='#piirkond=".$k->Piirkond."'>".$k->Piirkond."</a></li> "; } ?> </ul> </div> <div class="btn-group" role="group"> <button id="btnGroupVerticalDrop3" type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><?php echo $chooseparty; ?><span class="caret"></span> </button> <ul class="dropdown-menu" id = "erakonnad" aria-labelledby="btnGroupVerticalDrop3"> <?php foreach($erakonnad as $k){ echo "<li><a href='#erakond=".$k->Erakond."'>".$k->Erakond."</a></li> "; } ?> </ul> </div> </div> </div> <div class="col-sm-9 text-left" id="chart"> <!--<h3>Tulemused</h3>--> </div> <div class="col-sm-12 text-left"> <div class="panel panel-default"> <div class="panel-heading"> <div class="table-responsive"> <table id="tabel" class="table table-striped tablesorter"> <thead> <tr> <th><span class="glyphicon glyphicon-sort"></span><?php echo $number; ?></th> <th><span class="glyphicon glyphicon-sort-by-alphabet"></span><?php echo $name; ?></th> <th><span class="glyphicon glyphicon-sort-by-alphabet"></span><?php echo $party; ?></th> <th><span class="glyphicon glyphicon-sort-by-alphabet"></span><?php echo $region; ?></th> <th><span class="glyphicon glyphicon-sort"></span><?php echo $votes_lang; ?></th> </tr> </thead> <tbody class="searchable"> <?php foreach($kandidaadid as $k){ echo "<tr class=\"kandidaat\">"; echo "<td>".$k->Number."</td>"; echo "<td>".$k->Nimi."</td>"; echo "<td>".$k->Erakond."</td>"; echo "<td>".$k->Piirkond."</td>"; if(array_key_exists($k->Number,$haaled)) { echo "<td id=\"$k->Number\">".$haaled[$k->Number]."</td>"; } else { echo "<td>0</td>"; } echo "</tr>"; } ?> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> <!-- /.container -->
Kaspar94/evalimised2016
application/views/tulemused.php
PHP
mit
4,256
# encoding: utf-8 @via=#TODO your Username on the Twitter @link='#TODO your link to be shared' @title=#TODO your message title @message=#TODO your message on the share @hash_tags=#TODO your HashTags references JustShare.via=@via JustShare.link=CGI::unescape(@link) JustShare.title=@title JustShare.message=@message JustShare.hash_tags=@hash_tags
TonFw/just_share
lib/generators/templates/just_share.rb
Ruby
mit
346
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sylius\Bundle\CoreBundle\Model; use Doctrine\Common\Collections\Collection; use Sylius\Bundle\AddressingBundle\Model\ZoneInterface; use Sylius\Bundle\ShippingBundle\Model\ShippingCategoryInterface; use Sylius\Bundle\TaxationBundle\Model\TaxableInterface; use Sylius\Bundle\TaxationBundle\Model\TaxCategoryInterface; use Sylius\Bundle\VariableProductBundle\Model\VariableProductInterface; /** * Product interface. * * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl> */ interface ProductInterface extends VariableProductInterface, TaxableInterface { /** * Get product SKU. * * @return string */ public function getSku(); /** * {@inheritdoc} */ public function setSku($sku); /** * Get the variant selection method. * * @return string */ public function getVariantSelectionMethod(); /** * Set variant selection method. * * @param string $variantSelectionMethod */ public function setVariantSelectionMethod($variantSelectionMethod); /** * Check if variant is selectable by simple variant choice. * * @return Boolean */ public function isVariantSelectionMethodChoice(); /** * Get pretty label for variant selection method. * * @return string */ public function getVariantSelectionMethodLabel(); /** * Get taxons. * * @return Collection */ public function getTaxons(); /** * Set categorization taxons. * * @param Collection $taxons */ public function setTaxons(Collection $taxons); /** * Gets product price. * * @return integer $price */ public function getPrice(); /** * Sets product price. * * @param float $price */ public function setPrice($price); /** * Get product short description. * * @return string */ public function getShortDescription(); /** * Set product short description. * * @param string $shortDescription */ public function setShortDescription($shortDescription); /** * Set taxation category. * * @param TaxCategoryInterface $category */ public function setTaxCategory(TaxCategoryInterface $category = null); /** * Get product shipping category. * * @return ShippingCategoryInterface */ public function getShippingCategory(); /** * Set product shipping category. * * @param ShippingCategoryInterface $category */ public function setShippingCategory(ShippingCategoryInterface $category = null); /** * Get address zone restriction. * * @return ZoneInterface */ public function getRestrictedZone(); /** * Set address zone restriction. * * @param ZoneInterface $zone */ public function setRestrictedZone(ZoneInterface $zone = null); /** * Get all product images. * * @return Collection */ public function getImages(); /** * Get product main image. * * @return ImageInterface */ public function getImage(); /** * Get descuentos. * * @return Collection */ public function getDescuentos(); /** * Checks if product has descuento. * * @return Boolean */ public function hasDescuento(Descuento $descuento); /** * Add descuento. * * @param Descuento $descuento */ public function addDescuento(Descuento $descuento); /** * Remove descuento. * * @param Descuento $descuento */ public function removeDescuento(Descuento $descuento); }
JRomeoSalazar/ktsport
src/Sylius/Bundle/CoreBundle/Model/ProductInterface.php
PHP
mit
3,931
$(function() { $(".ajax_filter_choice").click(function() { $(this).parent().siblings().css("font-weight", "normal"); $(this).parent().css("font-weight","bold"); }) }); ajax_filtered_fields = { request_url: "/ajax_filtered_fields/json_index/", data_loaded: "data_loaded", _appendOption: function(obj, selector) { // append a json data row as an option to the selector var option = $('<option>' + obj[1] + '</option>'); option.attr({value: obj[0]}); option.appendTo(selector); return option; }, _removeOptions: function(selector) { // remove all options from selector selector.children("option").each(function(i) { $(this).remove(); }); }, getManyToManyJSON: function(element_id, app_label, object_name, lookup_string, select_related) { // manage the ManyToMany ajax request var selector_from = $("#" + element_id + "_from"); var selector_to = $("#" + element_id + "_to"); $("#" + element_id + "_input").val(""); selector_from.attr("disabled", true); selector_to.attr("disabled", true); this._removeOptions(selector_from); $.getJSON(this.request_url, { app_label: app_label, object_name: object_name, lookup_string: lookup_string, select_related: select_related}, function(data){ $.each(data, function(i, obj){ var option_is_selected = selector_to.children("option[value='" + obj[0] + "']").length; if (!option_is_selected) { ajax_filtered_fields._appendOption(obj, selector_from); }; }); SelectBox.init(element_id + "_from"); selector_from.attr("disabled", false); selector_to.attr("disabled", false); selector_from.trigger(ajax_filtered_fields.data_loaded); }); }, getForeignKeyJSON: function(element_id, app_label, object_name, lookup_string, select_related) { // manage the ForeignKey ajax request var selector = $("#" + element_id); var hidden = $("#hidden-" + element_id); $("#" + element_id + "_input").val(""); selector.attr("disabled", true); this._removeOptions(selector); $.getJSON(this.request_url, { app_label: app_label, object_name: object_name, lookup_string: lookup_string, select_related: select_related}, function(data){ var selection = hidden.val(); ajax_filtered_fields._appendOption(new Array("", "---------"), selector); $.each(data, function(i, obj){ ajax_filtered_fields._appendOption(obj, selector); }); selector.children("option[value='" + selection + "']").attr("selected", "selected"); selector.attr("disabled", false); SelectBox.init(element_id); ajax_filtered_fields.bindForeignKeyOptions(element_id); selector.trigger(ajax_filtered_fields.data_loaded); }); }, bindForeignKeyOptions: function(element_id) { // bind the dummy options to the hidden field that do the work var selector = $("#" + element_id); var hidden = $("#hidden-" + element_id); selector.change(function(e) { hidden.val($(this).val()); }); } };
jlzeller/django-ajax-filtered-fields
media/js/ajax_filtered_fields.js
JavaScript
mit
3,652
<TS language="sr@latin" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Klikni desnim tasterom za uređivanje adrese ili oznake</translation> </message> <message> <source>Create a new address</source> <translation>Kreiraj novu adresu</translation> </message> <message> <source>&amp;New</source> <translation>&amp;Novi</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopiraj selektovanu adresu u sistemski klipbord</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Kopiraj</translation> </message> <message> <source>C&amp;lose</source> <translation>Zatvori</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Briše trenutno izabranu adresu sa liste</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Izvoz podataka iz trenutne kartice u datoteku</translation> </message> <message> <source>&amp;Export</source> <translation>&amp;Izvoz</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Izbrisati</translation> </message> <message> <source>Choose the address to send coins to</source> <translation>Izaberite adresu za slanje novčića</translation> </message> <message> <source>Choose the address to receive coins with</source> <translation>Izaberite adresu za prijem novčića</translation> </message> <message> <source>Sending addresses</source> <translation>Adresa na koju se šalje</translation> </message> <message> <source>Receiving addresses</source> <translation>Adresa na koju se prima</translation> </message> <message> <source>These are your Egoldchain addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Ovo su Vaše Egoldchain adrese na koju se vrše uplate. Uvek proverite iznos i prijemnu adresu pre slanja novčića</translation> </message> <message> <source>These are your Egoldchain addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source> <translation>Ovo su Vaše Egoldchain adrese za primanje uplata. Preporučuje se upotreba nove adrese za svaku transakciju.</translation> </message> <message> <source>Copy &amp;Label</source> <translation>Kopiranje &amp;Oznaka</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Izmena</translation> </message> </context> <context> <name>AddressTableModel</name> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Passphrase Dialog</source> <translation>Dialog pristupne fraze</translation> </message> <message> <source>Enter passphrase</source> <translation>Unesi pristupnu frazu</translation> </message> <message> <source>New passphrase</source> <translation>Nova pristupna fraza</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Ponovo unesite pristupnu frazu</translation> </message> <message> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Unesite novu pristupnu frazu u novčanik. &lt;br/&gt;Molimo, koristite pristupnu frazu koja ima &lt;b&gt; deset ili više nasumičnih znakova&lt;/b&gt;, ili &lt;b&gt;osam ili više reči&lt;/b&gt;.</translation> </message> <message> <source>Encrypt wallet</source> <translation>Šifrujte novčanik</translation> </message> <message> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Da biste otključali novčanik potrebno je da unesete svoju pristupnu frazu.</translation> </message> <message> <source>Unlock wallet</source> <translation>Otključajte novčanik</translation> </message> <message> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Da biste dešifrovali novčanik, potrebno je da unesete svoju pristupnu frazu.</translation> </message> <message> <source>Decrypt wallet</source> <translation>Dešifrujte novčanik</translation> </message> <message> <source>Change passphrase</source> <translation>Promenite pristupnu frazu</translation> </message> <message> <source>Enter the old passphrase and new passphrase to the wallet.</source> <translation>Unesite u novčanik staru pristupnu frazu i novu pristupnu frazu.</translation> </message> <message> <source>Confirm wallet encryption</source> <translation>Potvrdite šifrovanje novčanika</translation> </message> <message> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR EgoldchainS&lt;/b&gt;!</source> <translation>Upozorenje: Ako šifrujete svoj novčanik, i potom izgubite svoju pristupnu frazu &lt;b&gt;IZGUBIĆETE SVE SVOJE BITKOINE&lt;/b&gt;!</translation> </message> <message> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Da li ste sigurni da želite da šifrujete svoj novčanik?</translation> </message> <message> <source>Wallet encrypted</source> <translation>Novčanik je šifrovan</translation> </message> </context> <context> <name>BanTableModel</name> <message> <source>IP/Netmask</source> <translation>IP/Netmask</translation> </message> <message> <source>Banned Until</source> <translation>Banovani ste do</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <source>Synchronizing with network...</source> <translation>Usklađivanje sa mrežom...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Pregled</translation> </message> <message> <source>Quit application</source> <translation>Isključi aplikaciju</translation> </message> <message> <source>&amp;About %1</source> <translation>&amp;Otprilike %1</translation> </message> <message> <source>Show information about %1</source> <translation>Prikaži informacije za otprilike %1</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opcije...</translation> </message> <message> <source>&amp;Change Passphrase...</source> <translation>&amp;Izmeni pristupnu frazu...</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>&amp;Slanje adresa...</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>&amp;Primanje adresa...</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Otvori &amp;URI...</translation> </message> <message> <source>Send coins to a Egoldchain address</source> <translation>Pošalji novčiće na Egoldchain adresu</translation> </message> <message> <source>&amp;Verify message...</source> <translation>&amp;Proveri poruku...</translation> </message> <message> <source>Egoldchain</source> <translation>Egoldchain</translation> </message> <message> <source>Wallet</source> <translation>Novčanik</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Pošalji</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Primi</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Prikazati / Sakriti</translation> </message> <message> <source>Show or hide the main Window</source> <translation>Prikaži ili sakrij glavni prozor</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Podešavanja</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Pomoć</translation> </message> <message> <source>Error</source> <translation>Greska</translation> </message> <message> <source>Warning</source> <translation>Upozorenje</translation> </message> <message> <source>Information</source> <translation>Informacije</translation> </message> <message> <source>%1 client</source> <translation>%1 klijent</translation> </message> <message> <source>Date: %1 </source> <translation>Datum: %1 </translation> </message> <message> <source>Amount: %1 </source> <translation>Iznos: %1 </translation> </message> <message> <source>Type: %1 </source> <translation>Tip: %1 </translation> </message> <message> <source>Label: %1 </source> <translation>Oznaka: %1 </translation> </message> <message> <source>Address: %1 </source> <translation>Adresa: %1 </translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Quantity:</source> <translation>Količina:</translation> </message> <message> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <source>Fee:</source> <translation>Naknada:</translation> </message> <message> <source>After Fee:</source> <translation>Nakon Naknade:</translation> </message> <message> <source>Amount</source> <translation>Kolicina</translation> </message> <message> <source>Date</source> <translation>Datum</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Izmeni Adresu</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Oznaka</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> <message> <source>Error</source> <translation>Greska</translation> </message> </context> <context> <name>ModalOverlay</name> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> </context> <context> <name>OverviewPage</name> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Kolicina</translation> </message> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> </context> <context> <name>ReceiveCoinsDialog</name> </context> <context> <name>ReceiveRequestDialog</name> </context> <context> <name>RecentRequestsTableModel</name> </context> <context> <name>SendCoinsDialog</name> <message> <source>Quantity:</source> <translation>Količina:</translation> </message> <message> <source>Amount:</source> <translation>Iznos:</translation> </message> <message> <source>Fee:</source> <translation>Naknada:</translation> </message> <message> <source>After Fee:</source> <translation>Nakon Naknade:</translation> </message> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> </context> <context> <name>TransactionView</name> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>bitcoin-core</name> <message> <source>Egoldchain Core</source> <translation>Egoldchain Core</translation> </message> <message> <source>Information</source> <translation>Informacije</translation> </message> <message> <source>Warning</source> <translation>Upozorenje</translation> </message> <message> <source>Insufficient funds</source> <translation>Nedovoljno sredstava</translation> </message> <message> <source>Loading block index...</source> <translation>Ucitavanje indeksa bloka...</translation> </message> <message> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Dodajte cvor za povezivanje, da bi pokusali da odrzite vezu otvorenom</translation> </message> <message> <source>Loading wallet...</source> <translation>Ucitavanje novcanika...</translation> </message> <message> <source>Cannot write default address</source> <translation>Nije moguce ispisivanje podrazumevane adrese</translation> </message> <message> <source>Rescanning...</source> <translation>Ponovno skeniranje...</translation> </message> <message> <source>Done loading</source> <translation>Zavrseno ucitavanje</translation> </message> <message> <source>Error</source> <translation>Greska</translation> </message> </context> </TS>
egoldchain/egoldchain-master
src/qt/locale/bitcoin_sr@latin.ts
TypeScript
mit
15,120
""" Support to interface with Sonos players (via SoCo). For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.sonos/ """ import datetime import logging from os import path import socket import urllib import voluptuous as vol from homeassistant.components.media_player import ( ATTR_MEDIA_ENQUEUE, DOMAIN, MEDIA_TYPE_MUSIC, SUPPORT_NEXT_TRACK, SUPPORT_PAUSE, SUPPORT_PLAY_MEDIA, SUPPORT_PREVIOUS_TRACK, SUPPORT_SEEK, SUPPORT_VOLUME_MUTE, SUPPORT_VOLUME_SET, SUPPORT_CLEAR_PLAYLIST, SUPPORT_SELECT_SOURCE, MediaPlayerDevice) from homeassistant.const import ( STATE_IDLE, STATE_PAUSED, STATE_PLAYING, STATE_UNKNOWN, STATE_OFF, ATTR_ENTITY_ID) from homeassistant.config import load_yaml_config_file import homeassistant.helpers.config_validation as cv REQUIREMENTS = ['SoCo==0.12'] _LOGGER = logging.getLogger(__name__) # The soco library is excessively chatty when it comes to logging and # causes a LOT of spam in the logs due to making a http connection to each # speaker every 10 seconds. Quiet it down a bit to just actual problems. _SOCO_LOGGER = logging.getLogger('soco') _SOCO_LOGGER.setLevel(logging.ERROR) _REQUESTS_LOGGER = logging.getLogger('requests') _REQUESTS_LOGGER.setLevel(logging.ERROR) SUPPORT_SONOS = SUPPORT_PAUSE | SUPPORT_VOLUME_SET | SUPPORT_VOLUME_MUTE |\ SUPPORT_PREVIOUS_TRACK | SUPPORT_NEXT_TRACK | SUPPORT_PLAY_MEDIA |\ SUPPORT_SEEK | SUPPORT_CLEAR_PLAYLIST | SUPPORT_SELECT_SOURCE SERVICE_GROUP_PLAYERS = 'sonos_group_players' SERVICE_UNJOIN = 'sonos_unjoin' SERVICE_SNAPSHOT = 'sonos_snapshot' SERVICE_RESTORE = 'sonos_restore' SERVICE_SET_TIMER = 'sonos_set_sleep_timer' SERVICE_CLEAR_TIMER = 'sonos_clear_sleep_timer' SUPPORT_SOURCE_LINEIN = 'Line-in' SUPPORT_SOURCE_TV = 'TV' # Service call validation schemas ATTR_SLEEP_TIME = 'sleep_time' SONOS_SCHEMA = vol.Schema({ ATTR_ENTITY_ID: cv.entity_ids, }) SONOS_SET_TIMER_SCHEMA = SONOS_SCHEMA.extend({ vol.Required(ATTR_SLEEP_TIME): vol.All(vol.Coerce(int), vol.Range(min=0, max=86399)) }) # List of devices that have been registered DEVICES = [] # pylint: disable=unused-argument, too-many-locals def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Sonos platform.""" import soco global DEVICES if discovery_info: player = soco.SoCo(discovery_info) # if device allready exists by config if player.uid in DEVICES: return True if player.is_visible: device = SonosDevice(hass, player) add_devices([device]) if not DEVICES: register_services(hass) DEVICES.append(device) return True return False players = None hosts = config.get('hosts', None) if hosts: # Support retro compatibility with comma separated list of hosts # from config hosts = hosts.split(',') if isinstance(hosts, str) else hosts players = [] for host in hosts: players.append(soco.SoCo(socket.gethostbyname(host))) if not players: players = soco.discover(interface_addr=config.get('interface_addr', None)) if not players: _LOGGER.warning('No Sonos speakers found.') return False DEVICES = [SonosDevice(hass, p) for p in players] add_devices(DEVICES) register_services(hass) _LOGGER.info('Added %s Sonos speakers', len(players)) return True def register_services(hass): """Register all services for sonos devices.""" descriptions = load_yaml_config_file( path.join(path.dirname(__file__), 'services.yaml')) hass.services.register(DOMAIN, SERVICE_GROUP_PLAYERS, _group_players_service, descriptions.get(SERVICE_GROUP_PLAYERS), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_UNJOIN, _unjoin_service, descriptions.get(SERVICE_UNJOIN), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_SNAPSHOT, _snapshot_service, descriptions.get(SERVICE_SNAPSHOT), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_RESTORE, _restore_service, descriptions.get(SERVICE_RESTORE), schema=SONOS_SCHEMA) hass.services.register(DOMAIN, SERVICE_SET_TIMER, _set_sleep_timer_service, descriptions.get(SERVICE_SET_TIMER), schema=SONOS_SET_TIMER_SCHEMA) hass.services.register(DOMAIN, SERVICE_CLEAR_TIMER, _clear_sleep_timer_service, descriptions.get(SERVICE_CLEAR_TIMER), schema=SONOS_SCHEMA) def _apply_service(service, service_func, *service_func_args): """Internal func for applying a service.""" entity_ids = service.data.get('entity_id') if entity_ids: _devices = [device for device in DEVICES if device.entity_id in entity_ids] else: _devices = DEVICES for device in _devices: service_func(device, *service_func_args) device.update_ha_state(True) def _group_players_service(service): """Group media players, use player as coordinator.""" _apply_service(service, SonosDevice.group_players) def _unjoin_service(service): """Unjoin the player from a group.""" _apply_service(service, SonosDevice.unjoin) def _snapshot_service(service): """Take a snapshot.""" _apply_service(service, SonosDevice.snapshot) def _restore_service(service): """Restore a snapshot.""" _apply_service(service, SonosDevice.restore) def _set_sleep_timer_service(service): """Set a timer.""" _apply_service(service, SonosDevice.set_sleep_timer, service.data[ATTR_SLEEP_TIME]) def _clear_sleep_timer_service(service): """Set a timer.""" _apply_service(service, SonosDevice.clear_sleep_timer) def only_if_coordinator(func): """Decorator for coordinator. If used as decorator, avoid calling the decorated method if player is not a coordinator. If not, a grouped speaker (not in coordinator role) will throw soco.exceptions.SoCoSlaveException. Also, partially catch exceptions like: soco.exceptions.SoCoUPnPException: UPnP Error 701 received: Transition not available from <player ip address> """ def wrapper(*args, **kwargs): """Decorator wrapper.""" if args[0].is_coordinator: from soco.exceptions import SoCoUPnPException try: func(*args, **kwargs) except SoCoUPnPException: _LOGGER.error('command "%s" for Sonos device "%s" ' 'not available in this mode', func.__name__, args[0].name) else: _LOGGER.debug('Ignore command "%s" for Sonos device "%s" (%s)', func.__name__, args[0].name, 'not coordinator') return wrapper # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=abstract-method class SonosDevice(MediaPlayerDevice): """Representation of a Sonos device.""" # pylint: disable=too-many-arguments def __init__(self, hass, player): """Initialize the Sonos device.""" from soco.snapshot import Snapshot self.hass = hass self.volume_increment = 5 self._player = player self._speaker_info = None self._name = None self._coordinator = None self._media_content_id = None self._media_duration = None self._media_image_url = None self._media_artist = None self._media_album_name = None self._media_title = None self.update() self.soco_snapshot = Snapshot(self._player) @property def should_poll(self): """Polling needed.""" return True def update_sonos(self, now): """Update state, called by track_utc_time_change.""" self.update_ha_state(True) @property def unique_id(self): """Return an unique ID.""" return self._player.uid @property def name(self): """Return the name of the device.""" return self._name @property def state(self): """Return the state of the device.""" if self._status == 'PAUSED_PLAYBACK': return STATE_PAUSED if self._status == 'PLAYING': return STATE_PLAYING if self._status == 'STOPPED': return STATE_IDLE if self._status == 'OFF': return STATE_OFF return STATE_UNKNOWN @property def is_coordinator(self): """Return true if player is a coordinator.""" return self._player.is_coordinator def update(self): """Retrieve latest state.""" self._speaker_info = self._player.get_speaker_info() self._name = self._speaker_info['zone_name'].replace( ' (R)', '').replace(' (L)', '') if self.available: self._status = self._player.get_current_transport_info().get( 'current_transport_state') trackinfo = self._player.get_current_track_info() if trackinfo['uri'].startswith('x-rincon:'): # this speaker is a slave, find the coordinator # the uri of the track is 'x-rincon:{coordinator-id}' coordinator_id = trackinfo['uri'][9:] coordinators = [device for device in DEVICES if device.unique_id == coordinator_id] self._coordinator = coordinators[0] if coordinators else None else: self._coordinator = None if not self._coordinator: mediainfo = self._player.avTransport.GetMediaInfo([ ('InstanceID', 0) ]) duration = trackinfo.get('duration', '0:00') # if the speaker is playing from the "line-in" source, getting # track metadata can return NOT_IMPLEMENTED, which breaks the # volume logic below if duration == 'NOT_IMPLEMENTED': duration = None else: duration = sum(60 ** x[0] * int(x[1]) for x in enumerate( reversed(duration.split(':')))) media_image_url = trackinfo.get('album_art', None) media_artist = trackinfo.get('artist', None) media_album_name = trackinfo.get('album', None) media_title = trackinfo.get('title', None) if media_image_url in ('', 'NOT_IMPLEMENTED', None): # fallback to asking the speaker directly media_image_url = \ 'http://{host}:{port}/getaa?s=1&u={uri}'.format( host=self._player.ip_address, port=1400, uri=urllib.parse.quote(mediainfo['CurrentURI']) ) if media_artist in ('', 'NOT_IMPLEMENTED', None): # if listening to a radio stream the media_artist field # will be empty and the title field will contain the # filename that is being streamed current_uri_metadata = mediainfo["CurrentURIMetaData"] if current_uri_metadata not in \ ('', 'NOT_IMPLEMENTED', None): # currently soco does not have an API for this import soco current_uri_metadata = soco.xml.XML.fromstring( soco.utils.really_utf8(current_uri_metadata)) md_title = current_uri_metadata.findtext( './/{http://purl.org/dc/elements/1.1/}title') if md_title not in ('', 'NOT_IMPLEMENTED', None): media_artist = '' media_title = md_title self._media_content_id = trackinfo.get('title', None) self._media_duration = duration self._media_image_url = media_image_url self._media_artist = media_artist self._media_album_name = media_album_name self._media_title = media_title else: self._status = 'OFF' self._coordinator = None self._media_content_id = None self._media_duration = None self._media_image_url = None self._media_artist = None self._media_album_name = None self._media_title = None @property def volume_level(self): """Volume level of the media player (0..1).""" return self._player.volume / 100.0 @property def is_volume_muted(self): """Return true if volume is muted.""" return self._player.mute @property def media_content_id(self): """Content ID of current playing media.""" if self._coordinator: return self._coordinator.media_content_id else: return self._media_content_id @property def media_content_type(self): """Content type of current playing media.""" return MEDIA_TYPE_MUSIC @property def media_duration(self): """Duration of current playing media in seconds.""" if self._coordinator: return self._coordinator.media_duration else: return self._media_duration @property def media_image_url(self): """Image url of current playing media.""" if self._coordinator: return self._coordinator.media_image_url else: return self._media_image_url @property def media_artist(self): """Artist of current playing media, music track only.""" if self._coordinator: return self._coordinator.media_artist else: return self._media_artist @property def media_album_name(self): """Album name of current playing media, music track only.""" if self._coordinator: return self._coordinator.media_album_name else: return self._media_album_name @property def media_title(self): """Title of current playing media.""" if self._player.is_playing_line_in: return SUPPORT_SOURCE_LINEIN if self._player.is_playing_tv: return SUPPORT_SOURCE_TV if self._coordinator: return self._coordinator.media_title else: return self._media_title @property def supported_media_commands(self): """Flag of media commands that are supported.""" if not self.source_list: # some devices do not allow source selection return SUPPORT_SONOS ^ SUPPORT_SELECT_SOURCE return SUPPORT_SONOS def volume_up(self): """Volume up media player.""" self._player.volume += self.volume_increment def volume_down(self): """Volume down media player.""" self._player.volume -= self.volume_increment def set_volume_level(self, volume): """Set volume level, range 0..1.""" self._player.volume = str(int(volume * 100)) def mute_volume(self, mute): """Mute (true) or unmute (false) media player.""" self._player.mute = mute def select_source(self, source): """Select input source.""" if source == SUPPORT_SOURCE_LINEIN: self._player.switch_to_line_in() elif source == SUPPORT_SOURCE_TV: self._player.switch_to_tv() @property def source_list(self): """List of available input sources.""" model_name = self._speaker_info['model_name'] if 'PLAY:5' in model_name: return [SUPPORT_SOURCE_LINEIN] elif 'PLAYBAR' in model_name: return [SUPPORT_SOURCE_LINEIN, SUPPORT_SOURCE_TV] @property def source(self): """Name of the current input source.""" if self._player.is_playing_line_in: return SUPPORT_SOURCE_LINEIN if self._player.is_playing_tv: return SUPPORT_SOURCE_TV return None @only_if_coordinator def turn_off(self): """Turn off media player.""" self._player.pause() def media_play(self): """Send play command.""" if self._coordinator: self._coordinator.media_play() else: self._player.play() def media_pause(self): """Send pause command.""" if self._coordinator: self._coordinator.media_pause() else: self._player.pause() def media_next_track(self): """Send next track command.""" if self._coordinator: self._coordinator.media_next_track() else: self._player.next() def media_previous_track(self): """Send next track command.""" if self._coordinator: self._coordinator.media_previous_track() else: self._player.previous() def media_seek(self, position): """Send seek command.""" if self._coordinator: self._coordinator.media_seek(position) else: self._player.seek(str(datetime.timedelta(seconds=int(position)))) def clear_playlist(self): """Clear players playlist.""" if self._coordinator: self._coordinator.clear_playlist() else: self._player.clear_queue() @only_if_coordinator def turn_on(self): """Turn the media player on.""" self._player.play() def play_media(self, media_type, media_id, **kwargs): """ Send the play_media command to the media player. If ATTR_MEDIA_ENQUEUE is True, add `media_id` to the queue. """ if self._coordinator: self._coordinator.play_media(media_type, media_id, **kwargs) else: if kwargs.get(ATTR_MEDIA_ENQUEUE): from soco.exceptions import SoCoUPnPException try: self._player.add_uri_to_queue(media_id) except SoCoUPnPException: _LOGGER.error('Error parsing media uri "%s", ' "please check it's a valid media resource " 'supported by Sonos', media_id) else: self._player.play_uri(media_id) def group_players(self): """Group all players under this coordinator.""" if self._coordinator: self._coordinator.group_players() else: self._player.partymode() @only_if_coordinator def unjoin(self): """Unjoin the player from a group.""" self._player.unjoin() @only_if_coordinator def snapshot(self): """Snapshot the player.""" self.soco_snapshot.snapshot() @only_if_coordinator def restore(self): """Restore snapshot for the player.""" self.soco_snapshot.restore(True) @only_if_coordinator def set_sleep_timer(self, sleep_time): """Set the timer on the player.""" self._player.set_sleep_timer(sleep_time) @only_if_coordinator def clear_sleep_timer(self): """Clear the timer on the player.""" self._player.set_sleep_timer(None) @property def available(self): """Return True if player is reachable, False otherwise.""" try: sock = socket.create_connection( address=(self._player.ip_address, 1443), timeout=3) sock.close() return True except socket.error: return False
betrisey/home-assistant
homeassistant/components/media_player/sonos.py
Python
mit
20,355
=begin give highest possible product out of three integers in a given array input: array of integers (will always have at least three integers) output: highest product, integer PSEUDOCODE int_array.combination(3) => gives array of combinations of all possible groups of three array_combos.each do |group| products_array << group.inject(:*) end products_array.sort highest_product = products_array[-1] O(n) run time, O(n^2) space how to save space? =end def highest_product(array_of_ints) products_array = [] array_of_ints.combination(3) {|group| products_array << group.inject(:*)} products_array.sort! highest_product = products_array.last end # O(n) run time, O(n) space #DRIVER CODE p highest_product([1,1,1,1,4]) == 4 p highest_product([7, 1, 9, 4]) == 252 p highest_product([-10, -10, 3, 1, 2]) == 300
mairene/interviewpractice
interviewcake/highest_product_of_array.rb
Ruby
mit
824
'use strict'; var type = require('type-detect'); var path = require('path'); var removeTrailingSeparator = require('remove-trailing-path-separator'); var errors = require('common-errors'); var prettyFormat = require('pretty-format'); module.exports = function (input, cb) { if (type(input) !== 'string') { cb(new errors.TypeError('input requires string'), null); return; } var split = removeTrailingSeparator(path.normalize(input)).split(path.sep); var inputLast = split[split.length - 1]; if (['', '.', '..'].some(function (value) { return inputLast === value; })) { cb(new errors.ArgumentError('input is not allowed: ' + prettyFormat(inputLast)), null); return; } cb(null, inputLast); };
togusafish/pandawing-_-node-run-yo
lib/pick-target.js
JavaScript
mit
731
""" """ import logging import time import hiro import mock from flask import Flask, request from werkzeug.exceptions import BadRequest from flask_limiter.extension import C, Limiter from flask_limiter.util import get_remote_address def test_reset(extension_factory): app, limiter = extension_factory({C.DEFAULT_LIMITS: "1 per day"}) @app.route("/") def null(): return "Hello Reset" with app.test_client() as cli: cli.get("/") assert "1 per 1 day" in cli.get("/").data.decode() limiter.reset() assert "Hello Reset" == cli.get("/").data.decode() assert "1 per 1 day" in cli.get("/").data.decode() def test_reset_unsupported(extension_factory, memcached_connection): app, limiter = extension_factory( {C.DEFAULT_LIMITS: "1 per day", C.STORAGE_URI: "memcached://localhost:31211"} ) @app.route("/") def null(): return "Hello Reset" with app.test_client() as cli: cli.get("/") assert "1 per 1 day" in cli.get("/").data.decode() # no op with memcached but no error raised limiter.reset() assert "1 per 1 day" in cli.get("/").data.decode() def test_combined_rate_limits(extension_factory): app, limiter = extension_factory({C.DEFAULT_LIMITS: "1 per hour; 10 per day"}) @app.route("/t1") @limiter.limit("100 per hour;10/minute") def t1(): return "t1" @app.route("/t2") def t2(): return "t2" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get("/t1").status_code assert 200 == cli.get("/t2").status_code assert 429 == cli.get("/t2").status_code def test_defaults_per_method(extension_factory): app, limiter = extension_factory( {C.DEFAULT_LIMITS: "1 per hour", C.DEFAULT_LIMITS_PER_METHOD: True} ) @app.route("/t1", methods=["GET", "POST"]) def t1(): return "t1" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get("/t1").status_code assert 429 == cli.get("/t1").status_code assert 200 == cli.post("/t1").status_code assert 429 == cli.post("/t1").status_code def test_default_limit_with_exemption(extension_factory): def is_backdoor(): return request.headers.get("backdoor") == "true" app, limiter = extension_factory( {C.DEFAULT_LIMITS: "1 per hour", C.DEFAULT_LIMITS_EXEMPT_WHEN: is_backdoor} ) @app.route("/t1") def t1(): return "test" with hiro.Timeline() as timeline: with app.test_client() as cli: assert cli.get("/t1", headers={"backdoor": "true"}).status_code == 200 assert cli.get("/t1", headers={"backdoor": "true"}).status_code == 200 assert cli.get("/t1").status_code == 200 assert cli.get("/t1").status_code == 429 timeline.forward(3600) assert cli.get("/t1").status_code == 200 def test_default_limit_with_conditional_deduction(extension_factory): def failed_request(response): return response.status_code != 200 app, limiter = extension_factory( {C.DEFAULT_LIMITS: "1 per hour", C.DEFAULT_LIMITS_DEDUCT_WHEN: failed_request} ) @app.route("/t1/<path:path>") def t1(path): if path != "1": raise BadRequest() return path with hiro.Timeline() as timeline: with app.test_client() as cli: assert cli.get("/t1/1").status_code == 200 assert cli.get("/t1/1").status_code == 200 assert cli.get("/t1/2").status_code == 400 assert cli.get("/t1/1").status_code == 429 assert cli.get("/t1/2").status_code == 429 timeline.forward(3600) assert cli.get("/t1/1").status_code == 200 assert cli.get("/t1/2").status_code == 400 def test_key_func(extension_factory): app, limiter = extension_factory() @app.route("/t1") @limiter.limit("100 per minute", lambda: "test") def t1(): return "test" with hiro.Timeline().freeze(): with app.test_client() as cli: for i in range(0, 100): assert ( 200 == cli.get( "/t1", headers={"X_FORWARDED_FOR": "127.0.0.2"} ).status_code ) assert 429 == cli.get("/t1").status_code def test_logging(caplog): app = Flask(__name__) limiter = Limiter(app, key_func=get_remote_address) @app.route("/t1") @limiter.limit("1/minute") def t1(): return "test" with app.test_client() as cli: assert 200 == cli.get("/t1").status_code assert 429 == cli.get("/t1").status_code assert len(caplog.records) == 1 assert caplog.records[0].levelname == "WARNING" def test_reuse_logging(): app = Flask(__name__) app_handler = mock.Mock() app_handler.level = logging.INFO app.logger.addHandler(app_handler) limiter = Limiter(app, key_func=get_remote_address) for handler in app.logger.handlers: limiter.logger.addHandler(handler) @app.route("/t1") @limiter.limit("1/minute") def t1(): return "42" with app.test_client() as cli: cli.get("/t1") cli.get("/t1") assert app_handler.handle.call_count == 1 def test_disabled_flag(extension_factory): app, limiter = extension_factory( config={C.ENABLED: False}, default_limits=["1/minute"] ) @app.route("/t1") def t1(): return "test" @app.route("/t2") @limiter.limit("10 per minute") def t2(): return "test" with app.test_client() as cli: assert cli.get("/t1").status_code == 200 assert cli.get("/t1").status_code == 200 for i in range(0, 10): assert cli.get("/t2").status_code == 200 assert cli.get("/t2").status_code == 200 def test_multiple_apps(): app1 = Flask(__name__) app2 = Flask(__name__) limiter = Limiter(default_limits=["1/second"], key_func=get_remote_address) limiter.init_app(app1) limiter.init_app(app2) @app1.route("/ping") def ping(): return "PONG" @app1.route("/slowping") @limiter.limit("1/minute") def slow_ping(): return "PONG" @app2.route("/ping") @limiter.limit("2/second") def ping_2(): return "PONG" @app2.route("/slowping") @limiter.limit("2/minute") def slow_ping_2(): return "PONG" with hiro.Timeline().freeze() as timeline: with app1.test_client() as cli: assert cli.get("/ping").status_code == 200 assert cli.get("/ping").status_code == 429 timeline.forward(1) assert cli.get("/ping").status_code == 200 assert cli.get("/slowping").status_code == 200 timeline.forward(59) assert cli.get("/slowping").status_code == 429 timeline.forward(1) assert cli.get("/slowping").status_code == 200 with app2.test_client() as cli: assert cli.get("/ping").status_code == 200 assert cli.get("/ping").status_code == 200 assert cli.get("/ping").status_code == 429 timeline.forward(1) assert cli.get("/ping").status_code == 200 assert cli.get("/slowping").status_code == 200 timeline.forward(59) assert cli.get("/slowping").status_code == 200 assert cli.get("/slowping").status_code == 429 timeline.forward(1) assert cli.get("/slowping").status_code == 200 def test_headers_no_breach(): app = Flask(__name__) limiter = Limiter( app, default_limits=["10/minute"], headers_enabled=True, key_func=get_remote_address, ) @app.route("/t1") def t1(): return "test" @app.route("/t2") @limiter.limit("2/second; 5 per minute; 10/hour") def t2(): return "test" with hiro.Timeline().freeze(): with app.test_client() as cli: resp = cli.get("/t1") assert resp.headers.get("X-RateLimit-Limit") == "10" assert resp.headers.get("X-RateLimit-Remaining") == "9" assert resp.headers.get("X-RateLimit-Reset") == str(int(time.time() + 61)) assert resp.headers.get("Retry-After") == str(60) resp = cli.get("/t2") assert resp.headers.get("X-RateLimit-Limit") == "2" assert resp.headers.get("X-RateLimit-Remaining") == "1" assert resp.headers.get("X-RateLimit-Reset") == str(int(time.time() + 2)) assert resp.headers.get("Retry-After") == str(1) assert limiter.current_limit.remaining == 1 assert limiter.current_limit.reset_at == int(time.time() + 2) assert not limiter.current_limit.breached def test_headers_breach(): app = Flask(__name__) limiter = Limiter( app, default_limits=["10/minute"], headers_enabled=True, key_func=get_remote_address, ) @app.route("/t1") @limiter.limit("2/second; 10 per minute; 20/hour") def t(): return "test" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: for i in range(10): resp = cli.get("/t1") timeline.forward(1) assert len(limiter.current_limits) == 3 assert all(not limit.breached for limit in limiter.current_limits) resp = cli.get("/t1") timeline.forward(1) assert resp.headers.get("X-RateLimit-Limit") == "10" assert resp.headers.get("X-RateLimit-Remaining") == "0" assert resp.headers.get("X-RateLimit-Reset") == str(int(time.time() + 50)) assert resp.headers.get("Retry-After") == str(int(50)) assert limiter.current_limit.remaining == 0 assert limiter.current_limit.reset_at == int(time.time() + 50) assert limiter.current_limit.breached def test_retry_after(): app = Flask(__name__) _ = Limiter( app, default_limits=["1/minute"], headers_enabled=True, key_func=get_remote_address, ) @app.route("/t1") def t(): return "test" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: resp = cli.get("/t1") retry_after = int(resp.headers.get("Retry-After")) assert retry_after > 0 timeline.forward(retry_after) resp = cli.get("/t1") assert resp.status_code == 200 def test_retry_after_exists_seconds(): app = Flask(__name__) _ = Limiter( app, default_limits=["1/minute"], headers_enabled=True, key_func=get_remote_address, ) @app.route("/t1") def t(): return "", 200, {"Retry-After": "1000000"} with app.test_client() as cli: resp = cli.get("/t1") retry_after = int(resp.headers.get("Retry-After")) assert retry_after > 1000 def test_retry_after_exists_rfc1123(): app = Flask(__name__) _ = Limiter( app, default_limits=["1/minute"], headers_enabled=True, key_func=get_remote_address, ) @app.route("/t1") def t(): return "", 200, {"Retry-After": "Sun, 06 Nov 2032 01:01:01 GMT"} with app.test_client() as cli: resp = cli.get("/t1") retry_after = int(resp.headers.get("Retry-After")) assert retry_after > 1000 def test_custom_headers_from_config(): app = Flask(__name__) app.config.setdefault(C.HEADER_LIMIT, "X-Limit") app.config.setdefault(C.HEADER_REMAINING, "X-Remaining") app.config.setdefault(C.HEADER_RESET, "X-Reset") limiter = Limiter( app, default_limits=["10/minute"], headers_enabled=True, key_func=get_remote_address, ) @app.route("/t1") @limiter.limit("2/second; 10 per minute; 20/hour") def t(): return "test" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: for i in range(11): resp = cli.get("/t1") timeline.forward(1) assert resp.headers.get("X-Limit") == "10" assert resp.headers.get("X-Remaining") == "0" assert resp.headers.get("X-Reset") == str(int(time.time() + 50)) def test_application_shared_limit(extension_factory): app, limiter = extension_factory(application_limits=["2/minute"]) @app.route("/t1") def t1(): return "route1" @app.route("/t2") def t2(): return "route2" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get("/t1").status_code assert 200 == cli.get("/t2").status_code assert 429 == cli.get("/t1").status_code def test_callable_default_limit(extension_factory): app, limiter = extension_factory(default_limits=[lambda: "1/minute"]) @app.route("/t1") def t1(): return "t1" @app.route("/t2") def t2(): return "t2" with hiro.Timeline().freeze(): with app.test_client() as cli: assert cli.get("/t1").status_code == 200 assert cli.get("/t2").status_code == 200 assert cli.get("/t1").status_code == 429 assert cli.get("/t2").status_code == 429 def test_callable_application_limit(extension_factory): app, limiter = extension_factory(application_limits=[lambda: "1/minute"]) @app.route("/t1") def t1(): return "t1" @app.route("/t2") def t2(): return "t2" with hiro.Timeline().freeze(): with app.test_client() as cli: assert cli.get("/t1").status_code == 200 assert cli.get("/t2").status_code == 429 def test_no_auto_check(extension_factory): app, limiter = extension_factory(auto_check=False) @app.route("/", methods=["GET", "POST"]) @limiter.limit("1/second", per_method=True) def root(): return "root" with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get("/").status_code assert 200 == cli.get("/").status_code # attach before_request to perform check @app.before_request def _(): limiter.check() with hiro.Timeline().freeze(): with app.test_client() as cli: assert 200 == cli.get("/").status_code assert 429 == cli.get("/").status_code def test_fail_on_first_breach(extension_factory): app, limiter = extension_factory(fail_on_first_breach=True) @app.route("/", methods=["GET", "POST"]) @limiter.limit("1/second", per_method=True) @limiter.limit("2/minute", per_method=True) def root(): return "root" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert 200 == cli.get("/").status_code assert 429 == cli.get("/").status_code assert [True] == [k.breached for k in limiter.current_limits] timeline.forward(1) assert 200 == cli.get("/").status_code assert [False, False] == [k.breached for k in limiter.current_limits] timeline.forward(1) assert 429 == cli.get("/").status_code assert [False, True] == [k.breached for k in limiter.current_limits] def test_no_fail_on_first_breach(extension_factory): app, limiter = extension_factory(fail_on_first_breach=False) @app.route("/", methods=["GET", "POST"]) @limiter.limit("1/second", per_method=True) @limiter.limit("2/minute", per_method=True) def root(): return "root" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert 200 == cli.get("/").status_code assert 429 == cli.get("/").status_code assert [True, False] == [k.breached for k in limiter.current_limits] timeline.forward(1) assert 429 == cli.get("/").status_code assert [False, True] == [k.breached for k in limiter.current_limits] def test_custom_key_prefix(redis_connection, extension_factory): app1, limiter1 = extension_factory( key_prefix="moo", storage_uri="redis://localhost:46379" ) app2, limiter2 = extension_factory( {C.KEY_PREFIX: "cow"}, storage_uri="redis://localhost:46379" ) app3, limiter3 = extension_factory(storage_uri="redis://localhost:46379") @app1.route("/test") @limiter1.limit("1/day") def app1_test(): return "app1 test" @app2.route("/test") @limiter2.limit("1/day") def app2_test(): return "app1 test" @app3.route("/test") @limiter3.limit("1/day") def app3_test(): return "app1 test" with app1.test_client() as cli: resp = cli.get("/test") assert 200 == resp.status_code resp = cli.get("/test") assert 429 == resp.status_code with app2.test_client() as cli: resp = cli.get("/test") assert 200 == resp.status_code resp = cli.get("/test") assert 429 == resp.status_code with app3.test_client() as cli: resp = cli.get("/test") assert 200 == resp.status_code resp = cli.get("/test") assert 429 == resp.status_code def test_second_instance_bypassed_by_shared_g(): app = Flask(__name__) limiter1 = Limiter(app, key_func=get_remote_address) limiter2 = Limiter(app, key_func=get_remote_address) @app.route("/test1") @limiter2.limit("1/second") def app_test1(): return "app test1" @app.route("/test2") @limiter1.limit("10/minute") @limiter2.limit("1/second") def app_test2(): return "app test2" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert cli.get("/test1").status_code == 200 assert cli.get("/test2").status_code == 200 assert cli.get("/test1").status_code == 429 assert cli.get("/test2").status_code == 200 for i in range(8): assert cli.get("/test1").status_code == 429 assert cli.get("/test2").status_code == 200 assert cli.get("/test2").status_code == 429 timeline.forward(1) assert cli.get("/test1").status_code == 200 assert cli.get("/test2").status_code == 429 timeline.forward(59) assert cli.get("/test1").status_code == 200 assert cli.get("/test2").status_code == 200 def test_independent_instances_by_key_prefix(): app = Flask(__name__) limiter1 = Limiter(app, key_prefix="lmt1", key_func=get_remote_address) limiter2 = Limiter(app, key_prefix="lmt2", key_func=get_remote_address) @app.route("/test1") @limiter2.limit("1/second") def app_test1(): return "app test1" @app.route("/test2") @limiter1.limit("10/minute") @limiter2.limit("1/second") def app_test2(): return "app test2" with hiro.Timeline().freeze() as timeline: with app.test_client() as cli: assert cli.get("/test1").status_code == 200 assert cli.get("/test2").status_code == 200 resp = cli.get("/test1") assert resp.status_code == 429 assert "1 per 1 second" in resp.data.decode() resp = cli.get("/test2") assert resp.status_code == 429 assert "1 per 1 second" in resp.data.decode() for i in range(8): assert cli.get("/test1").status_code == 429 assert cli.get("/test2").status_code == 429 assert cli.get("/test2").status_code == 429 timeline.forward(1) assert cli.get("/test1").status_code == 200 assert cli.get("/test2").status_code == 429 timeline.forward(59) assert cli.get("/test1").status_code == 200 assert cli.get("/test2").status_code == 200
alisaifee/flask-limiter
tests/test_flask_ext.py
Python
mit
20,218
<?php /** * Transformer.php. * * Part of EasyWeChat. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @author overtrue <i@overtrue.me> * @copyright 2015 overtrue <i@overtrue.me> * * @link https://github.com/overtrue * @link http://overtrue.me */ namespace EasyWeChat\Staff; use EasyWeChat\Message\AbstractMessage; /** * Class Transformer. */ class Transformer { /** * transform message to XML. * * @param AbstractMessage $message * * @return array */ public function transform(AbstractMessage $message) { $handle = 'transform'.substr(get_class($message), strlen('EasyWeChat\Message')); return method_exists($this, $handle) ? $this->$handle($message) : []; } /** * Transform text message. * * @return array */ public function tranformText(AbstractMessage $message) { return array( 'text' => array( 'content' => $message->content, ), ); } /** * Transform image message. * * @return array */ public function tranformImage(AbstractMessage $message) { return array( 'image' => array( 'media_id' => $message->media_id, ), ); } /** * Transform video message. * * @return array */ public function tranformVideo(AbstractMessage $message) { return array( 'video' => array( 'title' => $message->title, 'media_id' => $message->media_id, 'description' => $message->description, 'thumb_media_id' => $message->thumb_media_id, ), ); } /** * Transform voice message. * * @return array */ public function tranformVoice(AbstractMessage $message) { return array( 'voice' => array( 'media_id' => $message->media_id, ), ); } /** * Transform articles message. * * @return array */ public function tranformArticles(AbstractMessage $message) { $articles = array(); foreach ($message->items as $item) { $articles[] = array( 'title' => $item->title, 'description' => $item->description, 'url' => $item->url, 'picurl' => $item->pic_url, ); } return array('news' => array('articles' => $articles)); } }
TheNorthMemory/wechat
src/EasyWeChat/Staff/Transformer.php
PHP
mit
2,874
import { Component } from '@angular/core'; // Visual Recognition import { VisualRecognitionService } from './visual-recognition.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'CyberusAI'; sources: Array<Object>; constructor(private visualRecognitionService: VisualRecognitionService) { this.sources = [ { src: "assets/videos/VIRAT_S_010000_00_000000_000165.mp4", type: "video/mp4" }, { src: "assets/videos/out.mp4", type: "video/mp4" } ]; } public testWatson() { this.visualRecognitionService.classify("assets/putin.jpg"); } ngOnInit() { } }
jeremy091/cyberusAI
cyberus/container/src/app/app.component.ts
TypeScript
mit
746
import os from setuptools import setup, find_packages README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='django-email-subscription', url='https://github.com/MagicSolutions/django-email-subscription', version='0.0.1', description='Django app for creating subcription accoutns.', long_description=README, install_requires=[ 'django-simple-captcha>=0.4.2', ], packages=find_packages(), package_data={'': ['LICENSE']}, include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', ], )
MagicSolutions/django-email-subscription
setup.py
Python
mit
888
#ifndef _OPERATIONS_HPP #define _OPERATIONS_HPP #define CL_USE_DEPRECATED_OPENCL_1_1_APIS #define CL_USE_DEPRECATED_OPENCL_1_2_APIS #include <CL/cl.h> #include "matrix.hpp" #include "mem.hpp" class Operations { public: virtual ~Operations(void) { } virtual Matrix multiply(const Matrix& lhs, const Matrix& rhs) const = 0; }; class CpuOperations : public Operations { public: virtual Matrix multiply(const Matrix& lhs, const Matrix& rhs) const; }; class GpuOperations : public Operations { private: cl_device_id m_deviceId; public: GpuOperations(void); virtual Matrix multiply(const Matrix& lhs, const Matrix& rhs) const; protected: GpuOperations(std::string kernelFile); cl_context createContext(void) const; cl_command_queue createCommandQueue(cl_context context) const; cl_program buildProgram(cl_context context, const std::string& filename) const; cl_kernel createKernel(cl_context context, cl_program program, const std::string& name) const; cl_mem uploadBuffer(cl_context context, size_t size, const void* dataPtr) const; static cl_device_id selectDevice(void); CleanUp<cl_context> m_context; CleanUp<cl_command_queue> m_queue; CleanUp<cl_program> m_program; }; class TransposedGpuOperations : public GpuOperations { public: TransposedGpuOperations(void); virtual Matrix multiply(const Matrix& lhs, const Matrix& rhs) const; }; class DotGpuOperations : public GpuOperations { public: DotGpuOperations(void) : GpuOperations("matrix_mul_dot.cl") {} }; class Float4GpuOperations : public GpuOperations { public: Float4GpuOperations(void) : GpuOperations("matrix_mul_float4.cl") {} }; class ConstantGpuOperations : public GpuOperations { public: ConstantGpuOperations(void) : GpuOperations("matrix_mul_constant.cl") {} }; #endif // _OPERATIONS_HPP
elecro/opencl_matrix_mul
operations.hpp
C++
mit
1,887
module ListTool module App class UseCommand < Command class << self def match? arg ['u', 'use'].include? arg end def parse argv fail_if_not_an_array(argv) list = argv.shift { list: parse_list_number!(list) } end def execute options, lister raise(ListNotFoundError, 'no list with given number') if lister.set_default_list( options[:list] ).nil? end def help " u, use LIST\t\t\tSet default list" end end end end end
Vizvamitra/list-tool
lib/list_tool/app/commands/use_command.rb
Ruby
mit
582
<?php namespace LegalThings\DataEnricher\Processor; use LegalThings\DataEnricher\Node; use LegalThings\DataEnricher\Processor; /** * Equal processor */ class Equal implements Processor { use Processor\Implementation; /** * Apply processing to a single node * * @param Node $node */ public function applyToNode(Node $node) { $instruction = $node->getInstruction($this); if (!is_array($instruction) || count($instruction) !== 2) { $node->setResult(false); } // might want to improve this check for different types using a library $node->setResult($instruction[0] == $instruction[1]); } }
legalthings/data-enricher
src/DataEnricher/Processor/Equal.php
PHP
mit
707
///<reference path="../../../lib/RTCPeerConnection.d.ts"/> ///<reference path="WebRtcCommons.ts"/> "use strict"; class WebRtcProducer { private _id : string; private _debugMode : boolean = false; private _successCalled : boolean = false; private connection: RTCPeerConnection = null; private channel: RTCDataChannel = null; private _onPassDataToPeer : IWebRtcConnectionDataCallback = null; private _onConnectionSucces : () => void = null; private _onConnectionError : (error: Object) => void = null; private _config: any = null; /** * constructor */ constructor(servers: RTCIceServer[], _id?: string, _debugMode?: boolean) { this._id = _id; this._debugMode = _debugMode||false; if (servers != null) this._config = { "iceServers": servers }; } /** * setCallbacks */ setCallbacks(onPassDataToPeer: IWebRtcConnectionDataCallback, onConnectionSucces: () => void, onConnectionError: (error: Object) => void): void { this._onPassDataToPeer = onPassDataToPeer; this._onConnectionSucces = onConnectionSucces; this._onConnectionError = onConnectionError; } /** * isConnected */ isConnected(): boolean { return this.connection != null && (this.connection.iceConnectionState === 'completed' //RTCIceConnectionState.completed || this.connection.iceConnectionState === 'connected') && this.channel != null && this.channel.readyState === 'open' ; //RTCDataChannelState.open } /** * configure */ configure(data: IWebRtcConnectionData): void { var self = this; // step 1 if (data === null) { if (this._debugMode) self.log('configure - Step1', data); this.connection.createOffer( function(sdp: RTCSessionDescription): void { if (self._debugMode) self.log('onOfferCreated', sdp); self.connection.setLocalDescription(sdp, null); self._onPassDataToPeer({'RTCSessionDescription': sdp}); }, function (errorInformation: DOMError): void { console.error('onOfferError', errorInformation); }); } else // step 2 if (data['RTCSessionDescription'] != undefined) { if (this._debugMode) this.log('configure - Step2', data); this.connection.setRemoteDescription(data['RTCSessionDescription']); } else // step 3 if (data['RTCIceCandidate'] != undefined) { if (this._debugMode) this.log('configure - Step3', data); this.connection.addIceCandidate(data['RTCIceCandidate'], function(): void { if (self._debugMode) self.log('onAddIceCandidateSuccess'); }, function (error): void { if (self._debugMode) self.log('onAddIceCandidateError'); }); } } /** * sendText */ sendMessage(msg: string): void { if (this._debugMode) this.log('Sending message: "' +msg +'"'); if (!this.isConnected()) throw new WebRtcConnectionNotInitializedError(''); this.channel.send(msg); } /** * open */ open(): void{ if (this._debugMode) this.log('Creating new; iceServers: ' +JSON.stringify(this._config)); if (typeof webkitRTCPeerConnection === 'function') { this.connection = new webkitRTCPeerConnection( this._config ); } else if (typeof mozRTCPeerConnection === 'function') { throw new Error('Not implemented yet.'); //this.connection = new mozRTCPeerConnection( this._config ); } else throw new Error('unknown implementation of RTCPeerConnection'); this.internalInit(); this._successCalled = false; } /** * close */ close(): void{ this._successCalled = false; if (this.channel != null) this.channel.close(); if (this.connection != null) this.connection.close(); } /** * internalInit */ private internalInit(): void { this.channel = this.connection.createDataChannel('label', null); this.channel.onopen = this.onReceiveChannelStateChange; this.channel.onclose = this.onReceiveChannelStateChange; this.connection.onicecandidate = function(event: RTCIceCandidateEvent): void { if (event.candidate) { if (this._debugMode) this.log('onIceCandidate', event.candidate); this._onPassDataToPeer({'RTCIceCandidate': event.candidate}); } this.tryCallSuccess(); }.bind(this); this.connection.oniceconnectionstatechange = function(event: Event): void { if (this._debugMode) this.log('onIceConnectionStateChange: ' +this.connection.iceConnectionState, event); this.tryCallSuccess(); }.bind(this); } /** * onReceiveChannelStateChange */ private onReceiveChannelStateChange = function(event: Event): void { if (this._debugMode) this.log('onReceiveChannelStateChange', event); this.tryCallSuccess(); }.bind(this); /** * tryCallSuccess */ private tryCallSuccess = function(): void { if (!this._successCalled && this.isConnected()) { if (this._debugMode) this.log('triggering onConnectionSucces callback'); this._successCalled = true; this._onConnectionSucces(); } }.bind(this); /** * log */ private log(msg: string, ...optionalParams: Object[]) { if (!this._debugMode) throw new Error('Debug mode is disabled.'); var arr: Object[] = new Array<Object>().concat(this.dbgId() + ' ' + msg).concat(optionalParams); console.log.apply(console, arr); document.writeln(this.dbgId() +' ' +msg +' ' +this.connectionState() +'<br>'); } /** * connectionState */ private connectionState(): string { return '<b>[connected: '+this.isConnected() +']</b> ' +'connection.iceConnectionState: '+ (this.connection === null ? 'null' : this.connection.iceConnectionState) +'; ' +'connection.iceGatheringState: '+ (this.connection === null ? 'null' : this.connection.iceGatheringState) +'; ' +'connection.signalingState: '+ (this.connection === null ? 'null' : this.connection.signalingState) +'; ' +'channel.readyState: '+ (this.channel === null ? 'null' : this.channel.readyState); } /** * dbgId */ private dbgId(): string{ return '[' +(this._id != '' ? this._id +' ' : '') +'producer]'; } }
twerno/CardGameJS
CardGameJS/src/utils/WebRtc/WebRtcProducer.ts
TypeScript
mit
6,411
# ~*~ encoding: utf-8 ~*~ from pymongo import MongoClient from pandas import read_csv from datetime import date mongodb = MongoClient('192.168.178.82', 9999) db = mongodb['dev'] drug_collection = db['drug'] drugs = read_csv('~/Dokumente/bfarm_lieferenpass_meldung.csv', delimiter=';', encoding='iso8859_2').to_dict() drugs.pop('Id', None) drugs.pop('aktuelle Bescheidart', None) drugs.pop('Meldungsart', None) drugs.pop('aktuelle Bescheidart', None) data = dict() for x in range(drugs['Verkehrsfähig'].__len__()): """ if drugs['Ende Engpass'][x] == '-': data['end'] = None else: day, month, year = drugs['Ende Engpass'][x].split('.') data['end'] = date(int(year), int(month), int(day)).__str__() if drugs['Beginn Engpass'][x] == '-': data['initial_report'] = None else: day, month, year = drugs['Beginn Engpass'][x].split('.') data['initial_report'] = date(int(year), int(month), int(day)).__str__() if drugs['Datum der letzten Meldung'][x] == '-': data['last_report'] = None else: day, month, year = drugs['Datum der letzten Meldung'][x].split('.') data['last_report'] = date(int(year), int(month), int(day)).__str__() """ data['substance'] = drugs['Wirkstoffe'][x].replace(' ', '').split(';') data['enr'] = int(drugs['Enr'][x]) data['marketability'] = True if drugs['Verkehrsfähig'][x] == 'ja' else False data['atc_code'] = drugs['ATC-Code'][x] data['pzn'] = int(drugs['PZN'][x].split(' ')[0].replace(';', '')) if drugs['PZN'][x] != '-' else None data['drug_title'] = drugs['Arzneimittelbezeichnung'][x] data['hospital'] = True if drugs['Krankenhausrelevant'][x] == 'ja' else False drug_collection.update_one({'enr': data['enr']}, {'$set': data}, upsert=True)
schenkd/webdev-project
data_import.py
Python
mit
1,815
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AotCompilerHost, EmitterVisitorContext, ExternalReference, GeneratedFile, ParseSourceSpan, TypeScriptEmitter, collectExternalReferences, syntaxError} from '@angular/compiler'; import * as path from 'path'; import * as ts from 'typescript'; import {TypeCheckHost} from '../diagnostics/translate_diagnostics'; import {METADATA_VERSION, ModuleMetadata} from '../metadata/index'; import {CompilerHost, CompilerOptions, LibrarySummary} from './api'; import {MetadataReaderHost, createMetadataReaderCache, readMetadata} from './metadata_reader'; import {DTS, GENERATED_FILES, isInRootDir, relativeToRootDirs} from './util'; const NODE_MODULES_PACKAGE_NAME = /node_modules\/((\w|-)+|(@(\w|-)+\/(\w|-)+))/; const EXT = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/; export function createCompilerHost( {options, tsHost = ts.createCompilerHost(options, true)}: {options: CompilerOptions, tsHost?: ts.CompilerHost}): CompilerHost { return tsHost; } export interface MetadataProvider { getMetadata(sourceFile: ts.SourceFile): ModuleMetadata|undefined; } interface GenSourceFile { externalReferences: Set<string>; sourceFile: ts.SourceFile; emitCtx: EmitterVisitorContext; } export interface CodeGenerator { generateFile(genFileName: string, baseFileName?: string): GeneratedFile; findGeneratedFileNames(fileName: string): string[]; } function assert<T>(condition: T | null | undefined) { if (!condition) { // TODO(chuckjaz): do the right thing } return condition !; } /** * Implements the following hosts based on an api.CompilerHost: * - ts.CompilerHost to be consumed by a ts.Program * - AotCompilerHost for @angular/compiler * - TypeCheckHost for mapping ts errors to ng errors (via translateDiagnostics) */ export class TsCompilerAotCompilerTypeCheckHostAdapter implements ts.CompilerHost, AotCompilerHost, TypeCheckHost { private metadataReaderCache = createMetadataReaderCache(); private flatModuleIndexCache = new Map<string, boolean>(); private flatModuleIndexNames = new Set<string>(); private flatModuleIndexRedirectNames = new Set<string>(); private rootDirs: string[]; private moduleResolutionCache: ts.ModuleResolutionCache; private originalSourceFiles = new Map<string, ts.SourceFile|undefined>(); private originalFileExistsCache = new Map<string, boolean>(); private generatedSourceFiles = new Map<string, GenSourceFile>(); private generatedCodeFor = new Map<string, string[]>(); private emitter = new TypeScriptEmitter(); private metadataReaderHost: MetadataReaderHost; getCancellationToken: () => ts.CancellationToken; getDefaultLibLocation: () => string; trace: (s: string) => void; getDirectories: (path: string) => string[]; directoryExists?: (directoryName: string) => boolean; constructor( private rootFiles: string[], private options: CompilerOptions, private context: CompilerHost, private metadataProvider: MetadataProvider, private codeGenerator: CodeGenerator, private librarySummaries = new Map<string, LibrarySummary>()) { this.moduleResolutionCache = ts.createModuleResolutionCache( this.context.getCurrentDirectory !(), this.context.getCanonicalFileName.bind(this.context)); const basePath = this.options.basePath !; this.rootDirs = (this.options.rootDirs || [this.options.basePath !]).map(p => path.resolve(basePath, p)); if (context.getDirectories) { this.getDirectories = path => context.getDirectories !(path); } if (context.directoryExists) { this.directoryExists = directoryName => context.directoryExists !(directoryName); } if (context.getCancellationToken) { this.getCancellationToken = () => context.getCancellationToken !(); } if (context.getDefaultLibLocation) { this.getDefaultLibLocation = () => context.getDefaultLibLocation !(); } if (context.trace) { this.trace = s => context.trace !(s); } if (context.fileNameToModuleName) { this.fileNameToModuleName = context.fileNameToModuleName.bind(context); } // Note: don't copy over context.moduleNameToFileName as we first // normalize undefined containingFile to a filled containingFile. if (context.resourceNameToFileName) { this.resourceNameToFileName = context.resourceNameToFileName.bind(context); } if (context.toSummaryFileName) { this.toSummaryFileName = context.toSummaryFileName.bind(context); } if (context.fromSummaryFileName) { this.fromSummaryFileName = context.fromSummaryFileName.bind(context); } this.metadataReaderHost = { cacheMetadata: () => true, getSourceFileMetadata: (filePath) => { const sf = this.getOriginalSourceFile(filePath); return sf ? this.metadataProvider.getMetadata(sf) : undefined; }, fileExists: (filePath) => this.originalFileExists(filePath), readFile: (filePath) => assert(this.context.readFile(filePath)), }; } private resolveModuleName(moduleName: string, containingFile: string): ts.ResolvedModule |undefined { const rm = ts.resolveModuleName( moduleName, containingFile.replace(/\\/g, '/'), this.options, this, this.moduleResolutionCache) .resolvedModule; if (rm && this.isSourceFile(rm.resolvedFileName)) { // Case: generateCodeForLibraries = true and moduleName is // a .d.ts file in a node_modules folder. // Need to set isExternalLibraryImport to false so that generated files for that file // are emitted. rm.isExternalLibraryImport = false; } return rm; } // Note: We implement this method so that TypeScript and Angular share the same // ts.ModuleResolutionCache // and that we can tell ts.Program about our different opinion about // ResolvedModule.isExternalLibraryImport // (see our isSourceFile method). resolveModuleNames(moduleNames: string[], containingFile: string): ts.ResolvedModule[] { // TODO(tbosch): this seems to be a typing error in TypeScript, // as it contains assertions that the result contains the same number of entries // as the given module names. return <ts.ResolvedModule[]>moduleNames.map( moduleName => this.resolveModuleName(moduleName, containingFile)); } moduleNameToFileName(m: string, containingFile?: string): string|null { if (!containingFile) { if (m.indexOf('.') === 0) { throw new Error('Resolution of relative paths requires a containing file.'); } // Any containing file gives the same result for absolute imports containingFile = this.rootFiles[0]; } if (this.context.moduleNameToFileName) { return this.context.moduleNameToFileName(m, containingFile); } const resolved = this.resolveModuleName(m, containingFile); return resolved ? resolved.resolvedFileName : null; } /** * We want a moduleId that will appear in import statements in the generated code * which will be written to `containingFile`. * * Note that we also generate files for files in node_modules, as libraries * only ship .metadata.json files but not the generated code. * * Logic: * 1. if the importedFile and the containingFile are from the project sources * or from the same node_modules package, use a relative path * 2. if the importedFile is in a node_modules package, * use a path that starts with the package name. * 3. Error if the containingFile is in the node_modules package * and the importedFile is in the project soures, * as that is a violation of the principle that node_modules packages cannot * import project sources. */ fileNameToModuleName(importedFile: string, containingFile: string): string { const originalImportedFile = importedFile; if (this.options.traceResolution) { console.error( 'fileNameToModuleName from containingFile', containingFile, 'to importedFile', importedFile); } // drop extension importedFile = importedFile.replace(EXT, ''); const importedFilePackagName = getPackageName(importedFile); const containingFilePackageName = getPackageName(containingFile); let moduleName: string; if (importedFilePackagName === containingFilePackageName || GENERATED_FILES.test(originalImportedFile)) { const rootedContainingFile = relativeToRootDirs(containingFile, this.rootDirs); const rootedImportedFile = relativeToRootDirs(importedFile, this.rootDirs); if (rootedContainingFile !== containingFile && rootedImportedFile !== importedFile) { // if both files are contained in the `rootDirs`, then strip the rootDirs containingFile = rootedContainingFile; importedFile = rootedImportedFile; } moduleName = dotRelative(path.dirname(containingFile), importedFile); } else if (importedFilePackagName) { moduleName = stripNodeModulesPrefix(importedFile); } else { throw new Error( `Trying to import a source file from a node_modules package: import ${originalImportedFile} from ${containingFile}`); } return moduleName; } resourceNameToFileName(resourceName: string, containingFile: string): string|null { // Note: we convert package paths into relative paths to be compatible with the the // previous implementation of UrlResolver. const firstChar = resourceName[0]; if (firstChar === '/') { resourceName = resourceName.slice(1); } else if (firstChar !== '.') { resourceName = `./${resourceName}`; } const filePathWithNgResource = this.moduleNameToFileName(addNgResourceSuffix(resourceName), containingFile); return filePathWithNgResource ? stripNgResourceSuffix(filePathWithNgResource) : null; } toSummaryFileName(fileName: string, referringSrcFileName: string): string { return this.fileNameToModuleName(fileName, referringSrcFileName); } fromSummaryFileName(fileName: string, referringLibFileName: string): string { const resolved = this.moduleNameToFileName(fileName, referringLibFileName); if (!resolved) { throw new Error(`Could not resolve ${fileName} from ${referringLibFileName}`); } return resolved; } parseSourceSpanOf(fileName: string, line: number, character: number): ParseSourceSpan|null { const data = this.generatedSourceFiles.get(fileName); if (data && data.emitCtx) { return data.emitCtx.spanOf(line, character); } return null; } private getOriginalSourceFile( filePath: string, languageVersion?: ts.ScriptTarget, onError?: ((message: string) => void)|undefined): ts.SourceFile|null { // Note: we need the explicit check via `has` as we also cache results // that were null / undefined. if (this.originalSourceFiles.has(filePath)) { return this.originalSourceFiles.get(filePath) !; } if (!languageVersion) { languageVersion = this.options.target || ts.ScriptTarget.Latest; } // Note: This can also return undefined, // as the TS typings are not correct! const sf = this.context.getSourceFile(filePath, languageVersion, onError) || null; this.originalSourceFiles.set(filePath, sf); return sf; } updateGeneratedFile(genFile: GeneratedFile): ts.SourceFile { if (!genFile.stmts) { throw new Error( `Invalid Argument: Expected a GenerateFile with statements. ${genFile.genFileUrl}`); } const oldGenFile = this.generatedSourceFiles.get(genFile.genFileUrl); if (!oldGenFile) { throw new Error(`Illegal State: previous GeneratedFile not found for ${genFile.genFileUrl}.`); } const newRefs = genFileExternalReferences(genFile); const oldRefs = oldGenFile.externalReferences; let refsAreEqual = oldRefs.size === newRefs.size; if (refsAreEqual) { newRefs.forEach(r => refsAreEqual = refsAreEqual && oldRefs.has(r)); } if (!refsAreEqual) { throw new Error( `Illegal State: external references changed in ${genFile.genFileUrl}.\nOld: ${Array.from(oldRefs)}.\nNew: ${Array.from(newRefs)}`); } return this.addGeneratedFile(genFile, newRefs); } private addGeneratedFile(genFile: GeneratedFile, externalReferences: Set<string>): ts.SourceFile { if (!genFile.stmts) { throw new Error( `Invalid Argument: Expected a GenerateFile with statements. ${genFile.genFileUrl}`); } const {sourceText, context} = this.emitter.emitStatementsAndContext( genFile.genFileUrl, genFile.stmts, /* preamble */ '', /* emitSourceMaps */ false); const sf = ts.createSourceFile( genFile.genFileUrl, sourceText, this.options.target || ts.ScriptTarget.Latest); if ((this.options.module === ts.ModuleKind.AMD || this.options.module === ts.ModuleKind.UMD) && this.context.amdModuleName) { const moduleName = this.context.amdModuleName(sf); if (moduleName) sf.moduleName = moduleName; } this.generatedSourceFiles.set(genFile.genFileUrl, { sourceFile: sf, emitCtx: context, externalReferences, }); return sf; } shouldGenerateFile(fileName: string): {generate: boolean, baseFileName?: string} { // TODO(tbosch): allow generating files that are not in the rootDir // See https://github.com/angular/angular/issues/19337 if (!isInRootDir(fileName, this.options)) { return {generate: false}; } const genMatch = GENERATED_FILES.exec(fileName); if (!genMatch) { return {generate: false}; } const [, base, genSuffix, suffix] = genMatch; if (suffix !== 'ts') { return {generate: false}; } let baseFileName: string|undefined; if (genSuffix.indexOf('ngstyle') >= 0) { // Note: ngstyle files have names like `afile.css.ngstyle.ts` if (!this.originalFileExists(base)) { return {generate: false}; } } else { // Note: on-the-fly generated files always have a `.ts` suffix, // but the file from which we generated it can be a `.ts`/ `.d.ts` // (see options.generateCodeForLibraries). baseFileName = [`${base}.ts`, `${base}.d.ts`].find( baseFileName => this.isSourceFile(baseFileName) && this.originalFileExists(baseFileName)); if (!baseFileName) { return {generate: false}; } } return {generate: true, baseFileName}; } shouldGenerateFilesFor(fileName: string) { // TODO(tbosch): allow generating files that are not in the rootDir // See https://github.com/angular/angular/issues/19337 return !GENERATED_FILES.test(fileName) && this.isSourceFile(fileName) && isInRootDir(fileName, this.options); } getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: ((message: string) => void)|undefined): ts.SourceFile { // Note: Don't exit early in this method to make sure // we always have up to date references on the file! let genFileNames: string[] = []; let sf = this.getGeneratedFile(fileName); if (!sf) { const summary = this.librarySummaries.get(fileName); if (summary) { if (!summary.sourceFile) { summary.sourceFile = ts.createSourceFile( fileName, summary.text, this.options.target || ts.ScriptTarget.Latest); } sf = summary.sourceFile; genFileNames = []; } } if (!sf) { sf = this.getOriginalSourceFile(fileName); const cachedGenFiles = this.generatedCodeFor.get(fileName); if (cachedGenFiles) { genFileNames = cachedGenFiles; } else { if (!this.options.noResolve && this.shouldGenerateFilesFor(fileName)) { genFileNames = this.codeGenerator.findGeneratedFileNames(fileName).filter( fileName => this.shouldGenerateFile(fileName).generate); } this.generatedCodeFor.set(fileName, genFileNames); } } if (sf) { addReferencesToSourceFile(sf, genFileNames); } // TODO(tbosch): TypeScript's typings for getSourceFile are incorrect, // as it can very well return undefined. return sf !; } private getGeneratedFile(fileName: string): ts.SourceFile|null { const genSrcFile = this.generatedSourceFiles.get(fileName); if (genSrcFile) { return genSrcFile.sourceFile; } const {generate, baseFileName} = this.shouldGenerateFile(fileName); if (generate) { const genFile = this.codeGenerator.generateFile(fileName, baseFileName); return this.addGeneratedFile(genFile, genFileExternalReferences(genFile)); } return null; } private originalFileExists(fileName: string): boolean { let fileExists = this.originalFileExistsCache.get(fileName); if (fileExists == null) { fileExists = this.context.fileExists(fileName); this.originalFileExistsCache.set(fileName, fileExists); } return fileExists; } fileExists(fileName: string): boolean { fileName = stripNgResourceSuffix(fileName); if (this.librarySummaries.has(fileName) || this.generatedSourceFiles.has(fileName)) { return true; } if (this.shouldGenerateFile(fileName).generate) { return true; } return this.originalFileExists(fileName); } loadSummary(filePath: string): string|null { const summary = this.librarySummaries.get(filePath); if (summary) { return summary.text; } if (this.originalFileExists(filePath)) { return assert(this.context.readFile(filePath)); } return null; } isSourceFile(filePath: string): boolean { // Don't generate any files nor typecheck them // if skipTemplateCodegen is set and fullTemplateTypeCheck is not yet set, // for backwards compatibility. if (this.options.skipTemplateCodegen && !this.options.fullTemplateTypeCheck) { return false; } // If we have a summary from a previous compilation, // treat the file never as a source file. if (this.librarySummaries.has(filePath)) { return false; } if (GENERATED_FILES.test(filePath)) { return false; } if (this.options.generateCodeForLibraries === false && DTS.test(filePath)) { return false; } if (DTS.test(filePath)) { // Check for a bundle index. if (this.hasBundleIndex(filePath)) { const normalFilePath = path.normalize(filePath); return this.flatModuleIndexNames.has(normalFilePath) || this.flatModuleIndexRedirectNames.has(normalFilePath); } } return true; } readFile(fileName: string) { const summary = this.librarySummaries.get(fileName); if (summary) { return summary.text; } return this.context.readFile(fileName); } getMetadataFor(filePath: string): ModuleMetadata[]|undefined { return readMetadata(filePath, this.metadataReaderHost, this.metadataReaderCache); } loadResource(filePath: string): Promise<string>|string { if (this.context.readResource) return this.context.readResource(filePath); if (!this.originalFileExists(filePath)) { throw syntaxError(`Error: Resource file not found: ${filePath}`); } return assert(this.context.readFile(filePath)); } private hasBundleIndex(filePath: string): boolean { const checkBundleIndex = (directory: string): boolean => { let result = this.flatModuleIndexCache.get(directory); if (result == null) { if (path.basename(directory) == 'node_module') { // Don't look outside the node_modules this package is installed in. result = false; } else { // A bundle index exists if the typings .d.ts file has a metadata.json that has an // importAs. try { const packageFile = path.join(directory, 'package.json'); if (this.originalFileExists(packageFile)) { // Once we see a package.json file, assume false until it we find the bundle index. result = false; const packageContent: any = JSON.parse(assert(this.context.readFile(packageFile))); if (packageContent.typings) { const typings = path.normalize(path.join(directory, packageContent.typings)); if (DTS.test(typings)) { const metadataFile = typings.replace(DTS, '.metadata.json'); if (this.originalFileExists(metadataFile)) { const metadata = JSON.parse(assert(this.context.readFile(metadataFile))); if (metadata.flatModuleIndexRedirect) { this.flatModuleIndexRedirectNames.add(typings); // Note: don't set result = true, // as this would mark this folder // as having a bundleIndex too early without // filling the bundleIndexNames. } else if (metadata.importAs) { this.flatModuleIndexNames.add(typings); result = true; } } } } } else { const parent = path.dirname(directory); if (parent != directory) { // Try the parent directory. result = checkBundleIndex(parent); } else { result = false; } } } catch (e) { // If we encounter any errors assume we this isn't a bundle index. result = false; } } this.flatModuleIndexCache.set(directory, result); } return result; }; return checkBundleIndex(path.dirname(filePath)); } getDefaultLibFileName = (options: ts.CompilerOptions) => this.context.getDefaultLibFileName(options) getCurrentDirectory = () => this.context.getCurrentDirectory(); getCanonicalFileName = (fileName: string) => this.context.getCanonicalFileName(fileName); useCaseSensitiveFileNames = () => this.context.useCaseSensitiveFileNames(); getNewLine = () => this.context.getNewLine(); // Make sure we do not `host.realpath()` from TS as we do not want to resolve symlinks. // https://github.com/Microsoft/TypeScript/issues/9552 realPath = (p: string) => p; writeFile = this.context.writeFile.bind(this.context); } function genFileExternalReferences(genFile: GeneratedFile): Set<string> { return new Set(collectExternalReferences(genFile.stmts !).map(er => er.moduleName !)); } function addReferencesToSourceFile(sf: ts.SourceFile, genFileNames: string[]) { // Note: as we modify ts.SourceFiles we need to keep the original // value for `referencedFiles` around in cache the original host is caching ts.SourceFiles. // Note: cloning the ts.SourceFile is expensive as the nodes in have parent pointers, // i.e. we would also need to clone and adjust all nodes. let originalReferencedFiles: ts.FileReference[]|undefined = (sf as any).originalReferencedFiles; if (!originalReferencedFiles) { originalReferencedFiles = sf.referencedFiles; (sf as any).originalReferencedFiles = originalReferencedFiles; } const newReferencedFiles = [...originalReferencedFiles]; genFileNames.forEach(gf => newReferencedFiles.push({fileName: gf, pos: 0, end: 0})); sf.referencedFiles = newReferencedFiles; } export function getOriginalReferences(sourceFile: ts.SourceFile): ts.FileReference[]|undefined { return sourceFile && (sourceFile as any).originalReferencedFiles; } function dotRelative(from: string, to: string): string { const rPath: string = path.relative(from, to).replace(/\\/g, '/'); return rPath.startsWith('.') ? rPath : './' + rPath; } /** * Moves the path into `genDir` folder while preserving the `node_modules` directory. */ function getPackageName(filePath: string): string|null { const match = NODE_MODULES_PACKAGE_NAME.exec(filePath); return match ? match[1] : null; } function stripNodeModulesPrefix(filePath: string): string { return filePath.replace(/.*node_modules\//, ''); } function getNodeModulesPrefix(filePath: string): string|null { const match = /.*node_modules\//.exec(filePath); return match ? match[1] : null; } function stripNgResourceSuffix(fileName: string): string { return fileName.replace(/\.\$ngresource\$.*/, ''); } function addNgResourceSuffix(fileName: string): string { return `${fileName}.$ngresource$`; }
gjungb/angular
packages/compiler-cli/src/transformers/compiler_host.ts
TypeScript
mit
24,590
/** * @author fengchen, Dongyun Jin, Patrick Meredith, Michael Ilseman * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package llvmmop; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.List; import com.runtimeverification.rvmonitor.java.rvj.Main; import llvmmop.parser.ast.MOPSpecFile; import llvmmop.util.Tool; import llvmmop.util.AJFileCombiner; class JavaFileFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".java"); } } class MOPFileFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".mop"); } } public class LLVMMOPMain { static File outputDir = null; public static boolean debug = false; public static boolean noopt1 = false; public static boolean toJavaLib = false; public static boolean statistics = false; public static boolean statistics2 = false; public static String aspectname = null; public static boolean specifiedAJName = false; public static boolean isJarFile = false; public static String jarFilePath = null; public static final int NONE = 0; public static final int HANDLERS = 1; public static final int EVENTS = 2; public static int logLevel = NONE; public static boolean dacapo = false; public static boolean dacapo2 = false; public static boolean silent = false; public static boolean empty_advicebody = false; public static boolean translate2RV = true; public static boolean merge = false; public static boolean inline = false; public static boolean scalable = false; public static boolean keepRVFiles = false; public static List<String []> listFilePairs = new ArrayList<String []>(); public static List<String> listRVMFiles = new ArrayList<String>(); static private File getTargetDir(ArrayList<File> specFiles) throws MOPException{ if(LLVMMOPMain.outputDir != null){ return outputDir; } boolean sameDir = true; File parentFile = null; for(File file : specFiles){ if(parentFile == null){ parentFile = file.getAbsoluteFile().getParentFile(); } else { if(file.getAbsoluteFile().getParentFile().equals(parentFile)){ continue; } else { sameDir = false; break; } } } if(sameDir){ return parentFile; } else { return new File("."); } } /** * Process a java file including mop annotations to generate an aspect file. The path argument should be an existing java file name. The location * argument should contain the original file name, But it may have a different directory. * * @param path * an absolute path of a specification file * @param location * an absolute path for result file */ public static void processJavaFile(File file, String location) throws MOPException { MOPNameSpace.init(); String specStr = SpecExtractor.process(file); MOPSpecFile spec = SpecExtractor.parse(specStr); if (LLVMMOPMain.aspectname == null) { LLVMMOPMain.aspectname = Tool.getFileName(file.getAbsolutePath()); } MOPProcessor processor = new MOPProcessor(LLVMMOPMain.aspectname); String aspect = processor.process(spec); writeFile(aspect, location, "MonitorAspect.aj"); } /** * Process a specification file to generate an aspect file. The path argument should be an existing specification file name. The location * argument should contain the original file name, But it may have a different directory. * * @param path * an absolute path of a specification file * @param location * an absolute path for result file */ public static void processSpecFile(File file, String location) throws MOPException { MOPNameSpace.init(); String specStr = SpecExtractor.process(file); MOPSpecFile spec = SpecExtractor.parse(specStr); if (LLVMMOPMain.aspectname == null) { LLVMMOPMain.aspectname = Tool.getFileName(file.getAbsolutePath()); } MOPProcessor processor = new MOPProcessor(LLVMMOPMain.aspectname); String output = processor.process(spec); if (translate2RV) { writeFile(processor.translate2RV(spec), file.getAbsolutePath(), ".rvm"); } if (toJavaLib) { writeFile(output, location, "JavaLibMonitor.java"); } else { writeFile(output, location, "MonitorAspect.aj"); } } public static void processMultipleFiles(ArrayList<File> specFiles) throws MOPException { String aspectName; if(outputDir == null){ outputDir = getTargetDir(specFiles); } if(LLVMMOPMain.aspectname != null) { aspectName = LLVMMOPMain.aspectname; } else { if(specFiles.size() == 1) { aspectName = Tool.getFileName(specFiles.get(0).getAbsolutePath()); } else { int suffixNumber = 0; // generate auto name like 'MultiMonitorApsect.aj' File aspectFile; do{ suffixNumber++; aspectFile = new File(outputDir.getAbsolutePath() + File.separator + "MultiSpec_" + suffixNumber + "MonitorAspect.aj"); } while(aspectFile.exists()); aspectName = "MultiSpec_" + suffixNumber; } LLVMMOPMain.aspectname = aspectName; } MOPProcessor processor = new MOPProcessor(aspectName); MOPNameSpace.init(); ArrayList<MOPSpecFile> specs = new ArrayList<MOPSpecFile>(); for(File file : specFiles){ String specStr = SpecExtractor.process(file); MOPSpecFile spec = SpecExtractor.parse(specStr); if (translate2RV) { writeFile(processor.translate2RV(spec), file.getAbsolutePath(), ".rvm"); } specs.add(spec); } MOPSpecFile combinedSpec = SpecCombiner.process(specs); String output = processor.process(combinedSpec); writeCombinedAspectFile(output, aspectName); } protected static void writeJavaFile(String javaContent, String location) throws MOPException { if ((javaContent == null) || (javaContent.length() == 0)) throw new MOPException("Nothing to write as a java file"); if (!Tool.isJavaFile(location)) throw new MOPException(location + "should be a Java file!"); try { FileWriter f = new FileWriter(location); f.write(javaContent); f.close(); } catch (Exception e) { throw new MOPException(e.getMessage()); } } protected static void writeCombinedAspectFile(String aspectContent, String aspectName) throws MOPException { if (aspectContent == null || aspectContent.length() == 0) return; try { FileWriter f = new FileWriter(outputDir.getAbsolutePath() + File.separator + aspectName + "MonitorAspect.aj"); f.write(aspectContent); f.close(); } catch (Exception e) { throw new MOPException(e.getMessage()); } System.out.println(" " + aspectName + "MonitorAspect.aj is generated"); } protected static void writeFile(String content, String location, String suffix) throws MOPException { if (content == null || content.length() == 0) return; int i = location.lastIndexOf(File.separator); String filePath = ""; try { filePath = location.substring(0, i + 1) + Tool.getFileName(location) + suffix; FileWriter f = new FileWriter(filePath); f.write(content); f.close(); } catch (Exception e) { throw new MOPException(e.getMessage()); } if (suffix.equals(".rvm")) { listRVMFiles.add(filePath); } System.out.println(" " + Tool.getFileName(location) + suffix + " is generated"); } // PM protected static void writePluginOutputFile(String pluginOutput, String location) throws MOPException { int i = location.lastIndexOf(File.separator); try { FileWriter f = new FileWriter(location.substring(0, i + 1) + Tool.getFileName(location) + "PluginOutput.txt"); f.write(pluginOutput); f.close(); } catch (Exception e) { throw new MOPException(e.getMessage()); } System.out.println(" " + Tool.getFileName(location) + "PluginOutput.txt is generated"); } public static String polishPath(String path) { if (path.indexOf("%20") > 0) path = path.replaceAll("%20", " "); return path; } public static ArrayList<File> collectFiles(String[] files, String path) throws MOPException { ArrayList<File> ret = new ArrayList<File>(); for (String file : files) { String fPath = path.length() == 0 ? file : path + File.separator + file; File f = new File(fPath); if (!f.exists()) { throw new MOPException("[Error] Target file, " + file + ", doesn't exsit!"); } else if (f.isDirectory()) { ret.addAll(collectFiles(f.list(new JavaFileFilter()), f.getAbsolutePath())); ret.addAll(collectFiles(f.list(new MOPFileFilter()), f.getAbsolutePath())); } else { if (Tool.isSpecFile(file)) { ret.add(f); } else if (Tool.isJavaFile(file)) { ret.add(f); } else throw new MOPException("Unrecognized file type! The JavaMOP specification file should have .mop as the extension."); } } return ret; } public static void process(String[] files, String path) throws MOPException { ArrayList<File> specFiles = collectFiles(files, path); if(LLVMMOPMain.aspectname != null && files.length > 1){ LLVMMOPMain.merge = true; } if (LLVMMOPMain.merge) { System.out.println("-Processing " + specFiles.size() + " specification(s)"); processMultipleFiles(specFiles); String javaFile = outputDir.getAbsolutePath() + File.separator + LLVMMOPMain.aspectname + "RuntimeMonitor.java"; String ajFile = outputDir.getAbsolutePath() + File.separator + LLVMMOPMain.aspectname + "MonitorAspect.aj"; String combinerArgs[] = new String[2]; combinerArgs[0] = javaFile; combinerArgs[1] = ajFile; listFilePairs.add(combinerArgs); } else { for (File file : specFiles) { boolean needResetAspectName = LLVMMOPMain.aspectname == null; String location = outputDir == null ? file.getAbsolutePath() : outputDir.getAbsolutePath() + File.separator + file.getName(); System.out.println("-Processing " + file.getPath()); if (Tool.isSpecFile(file.getName())) { processSpecFile(file, location); } else if (Tool.isJavaFile(file.getName())) { processJavaFile(file, location); } File combineDir = outputDir == null ? file.getAbsoluteFile() .getParentFile() : outputDir; String javaFile = combineDir.getAbsolutePath() + File.separator + LLVMMOPMain.aspectname + "RuntimeMonitor.java"; String ajFile = combineDir.getAbsolutePath() + File.separator + LLVMMOPMain.aspectname + "MonitorAspect.aj"; String combinerArgs[] = new String[2]; combinerArgs[0] = javaFile; combinerArgs[1] = ajFile; listFilePairs.add(combinerArgs); if (needResetAspectName) { LLVMMOPMain.aspectname = null; } } } } public static void process(String arg) throws MOPException { if(outputDir != null && !outputDir.exists()) throw new MOPException("The output directory, " + outputDir.getPath() + " does not exist."); process(arg.split(";"), ""); } // PM public static void print_help() { System.out.println("Usage: java [-cp javmaop_classpath] llvmmop.LLVMMOPMain [-options] files"); System.out.println(""); System.out.println("where options include:"); System.out.println(" Options enabled by default are prefixed with \'+\'"); System.out.println(" -h -help\t\t\t print this help message"); System.out.println(" -v | -verbose\t\t enable verbose output"); System.out.println(" -debug\t\t\t enable verbose error message"); System.out.println(); System.out.println(" -local\t\t\t+ use local logic engine"); System.out.println(" -remote\t\t\t use default remote logic engine"); System.out.println("\t\t\t\t " + Configuration.getServerAddr()); System.out.println("\t\t\t\t (You can change the default address"); System.out.println("\t\t\t\t in llvmmop/config/remote_server_addr.properties)"); System.out.println(" -remote:<server address>\t use remote logic engine"); System.out.println(); System.out.println(" -d <output path>\t\t select directory to store output files"); System.out.println(" -n | -aspectname <aspect name>\t use the given aspect name instead of source code name"); System.out.println(); System.out.println(" -showevents\t\t\t show every event/handler occurrence"); System.out.println(" -showhandlers\t\t\t show every handler occurrence"); System.out.println(); System.out.println(" -s | -statistics\t\t generate monitor with statistics"); System.out.println(" -noopt1\t\t\t don't use the enable set optimization"); System.out.println(" -javalib\t\t\t generate a java library rather than an AspectJ file"); System.out.println(); System.out.println(" -aspect:\"<command line>\"\t compile the result right after it is generated"); System.out.println(); } public static void main(String[] args) { ClassLoader loader = LLVMMOPMain.class.getClassLoader(); String mainClassPath = loader.getResource("llvmmop/LLVMMOPMain.class").toString(); if (mainClassPath.endsWith(".jar!/llvmmop/LLVMMOPMain.class") && mainClassPath.startsWith("jar:")) { isJarFile = true; jarFilePath = mainClassPath.substring("jar:file:".length(), mainClassPath.length() - "!/llvmmop/LLVMMOPMain.class".length()); jarFilePath = polishPath(jarFilePath); } int i = 0; String files = ""; while (i < args.length) { if (args[i].compareTo("-h") == 0 || args[i].compareTo("-help") == 0) { print_help(); return; } if (args[i].compareTo("-d") == 0) { i++; outputDir = new File(args[i]); } else if (args[i].compareTo("-local") == 0) { } else if (args[i].compareTo("-remote") == 0) { } else if (args[i].startsWith("-remote:")) { } else if (args[i].compareTo("-v") == 0 || args[i].compareTo("-verbose") == 0) { MOPProcessor.verbose = true; } else if (args[i].compareTo("-javalib") == 0) { toJavaLib = true; } else if (args[i].compareTo("-debug") == 0) { LLVMMOPMain.debug = true; } else if (args[i].compareTo("-noopt1") == 0) { LLVMMOPMain.noopt1 = true; } else if (args[i].compareTo("-s") == 0 || args[i].compareTo("-statistics") == 0) { LLVMMOPMain.statistics = true; } else if (args[i].compareTo("-s2") == 0 || args[i].compareTo("-statistics2") == 0) { LLVMMOPMain.statistics2 = true; } else if (args[i].compareTo("-n") == 0 || args[i].compareTo("-aspectname") == 0) { i++; LLVMMOPMain.aspectname = args[i]; LLVMMOPMain.specifiedAJName = true; } else if (args[i].compareTo("-showhandlers") == 0) { if (LLVMMOPMain.logLevel < LLVMMOPMain.HANDLERS) LLVMMOPMain.logLevel = LLVMMOPMain.HANDLERS; } else if (args[i].compareTo("-showevents") == 0) { if (LLVMMOPMain.logLevel < LLVMMOPMain.EVENTS) LLVMMOPMain.logLevel = LLVMMOPMain.EVENTS; } else if (args[i].compareTo("-dacapo") == 0) { LLVMMOPMain.dacapo = true; } else if (args[i].compareTo("-dacapo2") == 0) { LLVMMOPMain.dacapo2 = true; } else if (args[i].compareTo("-silent") == 0) { LLVMMOPMain.silent = true; } else if (args[i].compareTo("-merge") == 0) { LLVMMOPMain.merge = true; } else if (args[i].compareTo("-inline") == 0) { LLVMMOPMain.inline = true; } else if (args[i].compareTo("-noadvicebody") == 0) { LLVMMOPMain.empty_advicebody = true; } else if (args[i].compareTo("-scalable") == 0) { LLVMMOPMain.scalable = true; } else if (args[i].compareTo("-translate2RV") == 0) { LLVMMOPMain.translate2RV = true; } else if (args[i].compareTo("-keepRVFiles") == 0) { LLVMMOPMain.keepRVFiles = true; } else { if (files.length() != 0) files += ";"; files += args[i]; } ++i; } if (files.length() == 0) { print_help(); return; } // Generate .rvm files and .aj files try { process(files); } catch (Exception e) { System.err.println(e.getMessage()); if (LLVMMOPMain.debug) e.printStackTrace(); } // replace mop with rvm and call rv-monitor int length = args.length; if (LLVMMOPMain.keepRVFiles) { length--; } String rvArgs[] = new String [length]; int p = 0; for (int j = 0; j < args.length; j++) { if (args[j].compareTo("-keepRVFiles") == 0) { // Don't pass keepRVFiles to rvmonitor continue; } rvArgs[p] = args[j].replaceAll("\\.mop", "\\.rvm"); p++; } Main.main(rvArgs); // Call AJFileCombiner here to combine these two // TODO for (String[] filePair : listFilePairs) { AJFileCombiner.main(filePair); File javaFile = new File(filePair[0]); try { if (!LLVMMOPMain.keepRVFiles) { boolean deleted = javaFile.delete(); if (!deleted) { System.err.println("Failed to delete java file: " + filePair[0]); } } } catch (Exception e) { } } for (String rvmFilePath : listRVMFiles) { File rvmFile = new File(rvmFilePath); try { if (!LLVMMOPMain.keepRVFiles) { boolean deleted = rvmFile.delete(); if (!deleted) { System.err.println("Failed to delete java file: " + rvmFilePath); } } } catch (Exception e) { } } } }
runtimeverification/llvmmop
src/llvmmop/LLVMMOPMain.java
Java
mit
17,124
/** * The DOM Element unit handling * * Copyright (C) 2008-2011 Nikolay Nemshilov */ var Element = RightJS.Element = new Class(Wrapper, { /** * constructor * * NOTE: this constructor will dynamically typecast * the wrappers depending on the element tag-name * * @param String element tag name or an HTMLElement instance * @param Object options * @return Element element */ initialize: function(element, options) { Element_initialize(this, element, options); } }, Element_Klass), Element_wrappers = Element.Wrappers = {}, elements_cache = {}, /** * bulds dom-elements * * @param String element tag name * @param Object options * @return HTMLElement */ make_element = function (tag, options) { return (tag in elements_cache ? elements_cache[tag] : ( elements_cache[tag] = document.createElement(tag) )).cloneNode(false); }; // // IE 6,7,8 (not 9!) browsers have a bug with checkbox and radio input elements // it doesn't place the 'checked' property correctly, plus there are some issues // with clonned SELECT objects, so we are replaceing the elements maker in here // if (IE8_OR_LESS) { make_element = function(tag, options) { if (options !== undefined && (tag === 'input' || tag === 'button')) { tag = '<'+ tag +' name="'+ options.name + '" type="'+ options.type +'"'+ (options.checked ? ' checked' : '') + ' />'; delete(options.name); delete(options.type); } return document.createElement(tag); }; } /** * Basic element's constructor * * @param Element wrapper instance * @param mixed raw dom element of a string tag name * @param Object options * @return void */ function Element_initialize(inst, element, options) { if (typeof element === 'string') { inst._ = make_element(element, options); if (options !== undefined) { for (var key in options) { switch (key) { case 'id': inst._.id = options[key]; break; case 'html': inst._.innerHTML = options[key]; break; case 'class': inst._.className = options[key]; break; case 'on': inst.on(options[key]); break; default: inst.set(key, options[key]); } } } } else { inst._ = element; } }
rightjs/rightjs-core
src/dom/element.js
JavaScript
mit
2,291
// dear imgui, v1.71 WIP // (main code and documentation) // Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code. // Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui // Releases change-log at https://github.com/ocornut/imgui/releases // Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started // Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269 // Developed by Omar Cornut and every direct or indirect contributors to the GitHub. // See LICENSE.txt for copyright and licensing details (standard MIT License). // This library is free but I need your support to sustain development and maintenance. // Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README. // Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui. // It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library. // Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without // modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't // come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you // to a better solution or official support for them. /* Index of this file: DOCUMENTATION - MISSION STATEMENT - END-USER GUIDE - PROGRAMMER GUIDE (read me!) - Read first. - How to update to a newer version of Dear ImGui. - Getting started with integrating Dear ImGui in your code/engine. - This is how a simple application may look like (2 variations). - This is how a simple rendering function may look like. - Using gamepad/keyboard navigation controls. - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS - Where is the documentation? - Which version should I get? - Who uses Dear ImGui? - Why the odd dual naming, "Dear ImGui" vs "ImGui"? - How can I tell whether to dispatch mouse/keyboard to imgui or to my application? - How can I display an image? What is ImTextureID, how does it works? - Why are multiple widgets reacting when I interact with a single one? How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack... - How can I use my own math types instead of ImVec2/ImVec4? - How can I load a different font than the default? - How can I easily use icons in my application? - How can I load multiple fonts? - How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic? - How can I interact with standard C++ types (such as std::string and std::vector)? - How can I use the drawing facilities without an ImGui window? (using ImDrawList API) - How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad) - I integrated Dear ImGui in my engine and the text or lines are blurry.. - I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. - How can I help? CODE (search for "[SECTION]" in the code to find them) // [SECTION] FORWARD DECLARATIONS // [SECTION] CONTEXT AND MEMORY ALLOCATORS // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) // [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions) // [SECTION] MISC HELPERS/UTILITIES (ImText* functions) // [SECTION] MISC HELPERS/UTILITIES (Color functions) // [SECTION] ImGuiStorage // [SECTION] ImGuiTextFilter // [SECTION] ImGuiTextBuffer // [SECTION] ImGuiListClipper // [SECTION] RENDER HELPERS // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) // [SECTION] TOOLTIPS // [SECTION] POPUPS // [SECTION] KEYBOARD/GAMEPAD NAVIGATION // [SECTION] COLUMNS // [SECTION] DRAG AND DROP // [SECTION] LOGGING/CAPTURING // [SECTION] SETTINGS // [SECTION] PLATFORM DEPENDENT HELPERS // [SECTION] METRICS/DEBUG WINDOW */ //----------------------------------------------------------------------------- // DOCUMENTATION //----------------------------------------------------------------------------- /* MISSION STATEMENT ================= - Easy to use to create code-driven and data-driven tools. - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools. - Easy to hack and improve. - Minimize screen real-estate usage. - Minimize setup and maintenance. - Minimize state storage on user side. - Portable, minimize dependencies, run on target (consoles, phones, etc.). - Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,. opening a tree node for the first time, etc. but a typical frame should not allocate anything). Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - Doesn't look fancy, doesn't animate. - Limited layout features, intricate layouts are typically crafted in code. END-USER GUIDE ============== - Double-click on title bar to collapse window. - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin(). - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents). - Click and drag on any empty space to move window. - TAB/SHIFT+TAB to cycle through keyboard editable fields. - CTRL+Click on a slider or drag box to input value as text. - Use mouse wheel to scroll. - Text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump. - CTRL+Shift+Left/Right to select words. - CTRL+A our Double-Click to select all. - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/ - CTRL+Z,CTRL+Y to undo/redo. - ESCAPE to revert text to its original value. - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) - Controls are automatically adjusted for OSX to match standard OSX text editing operations. - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard. - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW PROGRAMMER GUIDE ================ READ FIRST: - Read the FAQ below this section! - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs. - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features. - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build. - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori). You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md. - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances. For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI, where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches. - Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right. - This codebase is also optimized to yield decent performances with typical "Debug" builds settings. - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected). If you get an assert, read the messages and comments around the assert. - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace. - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types. See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that. However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase. - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!). HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI: - Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h) - Or maintain your own branch where you have imconfig.h modified. - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes. If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it. Please report any issue to the GitHub page! - Try to keep your copy of dear imgui reasonably up to date. GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE: - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library. - Add the Dear ImGui source files to your projects or using your preferred build system. It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL). - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types. - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them. - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide. Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render(). - Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code. - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder. HOW A SIMPLE APPLICATION MAY LOOK LIKE: EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder). // Application init: create a dear imgui context, setup some options, load fonts ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. // TODO: Fill optional fields of the io structure later. // TODO: Load TTF/OTF fonts if you don't want to use the default font. // Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11) ImGui_ImplWin32_Init(hwnd); ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext); // Application main loop while (true) { // Feed inputs to dear imgui, start new frame ImGui_ImplDX11_NewFrame(); ImGui_ImplWin32_NewFrame(); ImGui::NewFrame(); // Any application code here ImGui::Text("Hello, world!"); // Render dear imgui into screen ImGui::Render(); ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); g_pSwapChain->Present(1, 0); } // Shutdown ImGui_ImplDX11_Shutdown(); ImGui_ImplWin32_Shutdown(); ImGui::DestroyContext(); HOW A SIMPLE APPLICATION MAY LOOK LIKE: EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE. // Application init: create a dear imgui context, setup some options, load fonts ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls. // TODO: Fill optional fields of the io structure later. // TODO: Load TTF/OTF fonts if you don't want to use the default font. // Build and load the texture atlas into a texture // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer) int width, height; unsigned char* pixels = NULL; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // At this point you've got the texture data and you need to upload that your your graphic system: // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'. // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID. MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32) io.Fonts->TexID = (void*)texture; // Application main loop while (true) { // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc. // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings) io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds) io.DisplaySize.x = 1920.0f; // set the current display width io.DisplaySize.y = 1280.0f; // set the current display height here io.MousePos = my_mouse_pos; // set the mouse position io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states io.MouseDown[1] = my_mouse_buttons[1]; // Call NewFrame(), after this point you can use ImGui::* functions anytime // (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere) ImGui::NewFrame(); // Most of your application code here ImGui::Text("Hello, world!"); MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End(); MyGameRender(); // may use any ImGui functions as well! // Render imgui, swap buffers // (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code) ImGui::EndFrame(); ImGui::Render(); ImDrawData* draw_data = ImGui::GetDrawData(); MyImGuiRenderFunction(draw_data); SwapBuffers(); } // Shutdown ImGui::DestroyContext(); HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE: void void MyImGuiRenderFunction(ImDrawData* draw_data) { // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color. for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { // The texture for the draw call is specified by pcmd->TextureId. // The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization. MyEngineBindTexture((MyTexture*)pcmd->TextureId); // We are using scissoring to clip some objects. All low-level graphics API should supports it. // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches // (some elements visible outside their bounds) but you can fix that once everything else works! // - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize) // In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize. // However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github), // always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space. // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min) ImVec2 pos = draw_data->DisplayPos; MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y)); // Render 'pcmd->ElemCount/3' indexed triangles. // By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices. MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer); } idx_buffer += pcmd->ElemCount; } } } - The examples/ folders contains many actual implementation of the pseudo-codes above. - When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated. They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information. - Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues! USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS - The gamepad/keyboard navigation is fairly functional and keeps being improved. - Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse! - You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable. - Gamepad: - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable. - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame(). - See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values: 0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks. - We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone. Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.). - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW. - If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved. - Keyboard: - Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays. - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from: - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set. - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used). - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions. Please reach out if you think the game vs navigation input sharing could be improved. - Mouse: - PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback. - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard. - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag. Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements. When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved. When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that. (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!) (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want to set a boolean to ignore your other external mouse positions until the external source is moved again.) API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix. Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code. When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files. You can read releases logs https://github.com/ocornut/imgui/releases for more details. - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c). - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now. - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete). - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete). - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete). - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value! - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already). - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead! - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete). - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects. - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags. - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files. - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete). - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h. If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths. - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427) - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp. NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED. Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions. - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent). - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete). - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly). - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature. - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency. - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time. - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete). - 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.). old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports. when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call. in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function. - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set. - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details. - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more. If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format. To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code. If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them. - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format", consistent with other functions. Kept redirection functions (will obsolete). - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value. - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch). - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now. - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically. - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums. - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment. - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display. - 2018/02/07 (1.60) - reorganized context handling to be more explicit, - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END. - removed Shutdown() function, as DestroyContext() serve this purpose. - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance. - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts. - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts. - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths. - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete). - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete). - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData. - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side. - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete). - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame. - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set. - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete). - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete). - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete). - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete). - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete). - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed. - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up. Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions. - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency. - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg. - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding. - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows); - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency. - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it. - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details. removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting. - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead! - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete). - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete). - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete). - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)". - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)! - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete). - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete). - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency. - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix. - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame. - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely. - 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete). - 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete). - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton(). - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu. - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options. - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))' - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset. - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity. - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild(). - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it. - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc. - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal. - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore. If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you. If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar. This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color. ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); } If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color. - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext(). - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection. - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen). - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer. - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337). - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337) - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete). - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert. - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you. - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis. - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete. - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position. GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side. GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out! - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project. - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure. you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text. - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost. this necessary change will break your rendering function! the fix should be very easy. sorry for that :( - if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest. - the signature of the io.RenderDrawListsFn handler has changed! old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count) new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data). parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount' ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new. ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'. - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer. - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering! - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade! - 2015/07/10 (1.43) - changed SameLine() parameters from int to float. - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete). - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount. - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry! - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete). - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete). - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons. - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened. - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same). - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50. - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50. - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50. - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing) - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50. - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; } became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; } you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. it is now recommended that you sample the font texture with bilinear interpolation. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== Q: Where is the documentation? A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++. - Run the examples/ and explore them. - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function. - The demo covers most features of Dear ImGui, so you can read the code and see its output. - See documentation and comments at the top of imgui.cpp + effectively imgui.h. - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/ folder to explain how to integrate Dear ImGui with your own engine/application. - Your programming IDE is your friend, find the type or function declaration to find comments associated to it. Q: Which version should I get? A: I occasionally tag Releases (https://github.com/ocornut/imgui/releases) but it is generally safe and recommended to sync to master/latest. The library is fairly stable and regressions tend to be fixed fast when reported. You may also peak at the 'docking' branch which includes: - Docking/Merging features (https://github.com/ocornut/imgui/issues/2109) - Multi-viewport features (https://github.com/ocornut/imgui/issues/1542) Many projects are using this branch and it is kept in sync with master regularly. Q: Who uses Dear ImGui? A: See "Quotes" (https://github.com/ocornut/imgui/wiki/Quotes) and "Software using Dear ImGui" (https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages for a list of games/software which are publicly known to use dear imgui. Please add yours if you can! Q: Why the odd dual naming, "Dear ImGui" vs "ImGui"? A: The library started its life as "ImGui" due to the fact that I didn't give it a proper name when when I released 1.0, and had no particular expectation that it would take off. However, the term IMGUI (immediate-mode graphical user interface) was coined before and is being used in variety of other situations (e.g. Unity uses it own implementation of the IMGUI paradigm). To reduce the ambiguity without affecting existing code bases, I have decided on an alternate, longer name "Dear ImGui" that people can use to refer to this specific library. Please try to refer to this library as "Dear ImGui". Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application? A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } ) - When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application. - When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application. - When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS). Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false. This is because imgui needs to detect that you clicked in the void to unfocus its own windows. Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!). It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs. Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags(). Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.) Q: How can I display an image? What is ImTextureID, how does it works? A: Short explanation: - You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures. - Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value. - Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason). Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward. Long explanation: - Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices. At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.). - Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API. We carry the information to identify a "texture" in the ImTextureID type. ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice. Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function. - In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying an image from the end-user perspective. This is what the _examples_ rendering functions are using: OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp) DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp) DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp) DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp) For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID. Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure tying together both the texture and information about its format and how to read it. - If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them. If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID representation suggested by the example bindings is probably the best choice. (Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer) User code may do: // Cast our texture type to ImTextureID / void* MyTexture* texture = g_CoffeeTableTexture; ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height)); The renderer function called after ImGui::Render() will receive that same value that the user code passed: // Cast ImTextureID / void* stored in the draw command as our texture type MyTexture* texture = (MyTexture*)pcmd->TextureId; MyEngineBindTexture2D(texture); Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui. This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them. If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using. Here's a simplified OpenGL example using stb_image.h: // Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data: #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> [...] int my_image_width, my_image_height; unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4); // Turn the RGBA pixel data into an OpenGL texture: GLuint my_opengl_texture; glGenTextures(1, &my_opengl_texture); glBindTexture(GL_TEXTURE_2D, my_opengl_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data); // Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it: ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height)); C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa. Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*. Examples: GLuint my_tex = XXX; void* my_void_ptr; my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer) my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint ID3D11ShaderResourceView* my_dx11_srv = XXX; void* my_void_ptr; my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void* my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView* Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated. Q: Why are multiple widgets reacting when I interact with a single one? Q: How can I have multiple widgets with the same label or with an empty label? A: A primer on labels and the ID Stack... Dear ImGui internally need to uniquely identify UI elements. Elements that are typically not clickable (such as calls to the Text functions) don't need an ID. Interactive widgets (such as calls to Button buttons) need a unique ID. Unique ID are used internally to track active widgets and occasionally associate state to widgets. Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element. - Unique ID are often derived from a string label: Button("OK"); // Label = "OK", ID = hash of (..., "OK") Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel") - ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having two buttons labeled "OK" in different windows or different tree locations is fine. We used "..." above to signify whatever was already pushed to the ID stack previously: Begin("MyWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK") End(); Begin("MyOtherWindow"); Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK") End(); - If you have a same ID twice in the same location, you'll have a conflict: Button("OK"); Button("OK"); // ID collision! Interacting with either button will trigger the first one. Fear not! this is easy to solve and there are many ways to solve it! - Solving ID conflict in a simple/local context: When passing a label you can optionally specify extra ID information within string itself. Use "##" to pass a complement to the ID that won't be visible to the end-user. This helps solving the simple collision cases when you know e.g. at compilation time which items are going to be created: Begin("MyWindow"); Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play") Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above End(); - If you want to completely hide the label, but still need an ID: Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox! - Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels. For example you may want to include varying information in a window title bar, but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID: Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID") Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different sprintf(buf, "My game (%f FPS)###MyGame", fps); Begin(buf); // Variable title, ID = hash of "MyGame" - Solving ID conflict in a more general manner: Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts within the same window. This is the most convenient way of distinguishing ID when iterating and creating many UI elements programmatically. You can push a pointer, a string or an integer value into the ID stack. Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack. At each level of the stack we store the seed used for items at this level of the ID stack. Begin("Window"); for (int i = 0; i < 100; i++) { PushID(i); // Push i to the id tack Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click") PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj); Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click") PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj->Name); Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click") PopID(); } End(); - You can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of (..., "Click") PushID("node"); Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") PushID(my_ptr); Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click") PopID(); PopID(); - Tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of (..., "Click") if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag) { Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click") TreePop(); } - When working with trees, ID are used to preserve the open/close state of each tree node. Depending on your use cases you may want to use strings, indices or pointers as ID. e.g. when following a single pointer that may change over time, using a static string as ID will preserve your node open/closed state when the targeted object change. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. See what makes more sense in your situation! Q: How can I use my own math types instead of ImVec2/ImVec4? A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions. This way you'll be able to use your own types everywhere, e.g. passing glm::vec2 to ImGui functions instead of ImVec2. Q: How can I load a different font than the default? A: Use the font atlas to load the TTF/OTF file you want: ImGuiIO& io = ImGui::GetIO(); io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code. (Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.) (Read the 'misc/fonts/README.txt' file for more details about font loading.) New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ within a string literal, you need to write it double backslash "\\": io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!) io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT Q: How can I easily use icons in my application? A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your strings. You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment. (Read the 'misc/fonts/README.txt' file for more details about icons font loading.) Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: (Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.) ImGuiIO& io = ImGui::GetIO(); ImFont* font0 = io.Fonts->AddFontDefault(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() // the first loaded font gets used by default // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime // Options ImFontConfig config; config.OversampleH = 2; config.OversampleV = 1; config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config); // Combine multiple fonts into one (e.g. for icon fonts) static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 }; ImFontConfig config; config.MergeMode = true; io.Fonts->AddFontDefault(); io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic? A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. // Add default Japanese ranges io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese()); // Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need) ImVector<ImWchar> ranges; ImFontGlyphRangesBuilder builder; builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters) builder.AddChar(0x7262); // Add a specific character builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted) io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data); All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax. Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work! Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8. Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter(). The applications in examples/ are doing that. Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode). You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state. Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly. Q: How can I interact with standard C++ types (such as std::string and std::vector)? A: - Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers), and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases. - To use ImGui::InputText() with a std::string or any resizable string class, see misc/cpp/imgui_stdlib.h. - To use combo boxes and list boxes with std::vector or any other data structure: the BeginCombo()/EndCombo() API lets you iterate and submit items yourself, so does the ListBoxHeader()/ListBoxFooter() API. Prefer using them over the old and awkward Combo()/ListBox() api. - Generally for most high-level types you should be able to access the underlying data type. You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code). - Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application. Please bear in mind that using std::string on applications with large amount of UI may incur unsatisfactory performances. Modern implementations of std::string often include small-string optimization (which is often a local buffer) but those are not configurable and not the same across implementations. - If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead. One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str This is a small helper where you can instance strings with configurable local buffers length. Many game engines will provide similar or better string helpers. Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API) A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags. (The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse) Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like. - You can call ImGui::GetBackgroundDrawList() or ImGui::GetForegroundDrawList() and use those draw list to display contents behind or over every other imgui windows (one bg/fg drawlist per viewport). - You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data. Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display) A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls". (short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad) - You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy) This is the preferred solution for developer productivity. In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer. Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols. - You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine. - For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing for screen real-estate and precision. Q: I integrated Dear ImGui in my engine and the text or lines are blurry.. A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f). Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension. Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around.. A: You are probably mishandling the clipping rectangles in your render function. Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height). Q: How can I help? A: - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt and see how you want to help and can help! - Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui. - Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README. - Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc. You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1902). Visuals are ideal as they inspire other programmers. But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions. - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately). - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. this is also useful to set yourself in the context of another window (to get/set other settings) - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug". - tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. - tip: you can call Render() multiple times (e.g for VR renders). - tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui! */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #ifndef IMGUI_DEFINE_MATH_OPERATORS #define IMGUI_DEFINE_MATH_OPERATORS #endif #include "imgui_internal.h" #include <ctype.h> // toupper #include <stdio.h> // vsnprintf, sscanf, printf #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif // Debug options #define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL #define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window // Visual Studio warnings #ifdef _MSC_VER #pragma warning (disable: 4127) // condition expression is constant #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif // Clang/GCC warnings with -Weverything #ifdef __clang__ #pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great! #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // #pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic. #pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0 #endif #if __has_warning("-Wdouble-promotion") #pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double. #endif #elif defined(__GNUC__) #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size #pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*' #pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function #pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value #pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked #pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false #if __GNUC__ >= 8 #pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead #endif #endif // When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch. static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear // Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end) static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow(). static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time. //------------------------------------------------------------------------- // [SECTION] FORWARD DECLARATIONS //------------------------------------------------------------------------- static void SetCurrentWindow(ImGuiWindow* window); static void FindHoveredWindow(); static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags); static void CheckStacksSize(ImGuiWindow* window, bool write); static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges); static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list); static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window); static ImRect GetViewportRect(); // Settings static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name); static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line); static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); // Platform Dependents default implementation for IO functions static const char* GetClipboardTextFn_DefaultImpl(void* user_data); static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text); static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); namespace ImGui { static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags); // Navigation static void NavUpdate(); static void NavUpdateWindowing(); static void NavUpdateWindowingList(); static void NavUpdateMoveResult(); static float NavUpdatePageUpPageDown(int allowed_dir_flags); static inline void NavUpdateAnyRequestFlag(); static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id); static ImVec2 NavCalcPreferredRefPos(); static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window); static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window); static int FindWindowFocusIndex(ImGuiWindow* window); // Misc static void UpdateMouseInputs(); static void UpdateMouseWheel(); static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]); static void RenderWindowOuterBorders(ImGuiWindow* window); static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size); static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open); } //----------------------------------------------------------------------------- // [SECTION] CONTEXT AND MEMORY ALLOCATORS //----------------------------------------------------------------------------- // Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL. // ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext(). // 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call // SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading. // In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into. // 2) Important: Dear ImGui functions are not thread-safe because of this pointer. // If you want thread-safety to allow N threads to access N different contexts, you can: // - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h: // struct ImGuiContext; // extern thread_local ImGuiContext* MyImGuiTLS; // #define GImGui MyImGuiTLS // And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword. // - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586 // - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace. #ifndef GImGui ImGuiContext* GImGui = NULL; #endif // Memory Allocator functions. Use SetAllocatorFunctions() to change them. // If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file. // Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction. #ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); } static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); } #else static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; } static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); } #endif static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper; static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper; static void* GImAllocatorUserData = NULL; //----------------------------------------------------------------------------- // [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO) //----------------------------------------------------------------------------- ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested. WindowMinSize = ImVec2(32,32); // Minimum window size WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested. PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested. FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested. ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2). ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1). ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs. TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs. TabBorderSize = 0.0f; // Thickness of border around tabs. ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text. SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text. DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows. DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows. MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later. AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU. AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.) CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality. // Default theme ImGui::StyleColorsDark(this); } // To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you. // Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times. void ImGuiStyle::ScaleAllSizes(float scale_factor) { WindowPadding = ImFloor(WindowPadding * scale_factor); WindowRounding = ImFloor(WindowRounding * scale_factor); WindowMinSize = ImFloor(WindowMinSize * scale_factor); ChildRounding = ImFloor(ChildRounding * scale_factor); PopupRounding = ImFloor(PopupRounding * scale_factor); FramePadding = ImFloor(FramePadding * scale_factor); FrameRounding = ImFloor(FrameRounding * scale_factor); ItemSpacing = ImFloor(ItemSpacing * scale_factor); ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor); TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor); IndentSpacing = ImFloor(IndentSpacing * scale_factor); ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor); ScrollbarSize = ImFloor(ScrollbarSize * scale_factor); ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor); GrabMinSize = ImFloor(GrabMinSize * scale_factor); GrabRounding = ImFloor(GrabRounding * scale_factor); TabRounding = ImFloor(TabRounding * scale_factor); DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor); DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor); MouseCursorScale = ImFloor(MouseCursorScale * scale_factor); } ImGuiIO::ImGuiIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); // Settings ConfigFlags = ImGuiConfigFlags_None; BackendFlags = ImGuiBackendFlags_None; DisplaySize = ImVec2(-1.0f, -1.0f); DeltaTime = 1.0f/60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; for (int i = 0; i < ImGuiKey_COUNT; i++) KeyMap[i] = -1; KeyRepeatDelay = 0.250f; KeyRepeatRate = 0.050f; UserData = NULL; Fonts = NULL; FontGlobalScale = 1.0f; FontDefault = NULL; FontAllowUserScaling = false; DisplayFramebufferScale = ImVec2(1.0f, 1.0f); // Miscellaneous options MouseDrawCursor = false; #ifdef __APPLE__ ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag #else ConfigMacOSXBehaviors = false; #endif ConfigInputTextCursorBlink = true; ConfigWindowsResizeFromEdges = true; ConfigWindowsMoveFromTitleBarOnly = false; // Platform Functions BackendPlatformName = BackendRendererName = NULL; BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL; GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ClipboardUserData = NULL; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; ImeWindowHandle = NULL; #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS RenderDrawListsFn = NULL; #endif // Input (NB: we already have memset zero the entire structure!) MousePos = ImVec2(-FLT_MAX, -FLT_MAX); MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX); MouseDragThreshold = 6.0f; for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f; for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f; for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f; } // Pass in translated ASCII characters for text input. // - with glfw you can get those from the callback set in glfwSetCharCallback() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(unsigned int c) { if (c > 0 && c < 0x10000) InputQueueCharacters.push_back((ImWchar)c); } void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars) { while (*utf8_chars != 0) { unsigned int c = 0; utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL); if (c > 0 && c < 0x10000) InputQueueCharacters.push_back((ImWchar)c); } } void ImGuiIO::ClearInputCharacters() { InputQueueCharacters.resize(0); } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions) //----------------------------------------------------------------------------- ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p) { ImVec2 ap = p - a; ImVec2 ab_dir = b - a; float dot = ap.x * ab_dir.x + ap.y * ab_dir.y; if (dot < 0.0f) return a; float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y; if (dot > ab_len_sqr) return b; return a + ab_dir * dot / ab_len_sqr; } bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) { bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f; bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f; bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f; return ((b1 == b2) && (b2 == b3)); } void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w) { ImVec2 v0 = b - a; ImVec2 v1 = c - a; ImVec2 v2 = p - a; const float denom = v0.x * v1.y - v1.x * v0.y; out_v = (v2.x * v1.y - v1.x * v2.y) / denom; out_w = (v0.x * v2.y - v2.x * v0.y) / denom; out_u = 1.0f - out_v - out_w; } ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p) { ImVec2 proj_ab = ImLineClosestPoint(a, b, p); ImVec2 proj_bc = ImLineClosestPoint(b, c, p); ImVec2 proj_ca = ImLineClosestPoint(c, a, p); float dist2_ab = ImLengthSqr(p - proj_ab); float dist2_bc = ImLengthSqr(p - proj_bc); float dist2_ca = ImLengthSqr(p - proj_ca); float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca)); if (m == dist2_ab) return proj_ab; if (m == dist2_bc) return proj_bc; return proj_ca; } // Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more. int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } int ImStrnicmp(const char* str1, const char* str2, size_t count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } void ImStrncpy(char* dst, const char* src, size_t count) { if (count < 1) return; if (count > 1) strncpy(dst, src, count - 1); dst[count - 1] = 0; } char* ImStrdup(const char* str) { size_t len = strlen(str); void* buf = IM_ALLOC(len + 1); return (char*)memcpy(buf, (const void*)str, len + 1); } char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src) { size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1; size_t src_size = strlen(src) + 1; if (dst_buf_size < src_size) { IM_FREE(dst); dst = (char*)IM_ALLOC(src_size); if (p_dst_size) *p_dst_size = src_size; } return (char*)memcpy(dst, (const void*)src, src_size); } const char* ImStrchrRange(const char* str, const char* str_end, char c) { const char* p = (const char*)memchr(str, (int)c, str_end - str); return p; } int ImStrlenW(const ImWchar* str) { //return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits int n = 0; while (*str++) n++; return n; } // Find end-of-line. Return pointer will point to either first \n, either str_end. const char* ImStreolRange(const char* str, const char* str_end) { const char* p = (const char*)memchr(str, '\n', str_end - str); return p ? p : str_end; } const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line { while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n') buf_mid_line--; return buf_mid_line; } const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end) { if (!needle_end) needle_end = needle + strlen(needle); const char un0 = (char)toupper(*needle); while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end)) { if (toupper(*haystack) == un0) { const char* b = needle + 1; for (const char* a = haystack + 1; b < needle_end; a++, b++) if (toupper(*a) != toupper(*b)) break; if (b == needle_end) return haystack; } haystack++; } return NULL; } // Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible. void ImStrTrimBlanks(char* buf) { char* p = buf; while (p[0] == ' ' || p[0] == '\t') // Leading blanks p++; char* p_start = p; while (*p != 0) // Find end of string p++; while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks p--; if (p_start != buf) // Copy memory if we had leading blanks memmove(buf, p_start, p - p_start); buf[p - p_start] = 0; // Zero terminate } // A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size). // Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm. // B) When buf==NULL vsnprintf() will return the output size. #ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS //#define IMGUI_USE_STB_SPRINTF #ifdef IMGUI_USE_STB_SPRINTF #define STB_SPRINTF_IMPLEMENTATION #include "imstb_sprintf.h" #endif #if defined(_MSC_VER) && !defined(vsnprintf) #define vsnprintf _vsnprintf #endif int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) { va_list args; va_start(args, fmt); #ifdef IMGUI_USE_STB_SPRINTF int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); #else int w = vsnprintf(buf, buf_size, fmt, args); #endif va_end(args); if (buf == NULL) return w; if (w == -1 || w >= (int)buf_size) w = (int)buf_size - 1; buf[w] = 0; return w; } int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) { #ifdef IMGUI_USE_STB_SPRINTF int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args); #else int w = vsnprintf(buf, buf_size, fmt, args); #endif if (buf == NULL) return w; if (w == -1 || w >= (int)buf_size) w = (int)buf_size - 1; buf[w] = 0; return w; } #endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS // CRC32 needs a 1KB lookup table (not cache friendly) // Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily: // - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe. static const ImU32 GCrc32LookupTable[256] = { 0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91, 0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5, 0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59, 0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D, 0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01, 0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65, 0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9, 0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD, 0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1, 0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5, 0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79, 0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D, 0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21, 0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45, 0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9, 0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D, }; // Known size hash // It is ok to call ImHashData on a string with known length but the ### operator won't be supported. // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed) { ImU32 crc = ~seed; const unsigned char* data = (const unsigned char*)data_p; const ImU32* crc32_lut = GCrc32LookupTable; while (data_size-- != 0) crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++]; return ~crc; } // Zero-terminated string hash, with support for ### to reset back to seed value // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. // Because this syntax is rarely used we are optimizing for the common case. // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build) // FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements. ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed) { seed = ~seed; ImU32 crc = seed; const unsigned char* data = (const unsigned char*)data_p; const ImU32* crc32_lut = GCrc32LookupTable; if (data_size != 0) { while (data_size-- != 0) { unsigned char c = *data++; if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } else { while (unsigned char c = *data++) { if (c == '#' && data[0] == '#' && data[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } return ~crc; } FILE* ImFileOpen(const char* filename, const char* mode) { #if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__) // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can) const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1; const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1; ImVector<ImWchar> buf; buf.resize(filename_wsize + mode_wsize); ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL); ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL); return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]); #else return fopen(filename, mode); #endif } // Load file content into memory // Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree() void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes) { IM_ASSERT(filename && file_open_mode); if (out_file_size) *out_file_size = 0; FILE* f; if ((f = ImFileOpen(filename, file_open_mode)) == NULL) return NULL; long file_size_signed; if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return NULL; } size_t file_size = (size_t)file_size_signed; void* file_data = IM_ALLOC(file_size + padding_bytes); if (file_data == NULL) { fclose(f); return NULL; } if (fread(file_data, 1, file_size, f) != file_size) { fclose(f); IM_FREE(file_data); return NULL; } if (padding_bytes > 0) memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes); fclose(f); if (out_file_size) *out_file_size = file_size; return file_data; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILITIES (ImText* functions) //----------------------------------------------------------------------------- // Convert UTF-8 to 32-bits character, process single character input. // Based on stb_from_utf8() from github.com/nothings/stb/ // We handle UTF-8 decoding error by skipping forward. int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { unsigned int c = (unsigned int)-1; const unsigned char* str = (const unsigned char*)in_text; if (!(*str & 0x80)) { c = (unsigned int)(*str++); *out_char = c; return 1; } if ((*str & 0xe0) == 0xc0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 2) return 1; if (*str < 0xc2) return 2; c = (unsigned int)((*str++ & 0x1f) << 6); if ((*str & 0xc0) != 0x80) return 2; c += (*str++ & 0x3f); *out_char = c; return 2; } if ((*str & 0xf0) == 0xe0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 3) return 1; if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3; if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x0f) << 12); if ((*str & 0xc0) != 0x80) return 3; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 3; c += (*str++ & 0x3f); *out_char = c; return 3; } if ((*str & 0xf8) == 0xf0) { *out_char = 0xFFFD; // will be invalid but not end of string if (in_text_end && in_text_end - (const char*)str < 4) return 1; if (*str > 0xf4) return 4; if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4; if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x07) << 18); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 12); if ((*str & 0xc0) != 0x80) return 4; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 4; c += (*str++ & 0x3f); // utf-8 encodings of values used in surrogate pairs are invalid if ((c & 0xFFFFF800) == 0xD800) return 4; *out_char = c; return 4; } *out_char = 0; return 0; } int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes *buf_out++ = (ImWchar)c; } *buf_out = 0; if (in_text_remaining) *in_text_remaining = in_text; return (int)(buf_out - buf); } int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) { int char_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) char_count++; } return char_count; } // Based on stb_to_utf8() from github.com/nothings/stb/ static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c) { if (c < 0x80) { buf[0] = (char)c; return 1; } if (c < 0x800) { if (buf_size < 2) return 0; buf[0] = (char)(0xc0 + (c >> 6)); buf[1] = (char)(0x80 + (c & 0x3f)); return 2; } if (c >= 0xdc00 && c < 0xe000) { return 0; } if (c >= 0xd800 && c < 0xdc00) { if (buf_size < 4) return 0; buf[0] = (char)(0xf0 + (c >> 18)); buf[1] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[2] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[3] = (char)(0x80 + ((c ) & 0x3f)); return 4; } //else if (c < 0x10000) { if (buf_size < 3) return 0; buf[0] = (char)(0xe0 + (c >> 12)); buf[1] = (char)(0x80 + ((c>> 6) & 0x3f)); buf[2] = (char)(0x80 + ((c ) & 0x3f)); return 3; } } // Not optimal but we very rarely use this function. int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end) { unsigned int dummy = 0; return ImTextCharFromUtf8(&dummy, in_text, in_text_end); } static inline int ImTextCountUtf8BytesFromChar(unsigned int c) { if (c < 0x80) return 1; if (c < 0x800) return 2; if (c >= 0xdc00 && c < 0xe000) return 0; if (c >= 0xd800 && c < 0xdc00) return 4; return 3; } int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end) { char* buf_out = buf; const char* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) *buf_out++ = (char)c; else buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c); } *buf_out = 0; return (int)(buf_out - buf); } int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) { int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c = (unsigned int)(*in_text++); if (c < 0x80) bytes_count++; else bytes_count += ImTextCountUtf8BytesFromChar(c); } return bytes_count; } //----------------------------------------------------------------------------- // [SECTION] MISC HELPERS/UTILTIES (Color functions) // Note: The Convert functions are early design which are not consistent with other API. //----------------------------------------------------------------------------- ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in) { float s = 1.0f/255.0f; return ImVec4( ((in >> IM_COL32_R_SHIFT) & 0xFF) * s, ((in >> IM_COL32_G_SHIFT) & 0xFF) * s, ((in >> IM_COL32_B_SHIFT) & 0xFF) * s, ((in >> IM_COL32_A_SHIFT) & 0xFF) * s); } ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) { ImU32 out; out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT; out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT; return out; } // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) { float K = 0.f; if (g < b) { ImSwap(g, b); K = -1.f; } if (r < g) { ImSwap(r, g); K = -2.f / 6.f - K; } const float chroma = r - (g < b ? g : b); out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f)); out_s = chroma / (r + 1e-20f); out_v = r; } // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 // also http://en.wikipedia.org/wiki/HSL_and_HSV void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) { if (s == 0.0f) { // gray out_r = out_g = out_b = v; return; } h = ImFmod(h, 1.0f) / (60.0f/360.0f); int i = (int)h; float f = h - (float)i; float p = v * (1.0f - s); float q = v * (1.0f - s * f); float t = v * (1.0f - s * (1.0f - f)); switch (i) { case 0: out_r = v; out_g = t; out_b = p; break; case 1: out_r = q; out_g = v; out_b = p; break; case 2: out_r = p; out_g = v; out_b = t; break; case 3: out_r = p; out_g = q; out_b = v; break; case 4: out_r = t; out_g = p; out_b = v; break; case 5: default: out_r = v; out_g = p; out_b = q; break; } } ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul) { ImGuiStyle& style = GImGui->Style; ImVec4 c = style.Colors[idx]; c.w *= style.Alpha * alpha_mul; return ColorConvertFloat4ToU32(c); } ImU32 ImGui::GetColorU32(const ImVec4& col) { ImGuiStyle& style = GImGui->Style; ImVec4 c = col; c.w *= style.Alpha; return ColorConvertFloat4ToU32(c); } const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx) { ImGuiStyle& style = GImGui->Style; return style.Colors[idx]; } ImU32 ImGui::GetColorU32(ImU32 col) { float style_alpha = GImGui->Style.Alpha; if (style_alpha >= 1.0f) return col; ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT; a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range. return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT); } //----------------------------------------------------------------------------- // [SECTION] ImGuiStorage // Helper: Key->value storage //----------------------------------------------------------------------------- // std::lower_bound but without the bullshit static ImGuiStorage::Pair* LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key) { ImGuiStorage::Pair* first = data.Data; ImGuiStorage::Pair* last = data.Data + data.Size; size_t count = (size_t)(last - first); while (count > 0) { size_t count2 = count >> 1; ImGuiStorage::Pair* mid = first + count2; if (mid->key < key) { first = ++mid; count -= count2 + 1; } else { count = count2; } } return first; } // For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once. void ImGuiStorage::BuildSortByKey() { struct StaticFunc { static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs) { // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that. if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1; if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1; return 0; } }; if (Data.Size > 1) ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID); } int ImGuiStorage::GetInt(ImGuiID key, int default_val) const { ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; } bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const { return GetInt(key, default_val ? 1 : 0) != 0; } float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const { ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; } void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; } // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_i; } bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val) { return (bool*)GetIntRef(key, default_val ? 1 : 0); } float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_p; } // FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame) void ImGuiStorage::SetInt(ImGuiID key, int val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_i = val; } void ImGuiStorage::SetBool(ImGuiID key, bool val) { SetInt(key, val ? 1 : 0); } void ImGuiStorage::SetFloat(ImGuiID key, float val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_f = val; } void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val) { ImGuiStorage::Pair* it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_p = val; } void ImGuiStorage::SetAllInt(int v) { for (int i = 0; i < Data.Size; i++) Data[i].val_i = v; } //----------------------------------------------------------------------------- // [SECTION] ImGuiTextFilter //----------------------------------------------------------------------------- // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) { if (default_filter) { ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf)); Build(); } else { InputBuf[0] = 0; CountGrep = 0; } } bool ImGuiTextFilter::Draw(const char* label, float width) { if (width != 0.0f) ImGui::SetNextItemWidth(width); bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); if (value_changed) Build(); return value_changed; } void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>* out) const { out->resize(0); const char* wb = b; const char* we = wb; while (we < e) { if (*we == separator) { out->push_back(TextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) out->push_back(TextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); input_range.split(',', &Filters); CountGrep = 0; for (int i = 0; i != Filters.Size; i++) { TextRange& f = Filters[i]; while (f.b < f.e && ImCharIsBlankA(f.b[0])) f.b++; while (f.e > f.b && ImCharIsBlankA(f.e[-1])) f.e--; if (f.empty()) continue; if (Filters[i].b[0] != '-') CountGrep += 1; } } bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const { if (Filters.empty()) return true; if (text == NULL) text = ""; for (int i = 0; i != Filters.Size; i++) { const TextRange& f = Filters[i]; if (f.empty()) continue; if (f.b[0] == '-') { // Subtract if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL) return false; } else { // Grep if (ImStristr(text, text_end, f.begin(), f.end()) != NULL) return true; } } // Implicit * grep if (CountGrep == 0) return true; return false; } //----------------------------------------------------------------------------- // [SECTION] ImGuiTextBuffer //----------------------------------------------------------------------------- // On some platform vsnprintf() takes va_list by reference and modifies it. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. #ifndef va_copy #if defined(__GNUC__) || defined(__clang__) #define va_copy(dest, src) __builtin_va_copy(dest, src) #else #define va_copy(dest, src) (dest = src) #endif #endif char ImGuiTextBuffer::EmptyString[1] = { 0 }; void ImGuiTextBuffer::append(const char* str, const char* str_end) { int len = str_end ? (int)(str_end - str) : (int)strlen(str); // Add zero-terminator the first time const int write_off = (Buf.Size != 0) ? Buf.Size : 1; const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { int new_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); } Buf.resize(needed_sz); memcpy(&Buf[write_off - 1], str, (size_t)len); Buf[write_off - 1 + len] = 0; } void ImGuiTextBuffer::appendf(const char* fmt, ...) { va_list args; va_start(args, fmt); appendfv(fmt, args); va_end(args); } // Helper: Text buffer for logging/accumulating text void ImGuiTextBuffer::appendfv(const char* fmt, va_list args) { va_list args_copy; va_copy(args_copy, args); int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. if (len <= 0) { va_end(args_copy); return; } // Add zero-terminator the first time const int write_off = (Buf.Size != 0) ? Buf.Size : 1; const int needed_sz = write_off + len; if (write_off + len >= Buf.Capacity) { int new_capacity = Buf.Capacity * 2; Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity); } Buf.resize(needed_sz); ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy); va_end(args_copy); } //----------------------------------------------------------------------------- // [SECTION] ImGuiListClipper // This is currently not as flexible/powerful as it should be, needs some rework (see TODO) //----------------------------------------------------------------------------- static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height) { // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. // The clipper should probably have a 4th step to display the last item in a regular manner. ImGui::SetCursorPosY(pos_y); ImGuiWindow* window = ImGui::GetCurrentWindow(); window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. if (window->DC.CurrentColumns) window->DC.CurrentColumns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly } // Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 // Use case B: Begin() called from constructor with items_height>0 // FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. void ImGuiListClipper::Begin(int count, float items_height) { StartPosY = ImGui::GetCursorPosY(); ItemsHeight = items_height; ItemsCount = count; StepNo = 0; DisplayEnd = DisplayStart = -1; if (ItemsHeight > 0.0f) { ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display if (DisplayStart > 0) SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor StepNo = 2; } } void ImGuiListClipper::End() { if (ItemsCount < 0) return; // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (ItemsCount < INT_MAX) SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor ItemsCount = -1; StepNo = 3; } bool ImGuiListClipper::Step() { if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems) { ItemsCount = -1; return false; } if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height. { DisplayStart = 0; DisplayEnd = 1; StartPosY = ImGui::GetCursorPosY(); StepNo = 1; return true; } if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element. { if (ItemsCount == 1) { ItemsCount = -1; return false; } float items_height = ImGui::GetCursorPosY() - StartPosY; IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically Begin(ItemsCount-1, items_height); DisplayStart++; DisplayEnd++; StepNo = 3; return true; } if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3. { IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0); StepNo = 3; return true; } if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop. End(); return false; } //----------------------------------------------------------------------------- // [SECTION] RENDER HELPERS // Those (internal) functions are currently quite a legacy mess - their signature and behavior will change. // Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state. //----------------------------------------------------------------------------- const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end) { const char* text_display_end = text; if (!text_end) text_end = (const char*)-1; while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) text_display_end++; return text_display_end; } // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { text_display_end = FindRenderedTextEnd(text, text_end); } else { if (!text_end) text_end = text + strlen(text); // FIXME-OPT text_display_end = text_end; } if (text != text_display_end) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end); if (g.LogEnabled) LogRenderedText(&pos, text, text_display_end); } } void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!text_end) text_end = text + strlen(text); // FIXME-OPT if (text != text_end) { window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width); if (g.LogEnabled) LogRenderedText(&pos, text, text_end); } } // Default clip_rect uses (pos_min,pos_max) // Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges) void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { // Perform CPU side clipping for single clipped element to avoid using scissor state ImVec2 pos = pos_min; const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f); const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min; const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max; bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y); if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y); // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment. if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x); if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y); // Render if (need_clipping) { ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y); draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect); } else { draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL); } } void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect) { // Hide anything after a '##' string const char* text_display_end = FindRenderedTextEnd(text, text_end); const int text_len = (int)(text_display_end - text); if (text_len == 0) return; ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect); if (g.LogEnabled) LogRenderedText(&pos_min, text, text_display_end); } // Render a rectangle shaped with optional rounding and borders void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); const float border_size = g.Style.FrameBorderSize; if (border && border_size > 0.0f) { window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const float border_size = g.Style.FrameBorderSize; if (border_size > 0.0f) { window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size); window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); } } // Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale) { ImGuiContext& g = *GImGui; const float h = g.FontSize * 1.00f; float r = h * 0.40f * scale; ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale); ImVec2 a, b, c; switch (dir) { case ImGuiDir_Up: case ImGuiDir_Down: if (dir == ImGuiDir_Up) r = -r; a = ImVec2(+0.000f,+0.750f) * r; b = ImVec2(-0.866f,-0.750f) * r; c = ImVec2(+0.866f,-0.750f) * r; break; case ImGuiDir_Left: case ImGuiDir_Right: if (dir == ImGuiDir_Left) r = -r; a = ImVec2(+0.750f,+0.000f) * r; b = ImVec2(-0.750f,+0.866f) * r; c = ImVec2(-0.750f,-0.866f) * r; break; case ImGuiDir_None: case ImGuiDir_COUNT: IM_ASSERT(0); break; } g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text)); } void ImGui::RenderBullet(ImVec2 pos) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8); } void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; float thickness = ImMax(sz / 5.0f, 1.0f); sz -= thickness*0.5f; pos += ImVec2(thickness*0.25f, thickness*0.25f); float third = sz / 3.0f; float bx = pos.x + third; float by = pos.y + sz - third*0.5f; window->DrawList->PathLineTo(ImVec2(bx - third, by - third)); window->DrawList->PathLineTo(ImVec2(bx, by)); window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2)); window->DrawList->PathStroke(col, false, thickness); } void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags) { ImGuiContext& g = *GImGui; if (id != g.NavId) return; if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw)) return; ImGuiWindow* window = g.CurrentWindow; if (window->DC.NavHideHighlightOneFrame) return; float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding; ImRect display_rect = bb; display_rect.ClipWith(window->ClipRect); if (flags & ImGuiNavHighlightFlags_TypeDefault) { const float THICKNESS = 2.0f; const float DISTANCE = 3.0f + THICKNESS * 0.5f; display_rect.Expand(ImVec2(DISTANCE,DISTANCE)); bool fully_visible = window->ClipRect.Contains(display_rect); if (!fully_visible) window->DrawList->PushClipRect(display_rect.Min, display_rect.Max); window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS); if (!fully_visible) window->DrawList->PopClipRect(); } if (flags & ImGuiNavHighlightFlags_TypeThin) { window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f); } } //----------------------------------------------------------------------------- // [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!) //----------------------------------------------------------------------------- // ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(&context->DrawListSharedData) { Name = ImStrdup(name); ID = ImHashStr(name); IDStack.push_back(ID); Flags = ImGuiWindowFlags_None; Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f); WindowPadding = ImVec2(0.0f, 0.0f); WindowRounding = 0.0f; WindowBorderSize = 0.0f; NameBufLen = (int)strlen(name) + 1; MoveId = GetID("#MOVE"); ChildId = 0; Scroll = ImVec2(0.0f, 0.0f); ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f); ScrollbarSizes = ImVec2(0.0f, 0.0f); ScrollbarX = ScrollbarY = false; Active = WasActive = false; WriteAccessed = false; Collapsed = false; WantCollapseToggle = false; SkipItems = false; Appearing = false; Hidden = false; HasCloseButton = false; ResizeBorderHeld = -1; BeginCount = 0; BeginOrderWithinParent = -1; BeginOrderWithinContext = -1; PopupId = 0; AutoFitFramesX = AutoFitFramesY = -1; AutoFitOnlyGrows = false; AutoFitChildAxises = 0x00; AutoPosLastDirection = ImGuiDir_None; HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing; SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX); LastFrameActive = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; SettingsIdx = -1; DrawList = &DrawListInst; DrawList->_OwnerName = Name; ParentWindow = NULL; RootWindow = NULL; RootWindowForTitleBarHighlight = NULL; RootWindowForNav = NULL; NavLastIds[0] = NavLastIds[1] = 0; NavRectRel[0] = NavRectRel[1] = ImRect(); NavLastChildNavWindow = NULL; } ImGuiWindow::~ImGuiWindow() { IM_ASSERT(DrawList == &DrawListInst); IM_DELETE(Name); for (int i = 0; i != ColumnsStorage.Size; i++) ColumnsStorage[i].~ImGuiColumns(); } ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); ImGuiID id = ImHashData(&ptr, sizeof(void*), seed); ImGui::KeepAliveID(id); return id; } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); return ImHashStr(str, str_end ? (str_end - str) : 0, seed); } ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr) { ImGuiID seed = IDStack.back(); return ImHashData(&ptr, sizeof(void*), seed); } // This is only used in rare/specific situations to manufacture an ID out of nowhere. ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs) { ImGuiID seed = IDStack.back(); const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) }; ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed); ImGui::KeepAliveID(id); return id; } static void SetCurrentWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.CurrentWindow = window; if (window) g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } void ImGui::SetNavID(ImGuiID id, int nav_layer) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindow); IM_ASSERT(nav_layer == 0 || nav_layer == 1); g.NavId = id; g.NavWindow->NavLastIds[nav_layer] = id; } void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel) { ImGuiContext& g = *GImGui; SetNavID(id, nav_layer); g.NavWindow->NavRectRel[nav_layer] = rect_rel; g.NavMousePosDirty = true; g.NavDisableHighlight = false; g.NavDisableMouseHover = true; } void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.ActiveIdIsJustActivated = (g.ActiveId != id); if (g.ActiveIdIsJustActivated) { g.ActiveIdTimer = 0.0f; g.ActiveIdHasBeenPressed = false; g.ActiveIdHasBeenEdited = false; if (id != 0) { g.LastActiveId = id; g.LastActiveIdTimer = 0.0f; } } g.ActiveId = id; g.ActiveIdAllowNavDirFlags = 0; g.ActiveIdBlockNavInputFlags = 0; g.ActiveIdAllowOverlap = false; g.ActiveIdWindow = window; if (id) { g.ActiveIdIsAlive = id; g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse; } } // FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring. void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window) { ImGuiContext& g = *GImGui; IM_ASSERT(id != 0); // Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it. const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent; if (g.NavWindow != window) g.NavInitRequest = false; g.NavId = id; g.NavWindow = window; g.NavLayer = nav_layer; window->NavLastIds[nav_layer] = id; if (window->DC.LastItemId == id) window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos); if (g.ActiveIdSource == ImGuiInputSource_Nav) g.NavDisableMouseHover = true; else g.NavDisableHighlight = true; } void ImGui::ClearActiveID() { SetActiveID(0, NULL); } void ImGui::SetHoveredID(ImGuiID id) { ImGuiContext& g = *GImGui; g.HoveredId = id; g.HoveredIdAllowOverlap = false; if (id != 0 && g.HoveredIdPreviousFrame != id) g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f; } ImGuiID ImGui::GetHoveredID() { ImGuiContext& g = *GImGui; return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame; } void ImGui::KeepAliveID(ImGuiID id) { ImGuiContext& g = *GImGui; if (g.ActiveId == id) g.ActiveIdIsAlive = id; if (g.ActiveIdPreviousFrame == id) g.ActiveIdPreviousFrameIsAlive = true; } void ImGui::MarkItemEdited(ImGuiID id) { // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit(). // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data. ImGuiContext& g = *GImGui; IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive); IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out. //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id); g.ActiveIdHasBeenEdited = true; g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited; } static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags) { // An active popup disable hovering on other windows (apart from its own children) // FIXME-OPT: This could be cached/stored within the window. ImGuiContext& g = *GImGui; if (g.NavWindow) if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow) if (focused_root_window->WasActive && focused_root_window != window->RootWindow) { // For the purpose of those flags we differentiate "standard popup" from "modal popup" // NB: The order of those two tests is important because Modal windows are also Popups. if (focused_root_window->Flags & ImGuiWindowFlags_Modal) return false; if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup)) return false; } return true; } // Advance cursor given item size for layout. void ImGui::ItemSize(const ImVec2& size, float text_offset_y) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return; // Always align ourselves on pixel boundaries const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y); const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG] window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y); //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG] window->DC.PrevLineSize.y = line_height; window->DC.PrevLineTextBaseOffset = text_base_offset; window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f; // Horizontal layout mode if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) SameLine(); } void ImGui::ItemSize(const ImRect& bb, float text_offset_y) { ItemSize(bb.GetSize(), text_offset_y); } // Declare item bounding box for clipping and interaction. // Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface // declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd(). bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (id != 0) { // Navigation processing runs prior to clipping early-out // (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget // (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window. // it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame. // We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick) window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask; if (g.NavId == id || g.NavAnyRequest) if (g.NavWindow->RootWindowForNav == window->RootWindowForNav) if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened)) NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id); } window->DC.LastItemId = id; window->DC.LastItemRect = bb; window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None; #ifdef IMGUI_ENABLE_TEST_ENGINE if (id != 0) IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id); #endif // Clipping test const bool is_clipped = IsClippedEx(bb, id, false); if (is_clipped) return false; //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG] // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them) if (IsMouseHoveringRect(bb.Min, bb.Max)) window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect; return true; } // This is roughly matching the behavior of internal-facing ItemHoverable() // - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered() // - this should work even for non-interactive items that have no ID, so we cannot use LastItemId bool ImGui::IsItemHovered(ImGuiHoveredFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavDisableMouseHover && !g.NavDisableHighlight) return IsItemFocused(); // Test for bounding box overlap, as updated as ItemAdd() if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function // Test if we are hovering the right window (our window could be behind another window) // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself. // Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while. //if (g.HoveredWindow != window) // return false; if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped)) return false; // Test if another item is active (e.g. being dragged) if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId) return false; // Test if interactions on this window are blocked by an active popup or modal. // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here. if (!IsWindowContentHoverable(window, flags)) return false; // Test if the item is disabled if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled)) return false; // Special handling for the dummy item after Begin() which represent the title bar or tab. // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case. if (window->DC.LastItemId == window->MoveId && window->WriteAccessed) return false; return true; } // Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered(). bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id) { ImGuiContext& g = *GImGui; if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap) return false; ImGuiWindow* window = g.CurrentWindow; if (g.HoveredWindow != window) return false; if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap) return false; if (!IsMouseHoveringRect(bb.Min, bb.Max)) return false; if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None)) return false; if (window->DC.ItemFlags & ImGuiItemFlags_Disabled) return false; SetHoveredID(id); return true; } bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!bb.Overlaps(window->ClipRect)) if (id == 0 || id != g.ActiveId) if (clip_even_when_logged || !g.LogEnabled) return true; return false; } // Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out. bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id) { ImGuiContext& g = *GImGui; // Increment counters const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0; window->DC.FocusCounterAll++; if (is_tab_stop) window->DC.FocusCounterTab++; // Process TAB/Shift-TAB to tab *OUT* of the currently focused item. // (Note that we can always TAB out of a widget that doesn't allow tabbing in) if (g.ActiveId == id && g.FocusTabPressed && !(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_KeyTab_)) && g.FocusRequestNextWindow == NULL) { g.FocusRequestNextWindow = window; g.FocusRequestNextCounterTab = window->DC.FocusCounterTab + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items. } // Handle focus requests if (g.FocusRequestCurrWindow == window) { if (window->DC.FocusCounterAll == g.FocusRequestCurrCounterAll) return true; if (is_tab_stop && window->DC.FocusCounterTab == g.FocusRequestCurrCounterTab) { g.NavJustTabbedId = id; return true; } // If another item is about to be focused, we clear our own active id if (g.ActiveId == id) ClearActiveID(); } return false; } void ImGui::FocusableItemUnregister(ImGuiWindow* window) { window->DC.FocusCounterAll--; window->DC.FocusCounterTab--; } float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) return 0.0f; ImGuiWindow* window = GImGui->CurrentWindow; if (wrap_pos_x == 0.0f) wrap_pos_x = GetWorkRectMax().x; else if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space return ImMax(wrap_pos_x - pos.x, 1.0f); } // IM_ALLOC() == ImGui::MemAlloc() void* ImGui::MemAlloc(size_t size) { if (ImGuiContext* ctx = GImGui) ctx->IO.MetricsActiveAllocations++; return GImAllocatorAllocFunc(size, GImAllocatorUserData); } // IM_FREE() == ImGui::MemFree() void ImGui::MemFree(void* ptr) { if (ptr) if (ImGuiContext* ctx = GImGui) ctx->IO.MetricsActiveAllocations--; return GImAllocatorFreeFunc(ptr, GImAllocatorUserData); } const char* ImGui::GetClipboardText() { return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : ""; } void ImGui::SetClipboardText(const char* text) { if (GImGui->IO.SetClipboardTextFn) GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text); } const char* ImGui::GetVersion() { return IMGUI_VERSION; } // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module ImGuiContext* ImGui::GetCurrentContext() { return GImGui; } void ImGui::SetCurrentContext(ImGuiContext* ctx) { #ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this. #else GImGui = ctx; #endif } // Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui. // Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit // If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code // may see different structures thanwhat imgui.cpp sees, which is problematic. // We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui. bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx) { bool error = false; if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); } if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); } if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); } if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); } if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); } if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); } if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); } return !error; } void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data) { GImAllocatorAllocFunc = alloc_func; GImAllocatorFreeFunc = free_func; GImAllocatorUserData = user_data; } ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas) { ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas); if (GImGui == NULL) SetCurrentContext(ctx); Initialize(ctx); return ctx; } void ImGui::DestroyContext(ImGuiContext* ctx) { if (ctx == NULL) ctx = GImGui; Shutdown(ctx); if (GImGui == ctx) SetCurrentContext(NULL); IM_DELETE(ctx); } ImGuiIO& ImGui::GetIO() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); return GImGui->IO; } ImGuiStyle& ImGui::GetStyle() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); return GImGui->Style; } // Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame() ImDrawData* ImGui::GetDrawData() { ImGuiContext& g = *GImGui; return g.DrawData.Valid ? &g.DrawData : NULL; } double ImGui::GetTime() { return GImGui->Time; } int ImGui::GetFrameCount() { return GImGui->FrameCount; } ImDrawList* ImGui::GetBackgroundDrawList() { return &GImGui->BackgroundDrawList; } static ImDrawList* GetForegroundDrawList(ImGuiWindow*) { // This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches. return &GImGui->ForegroundDrawList; } ImDrawList* ImGui::GetForegroundDrawList() { return &GImGui->ForegroundDrawList; } ImDrawListSharedData* ImGui::GetDrawListSharedData() { return &GImGui->DrawListSharedData; } void ImGui::StartMouseMovingWindow(ImGuiWindow* window) { // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows. // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward. // This is because we want ActiveId to be set even when the window is not permitted to move. ImGuiContext& g = *GImGui; FocusWindow(window); SetActiveID(window->MoveId, window); g.NavDisableHighlight = true; g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos; bool can_move_window = true; if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove)) can_move_window = false; if (can_move_window) g.MovingWindow = window; } // Handle mouse moving window // Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing() void ImGui::UpdateMouseMovingWindowNewFrame() { ImGuiContext& g = *GImGui; if (g.MovingWindow != NULL) { // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window). // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency. KeepAliveID(g.ActiveId); IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow); ImGuiWindow* moving_window = g.MovingWindow->RootWindow; if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos)) { ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset; if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y) { MarkIniSettingsDirty(moving_window); SetWindowPos(moving_window, pos, ImGuiCond_Always); } FocusWindow(g.MovingWindow); } else { ClearActiveID(); g.MovingWindow = NULL; } } else { // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others. if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId) { KeepAliveID(g.ActiveId); if (!g.IO.MouseDown[0]) ClearActiveID(); } } } // Initiate moving window, handle left-click and right-click focus void ImGui::UpdateMouseMovingWindowEndFrame() { // Initiate moving window ImGuiContext& g = *GImGui; if (g.ActiveId != 0 || g.HoveredId != 0) return; // Unless we just made a window/popup appear if (g.NavWindow && g.NavWindow->Appearing) return; // Click to focus window and start moving (after we're done with all our widgets) if (g.IO.MouseClicked[0]) { if (g.HoveredRootWindow != NULL) { StartMouseMovingWindow(g.HoveredWindow); if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar)) if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0])) g.MovingWindow = NULL; } else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL) { // Clicking on void disable focus FocusWindow(NULL); } } // With right mouse button we close popups without changing focus based on where the mouse is aimed // Instead, focus will be restored to the window under the bottom-most closed popup. // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger) if (g.IO.MouseClicked[1]) { // Find the top-most window between HoveredWindow and the front most Modal Window. // This is where we can trim the popup stack. ImGuiWindow* modal = GetFrontMostPopupModal(); bool hovered_window_above_modal = false; if (modal == NULL) hovered_window_above_modal = true; for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--) { ImGuiWindow* window = g.Windows[i]; if (window == modal) break; if (window == g.HoveredWindow) hovered_window_above_modal = true; } ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true); } } static bool IsWindowActiveAndVisible(ImGuiWindow* window) { return (window->Active) && (!window->Hidden); } static void ImGui::UpdateMouseInputs() { ImGuiContext& g = *GImGui; // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well) if (IsMousePosValid(&g.IO.MousePos)) g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos); // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev)) g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; else g.IO.MouseDelta = ImVec2(0.0f, 0.0f); if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f) g.NavDisableMouseHover = false; g.IO.MousePosPrev = g.IO.MousePos; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f; g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f; g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i]; g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f; g.IO.MouseDoubleClicked[i] = false; if (g.IO.MouseClicked[i]) { if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime) { ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click } else { g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i]; g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f); g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; } else if (g.IO.MouseDown[i]) { // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f); g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos)); g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x); g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y); } if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i]) g.IO.MouseDownWasDoubleClick[i] = false; if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation g.NavDisableMouseHover = false; } } void ImGui::UpdateMouseWheel() { ImGuiContext& g = *GImGui; if (!g.HoveredWindow || g.HoveredWindow->Collapsed) return; if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f) return; ImGuiWindow* window = g.HoveredWindow; // Zoom / Scale window // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned. if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling) { const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); const float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) { const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; window->Pos = ImFloor(window->Pos + offset); window->Size = ImFloor(window->Size * scale); window->SizeFull = ImFloor(window->SizeFull * scale); } return; } // Mouse wheel scrolling // If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set). while ((window->Flags & ImGuiWindowFlags_ChildWindow) && (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs) && window->ParentWindow) window = window->ParentWindow; const bool scroll_allowed = !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs); if (scroll_allowed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f) && !g.IO.KeyCtrl) { ImVec2 max_step = (window->ContentsRegionRect.GetSize() + window->WindowPadding * 2.0f) * 0.67f; // Vertical Mouse Wheel Scrolling (hold Shift to scroll horizontally) if (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift) { float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step.y)); SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * scroll_step); } else if (g.IO.MouseWheel != 0.0f && g.IO.KeyShift) { float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x)); SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheel * scroll_step); } // Horizontal Mouse Wheel Scrolling (for hardware that supports it) if (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift) { float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x)); SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_step); } } } // The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app) void ImGui::UpdateHoveredWindowAndCaptureFlags() { ImGuiContext& g = *GImGui; // Find the window hovered by mouse: // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow. // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame. // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms. FindHoveredWindow(); // Modal windows prevents cursor from hovering behind them. ImGuiWindow* modal_window = GetFrontMostPopupModal(); if (modal_window) if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window)) g.HoveredRootWindow = g.HoveredWindow = NULL; // Disabled mouse? if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse) g.HoveredWindow = g.HoveredRootWindow = NULL; // We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward. int mouse_earliest_button_down = -1; bool mouse_any_down = false; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty()); mouse_any_down |= g.IO.MouseDown[i]; if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down]) mouse_earliest_button_down = i; } const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down]; // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02) const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0; if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload) g.HoveredWindow = g.HoveredRootWindow = NULL; // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app) if (g.WantCaptureMouseNextFrame != -1) g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0); else g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty()); // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app) if (g.WantCaptureKeyboardNextFrame != -1) g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0); else g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL); if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard)) g.IO.WantCaptureKeyboard = true; // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false; } void ImGui::NewFrame() { IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?"); ImGuiContext& g = *GImGui; #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiTestEngineHook_PreNewFrame(&g); #endif // Check user data // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument) IM_ASSERT(g.Initialized); IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!"); IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?"); IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!"); IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?"); IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!"); IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!"); IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting."); for (int n = 0; n < ImGuiKey_COUNT; n++) IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)"); // Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP) if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation."); // Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly. if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors)) g.IO.ConfigWindowsResizeFromEdges = false; // Load settings on first frame (if not explicitly loaded manually before) if (!g.SettingsLoaded) { IM_ASSERT(g.SettingsWindows.empty()); if (g.IO.IniFilename) LoadIniSettingsFromDisk(g.IO.IniFilename); g.SettingsLoaded = true; } // Save settings (with a delay after the last modification, so we don't spam disk too much) if (g.SettingsDirtyTimer > 0.0f) { g.SettingsDirtyTimer -= g.IO.DeltaTime; if (g.SettingsDirtyTimer <= 0.0f) { if (g.IO.IniFilename != NULL) SaveIniSettingsToDisk(g.IO.IniFilename); else g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves. g.SettingsDirtyTimer = 0.0f; } } g.Time += g.IO.DeltaTime; g.FrameScopeActive = true; g.FrameCount += 1; g.TooltipOverrideCount = 0; g.WindowsActiveCount = 0; // Setup current font and draw list shared data g.IO.Fonts->Locked = true; SetCurrentFont(GetDefaultFont()); IM_ASSERT(g.Font->IsLoaded()); g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol; g.BackgroundDrawList.Clear(); g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.BackgroundDrawList.PushClipRectFullScreen(); g.BackgroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); g.ForegroundDrawList.Clear(); g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID); g.ForegroundDrawList.PushClipRectFullScreen(); g.ForegroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); // Mark rendering data as invalid to prevent user who may have a handle on it to use it. g.DrawData.Clear(); // Drag and drop keep the source ID alive so even if the source disappear our state is consistent if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId) KeepAliveID(g.DragDropPayload.SourceId); // Clear reference to active widget if the widget isn't alive anymore if (!g.HoveredIdPreviousFrame) g.HoveredIdTimer = 0.0f; if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId)) g.HoveredIdNotActiveTimer = 0.0f; if (g.HoveredId) g.HoveredIdTimer += g.IO.DeltaTime; if (g.HoveredId && g.ActiveId != g.HoveredId) g.HoveredIdNotActiveTimer += g.IO.DeltaTime; g.HoveredIdPreviousFrame = g.HoveredId; g.HoveredId = 0; g.HoveredIdAllowOverlap = false; if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) ClearActiveID(); if (g.ActiveId) g.ActiveIdTimer += g.IO.DeltaTime; g.LastActiveIdTimer += g.IO.DeltaTime; g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow; g.ActiveIdPreviousFrameHasBeenEdited = g.ActiveIdHasBeenEdited; g.ActiveIdIsAlive = 0; g.ActiveIdPreviousFrameIsAlive = false; g.ActiveIdIsJustActivated = false; if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId) g.TempInputTextId = 0; // Drag and drop g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr; g.DragDropAcceptIdCurr = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropWithinSourceOrTarget = false; // Update keyboard input state memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Update gamepad/keyboard directional navigation NavUpdate(); // Update mouse input state UpdateMouseInputs(); // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX; // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering) UpdateMouseMovingWindowNewFrame(); UpdateHoveredWindowAndCaptureFlags(); // Background darkening/whitening if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f)) g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f); else g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f); g.MouseCursor = ImGuiMouseCursor_Arrow; g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1; g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default // Mouse wheel scrolling, scale UpdateMouseWheel(); // Pressing TAB activate widget focus g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab)); if (g.ActiveId == 0 && g.FocusTabPressed) { // Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also // manipulate the Next fields even, even though they will be turned into Curr fields by the code below. g.FocusRequestNextWindow = g.NavWindow; g.FocusRequestNextCounterAll = INT_MAX; if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX) g.FocusRequestNextCounterTab = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1); else g.FocusRequestNextCounterTab = g.IO.KeyShift ? -1 : 0; } // Turn queued focus request into current one g.FocusRequestCurrWindow = NULL; g.FocusRequestCurrCounterAll = g.FocusRequestCurrCounterTab = INT_MAX; if (g.FocusRequestNextWindow != NULL) { ImGuiWindow* window = g.FocusRequestNextWindow; g.FocusRequestCurrWindow = window; if (g.FocusRequestNextCounterAll != INT_MAX && window->DC.FocusCounterAll != -1) g.FocusRequestCurrCounterAll = ImModPositive(g.FocusRequestNextCounterAll, window->DC.FocusCounterAll + 1); if (g.FocusRequestNextCounterTab != INT_MAX && window->DC.FocusCounterTab != -1) g.FocusRequestCurrCounterTab = ImModPositive(g.FocusRequestNextCounterTab, window->DC.FocusCounterTab + 1); g.FocusRequestNextWindow = NULL; g.FocusRequestNextCounterAll = g.FocusRequestNextCounterTab = INT_MAX; } g.NavIdTabCounter = INT_MAX; // Mark all windows as not visible IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; window->WasActive = window->Active; window->BeginCount = 0; window->Active = false; window->WriteAccessed = false; } // Closing the focused window restore focus to the first active root window in descending z-order if (g.NavWindow && !g.NavWindow->WasActive) FocusTopMostWindowUnderOne(NULL, NULL); // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); g.BeginPopupStack.resize(0); ClosePopupsOverWindow(g.NavWindow, false); // Create implicit/fallback window - which we will only render it if the user has added something to it. // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags. // This fallback is particularly important as it avoid ImGui:: calls from crashing. SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver); Begin("Debug##Default"); g.FrameScopePushedImplicitWindow = true; #ifdef IMGUI_ENABLE_TEST_ENGINE ImGuiTestEngineHook_PostNewFrame(&g); #endif } void ImGui::Initialize(ImGuiContext* context) { ImGuiContext& g = *context; IM_ASSERT(!g.Initialized && !g.SettingsLoaded); // Add .ini handle for ImGuiWindow type ImGuiSettingsHandler ini_handler; ini_handler.TypeName = "Window"; ini_handler.TypeHash = ImHashStr("Window"); ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen; ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine; ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll; g.SettingsHandlers.push_back(ini_handler); g.Initialized = true; } // This function is merely here to free heap allocations. void ImGui::Shutdown(ImGuiContext* context) { // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame) ImGuiContext& g = *context; if (g.IO.Fonts && g.FontAtlasOwnedByContext) { g.IO.Fonts->Locked = false; IM_DELETE(g.IO.Fonts); } g.IO.Fonts = NULL; // Cleanup of other data are conditional on actually having initialized ImGui. if (!g.Initialized) return; // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file) if (g.SettingsLoaded && g.IO.IniFilename != NULL) { ImGuiContext* backup_context = GImGui; SetCurrentContext(context); SaveIniSettingsToDisk(g.IO.IniFilename); SetCurrentContext(backup_context); } // Clear everything else for (int i = 0; i < g.Windows.Size; i++) IM_DELETE(g.Windows[i]); g.Windows.clear(); g.WindowsFocusOrder.clear(); g.WindowsSortBuffer.clear(); g.CurrentWindow = NULL; g.CurrentWindowStack.clear(); g.WindowsById.Clear(); g.NavWindow = NULL; g.HoveredWindow = g.HoveredRootWindow = NULL; g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL; g.MovingWindow = NULL; g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); g.OpenPopupStack.clear(); g.BeginPopupStack.clear(); g.DrawDataBuilder.ClearFreeMemory(); g.BackgroundDrawList.ClearFreeMemory(); g.ForegroundDrawList.ClearFreeMemory(); g.PrivateClipboard.clear(); g.InputTextState.ClearFreeMemory(); for (int i = 0; i < g.SettingsWindows.Size; i++) IM_DELETE(g.SettingsWindows[i].Name); g.SettingsWindows.clear(); g.SettingsHandlers.clear(); if (g.LogFile && g.LogFile != stdout) { fclose(g.LogFile); g.LogFile = NULL; } g.LogBuffer.clear(); g.Initialized = false; } // FIXME: Add a more explicit sort order in the window structure. static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs) { const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs; const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs; if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) return d; if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; return (a->BeginOrderWithinParent - b->BeginOrderWithinParent); } static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window) { out_sorted_windows->push_back(window); if (window->Active) { int count = window->DC.ChildWindows.Size; if (count > 1) ImQsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer); for (int i = 0; i < count; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Active) AddWindowToSortBuffer(out_sorted_windows, child); } } } static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list) { if (draw_list->CmdBuffer.empty()) return; // Remove trailing command if unused ImDrawCmd& last_cmd = draw_list->CmdBuffer.back(); if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL) { draw_list->CmdBuffer.pop_back(); if (draw_list->CmdBuffer.empty()) return; } // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly. IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size); IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size); IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size); // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window) // If this assert triggers because you are drawing lots of stuff manually: // A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents. // B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes. // You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing: // glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset); // Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API. // C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists. if (sizeof(ImDrawIdx) == 2) IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above"); out_list->push_back(draw_list); } static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window) { ImGuiContext& g = *GImGui; g.IO.MetricsRenderWindows++; AddDrawListToDrawData(out_render_list, window->DrawList); for (int i = 0; i < window->DC.ChildWindows.Size; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active AddWindowToDrawData(out_render_list, child); } } // Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu) static void AddRootWindowToDrawData(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (window->Flags & ImGuiWindowFlags_Tooltip) AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window); else AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window); } void ImDrawDataBuilder::FlattenIntoSingleLayer() { int n = Layers[0].Size; int size = n; for (int i = 1; i < IM_ARRAYSIZE(Layers); i++) size += Layers[i].Size; Layers[0].resize(size); for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++) { ImVector<ImDrawList*>& layer = Layers[layer_n]; if (layer.empty()) continue; memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*)); n += layer.Size; layer.resize(0); } } static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data) { ImGuiIO& io = ImGui::GetIO(); draw_data->Valid = true; draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL; draw_data->CmdListsCount = draw_lists->Size; draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0; draw_data->DisplayPos = ImVec2(0.0f, 0.0f); draw_data->DisplaySize = io.DisplaySize; draw_data->FramebufferScale = io.DisplayFramebufferScale; for (int n = 0; n < draw_lists->Size; n++) { draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size; draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size; } } // When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result. void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect); window->ClipRect = window->DrawList->_ClipRectStack.back(); } void ImGui::PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->PopClipRect(); window->ClipRect = window->DrawList->_ClipRectStack.back(); } // This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal. void ImGui::EndFrame() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times. return; IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()?"); // Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME) if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f)) { g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y); g.PlatformImeLastPos = g.PlatformImePos; } // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API). if (g.CurrentWindowStack.Size != 1) { if (g.CurrentWindowStack.Size > 1) { IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?"); while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING End(); } else { IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?"); } } // Hide implicit/fallback "Debug" window if it hasn't been used g.FrameScopePushedImplicitWindow = false; if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed) g.CurrentWindow->Active = false; End(); // Show CTRL+TAB list window if (g.NavWindowingTarget) NavUpdateWindowingList(); // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted) if (g.DragDropActive) { bool is_delivered = g.DragDropPayload.Delivery; bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton)); if (is_delivered || is_elapsed) ClearDragDrop(); } // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing. if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount) { g.DragDropWithinSourceOrTarget = true; SetTooltip("..."); g.DragDropWithinSourceOrTarget = false; } // End frame g.FrameScopeActive = false; g.FrameCountEnded = g.FrameCount; // Initiate moving window + handle left-click and right-click focus UpdateMouseMovingWindowEndFrame(); // Sort the window list so that all child windows are after their parent // We cannot do that on FocusWindow() because childs may not exist yet g.WindowsSortBuffer.resize(0); g.WindowsSortBuffer.reserve(g.Windows.Size); for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it continue; AddWindowToSortBuffer(&g.WindowsSortBuffer, window); } // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong. IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); g.Windows.swap(g.WindowsSortBuffer); g.IO.MetricsActiveWindows = g.WindowsActiveCount; // Unlock font atlas g.IO.Fonts->Locked = false; // Clear Input data for next frame g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f; g.IO.InputQueueCharacters.resize(0); memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs)); } void ImGui::Render() { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); if (g.FrameCountEnded != g.FrameCount) EndFrame(); g.FrameCountRendered = g.FrameCount; // Gather ImDrawList to render (for each active window) g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0; g.DrawDataBuilder.Clear(); if (!g.BackgroundDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList); ImGuiWindow* windows_to_render_front_most[2]; windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL; windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL; for (int n = 0; n != g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1]) AddRootWindowToDrawData(window); } for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++) if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window AddRootWindowToDrawData(windows_to_render_front_most[n]); g.DrawDataBuilder.FlattenIntoSingleLayer(); // Draw software mouse cursor if requested if (g.IO.MouseDrawCursor) RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor); if (!g.ForegroundDrawList.VtxBuffer.empty()) AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList); // Setup ImDrawData structure for end-user SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData); g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount; g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount; // (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL) g.IO.RenderDrawListsFn(&g.DrawData); #endif } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { ImGuiContext& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; if (text == text_display_end) return ImVec2(0.0f, font_size); ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Round text_size.x = (float)(int)(text_size.x + 0.95f); return text_size; } // Helper to calculate coarse clipping of large list of evenly sized items. // NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern. // NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.LogEnabled) { // If logging is active, do not perform any clipping *out_items_display_start = 0; *out_items_display_end = items_count; return; } if (window->SkipItems) { *out_items_display_start = *out_items_display_end = 0; return; } // We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect ImRect unclipped_rect = window->ClipRect; if (g.NavMoveRequest) unclipped_rect.Add(g.NavScoringRectScreen); const ImVec2 pos = window->DC.CursorPos; int start = (int)((unclipped_rect.Min.y - pos.y) / items_height); int end = (int)((unclipped_rect.Max.y - pos.y) / items_height); // When performing a navigation request, ensure we have one item extra in the direction we are moving to if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up) start--; if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down) end++; start = ImClamp(start, 0, items_count); end = ImClamp(end + 1, start, items_count); *out_items_display_start = start; *out_items_display_end = end; } // Find window given position, search front-to-back // FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically // with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is // called, aka before the next Begin(). Moving window isn't affected. static void FindHoveredWindow() { ImGuiContext& g = *GImGui; ImGuiWindow* hovered_window = NULL; if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs)) hovered_window = g.MovingWindow; ImVec2 padding_regular = g.Style.TouchExtraPadding; ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular; for (int i = g.Windows.Size - 1; i >= 0; i--) { ImGuiWindow* window = g.Windows[i]; if (!window->Active || window->Hidden) continue; if (window->Flags & ImGuiWindowFlags_NoMouseInputs) continue; // Using the clipped AABB, a child window will typically be clipped by its parent (not always) ImRect bb(window->OuterRectClipped); if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) bb.Expand(padding_regular); else bb.Expand(padding_for_resize_from_edges); if (!bb.Contains(g.IO.MousePos)) continue; // Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches. if (hovered_window == NULL) hovered_window = window; if (hovered_window) break; } g.HoveredWindow = hovered_window; g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL; } // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip) { ImGuiContext& g = *GImGui; // Clip ImRect rect_clipped(r_min, r_max); if (clip) rect_clipped.ClipWith(g.CurrentWindow->ClipRect); // Expand for touch input const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); if (!rect_for_touch.Contains(g.IO.MousePos)) return false; return true; } int ImGui::GetKeyIndex(ImGuiKey imgui_key) { IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT); return GImGui->IO.KeyMap[imgui_key]; } // Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]! bool ImGui::IsKeyDown(int user_key_index) { if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown)); return GImGui->IO.KeysDown[user_key_index]; } int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate) { if (t == 0.0f) return 1; if (t <= repeat_delay || repeat_rate <= 0.0f) return 0; const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate); return (count > 0) ? count : 0; } int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate) { ImGuiContext& g = *GImGui; if (key_index < 0) return 0; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[key_index]; return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate); } bool ImGui::IsKeyPressed(int user_key_index, bool repeat) { ImGuiContext& g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownDuration[user_key_index]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0; return false; } bool ImGui::IsKeyReleased(int user_key_index) { ImGuiContext& g = *GImGui; if (user_key_index < 0) return false; IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown)); return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index]; } bool ImGui::IsMouseDown(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDown[button]; } bool ImGui::IsAnyMouseDown() { ImGuiContext& g = *GImGui; for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++) if (g.IO.MouseDown[n]) return true; return false; } bool ImGui::IsMouseClicked(int button, bool repeat) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownDuration[button]; if (t == 0.0f) return true; if (repeat && t > g.IO.KeyRepeatDelay) { // FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold. int amount = CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.5f); if (amount > 0) return true; } return false; } bool ImGui::IsMouseReleased(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseReleased[button]; } bool ImGui::IsMouseDoubleClicked(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } bool ImGui::IsMouseDragging(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (!g.IO.MouseDown[button]) return false; if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; } ImVec2 ImGui::GetMousePos() { return GImGui->IO.MousePos; } // NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed! ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup() { ImGuiContext& g = *GImGui; if (g.BeginPopupStack.Size > 0) return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos; return g.IO.MousePos; } // We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position. bool ImGui::IsMousePosValid(const ImVec2* mouse_pos) { // The assert is only to silence a false-positive in XCode Static Analysis. // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions). IM_ASSERT(GImGui != NULL); const float MOUSE_INVALID = -256000.0f; ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos; return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID; } // Return the delta from the initial clicking position while the mouse button is clicked or was just released. // This is locked and return 0.0f until the mouse moves past a distance threshold at least once. // NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window. ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; if (g.IO.MouseDown[button] || g.IO.MouseReleased[button]) if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button])) return g.IO.MousePos - g.IO.MouseClickedPos[button]; return ImVec2(0.0f, 0.0f); } void ImGui::ResetMouseDragDelta(int button) { ImGuiContext& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; } ImGuiMouseCursor ImGui::GetMouseCursor() { return GImGui->MouseCursor; } void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) { GImGui->MouseCursor = cursor_type; } void ImGui::CaptureKeyboardFromApp(bool capture) { GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0; } void ImGui::CaptureMouseFromApp(bool capture) { GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0; } bool ImGui::IsItemActive() { ImGuiContext& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = g.CurrentWindow; return g.ActiveId == window->DC.LastItemId; } return false; } bool ImGui::IsItemActivated() { ImGuiContext& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = g.CurrentWindow; if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId) return true; } return false; } bool ImGui::IsItemDeactivated() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId); } bool ImGui::IsItemDeactivatedAfterEdit() { ImGuiContext& g = *GImGui; return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEdited || (g.ActiveId == 0 && g.ActiveIdHasBeenEdited)); } bool ImGui::IsItemFocused() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId) return false; return true; } bool ImGui::IsItemClicked(int mouse_button) { return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None); } bool ImGui::IsItemToggledSelection() { ImGuiContext& g = *GImGui; return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false; } bool ImGui::IsAnyItemHovered() { ImGuiContext& g = *GImGui; return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0; } bool ImGui::IsAnyItemActive() { ImGuiContext& g = *GImGui; return g.ActiveId != 0; } bool ImGui::IsAnyItemFocused() { ImGuiContext& g = *GImGui; return g.NavId != 0 && !g.NavDisableHighlight; } bool ImGui::IsItemVisible() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ClipRect.Overlaps(window->DC.LastItemRect); } bool ImGui::IsItemEdited() { ImGuiWindow* window = GetCurrentWindowRead(); return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0; } // Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority. void ImGui::SetItemAllowOverlap() { ImGuiContext& g = *GImGui; if (g.HoveredId == g.CurrentWindow->DC.LastItemId) g.HoveredIdAllowOverlap = true; if (g.ActiveId == g.CurrentWindow->DC.LastItemId) g.ActiveIdAllowOverlap = true; } ImVec2 ImGui::GetItemRectMin() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.LastItemRect.GetSize(); } static ImRect GetViewportRect() { ImGuiContext& g = *GImGui; return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y); } static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag // Size const ImVec2 content_avail = GetContentRegionAvail(); ImVec2 size = ImFloor(size_arg); const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00); if (size.x <= 0.0f) size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues) if (size.y <= 0.0f) size.y = ImMax(content_avail.y + size.y, 4.0f); SetNextWindowSize(size); // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value. char title[256]; if (name) ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id); else ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id); const float backup_border_size = g.Style.ChildBorderSize; if (!border) g.Style.ChildBorderSize = 0.0f; bool ret = Begin(title, NULL, flags); g.Style.ChildBorderSize = backup_border_size; ImGuiWindow* child_window = g.CurrentWindow; child_window->ChildId = id; child_window->AutoFitChildAxises = auto_fit_axises; // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually. // While this is not really documented/defined, it seems that the expected thing to do. if (child_window->BeginCount == 1) parent_window->DC.CursorPos = child_window->Pos; // Process navigation-in immediately so NavInit can run on first frame if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll)) { FocusWindow(child_window); NavInitWindow(child_window, false); SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item g.ActiveIdSource = ImGuiInputSource_Nav; } return ret; } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiWindow* window = GetCurrentWindow(); return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags); } bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { IM_ASSERT(id != 0); return BeginChildEx(NULL, id, size_arg, border, extra_flags); } void ImGui::EndChild() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss if (window->BeginCount > 1) { End(); } else { ImVec2 sz = window->Size; if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f sz.x = ImMax(4.0f, sz.x); if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y)) sz.y = ImMax(4.0f, sz.y); End(); ImGuiWindow* parent_window = g.CurrentWindow; ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz); ItemSize(sz); if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened)) { ItemAdd(bb, window->ChildId); RenderNavHighlight(bb, window->ChildId); // When browsing a window that has no activable items (scroll only) we keep a highlight on the child if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow) RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin); } else { // Not navigable into ItemAdd(bb, 0); } } } // Helper to create a child window / scrolling region that looks like a normal widget frame. bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]); PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding); PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize); PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags); PopStyleVar(3); PopStyleColor(); return ret; } void ImGui::EndChildFrame() { EndChild(); } // Save and compare stack sizes on Begin()/End() to detect usage errors static void CheckStacksSize(ImGuiWindow* window, bool write) { // NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin) ImGuiContext& g = *GImGui; short* p_backup = &window->DC.StackSizesBackup[0]; { int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop() { int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup() { int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup() // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them. { int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor() { int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar() { int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont() IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup)); } static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled) { window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags); window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags); window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags); } ImGuiWindow* ImGui::FindWindowByID(ImGuiID id) { ImGuiContext& g = *GImGui; return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id); } ImGuiWindow* ImGui::FindWindowByName(const char* name) { ImGuiID id = ImHashStr(name); return FindWindowByID(id); } static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; // Create window the first time ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name); window->Flags = flags; g.WindowsById.SetVoidPtr(window->ID, window); // Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. window->Pos = ImVec2(60, 60); // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. if (!(flags & ImGuiWindowFlags_NoSavedSettings)) if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID)) { // Retrieve settings from .ini file window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false); window->Pos = ImFloor(settings->Pos); window->Collapsed = settings->Collapsed; if (ImLengthSqr(settings->Size) > 0.00001f) size = ImFloor(settings->Size); } window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size); window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { window->AutoFitFramesX = window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } else { if (window->Size.x <= 0.0f) window->AutoFitFramesX = 2; if (window->Size.y <= 0.0f) window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0); } g.WindowsFocusOrder.push_back(window); if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus) g.Windows.push_front(window); // Quite slow but rare and only once else g.Windows.push_back(window); return window; } static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size) { ImGuiContext& g = *GImGui; if (g.NextWindowData.SizeConstraintCond != 0) { // Using -1,-1 on either X/Y axis to preserve the current size. ImRect cr = g.NextWindowData.SizeConstraintRect; new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x; new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y; if (g.NextWindowData.SizeCallback) { ImGuiSizeCallbackData data; data.UserData = g.NextWindowData.SizeCallbackUserData; data.Pos = window->Pos; data.CurrentSize = window->SizeFull; data.DesiredSize = new_size; g.NextWindowData.SizeCallback(&data); new_size = data.DesiredSize; } new_size.x = ImFloor(new_size.x); new_size.y = ImFloor(new_size.y); } // Minimum size if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize))) { new_size = ImMax(new_size, g.Style.WindowMinSize); new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows } return new_size; } static ImVec2 CalcSizeContents(ImGuiWindow* window) { if (window->Collapsed) if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) return window->SizeContents; if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0) return window->SizeContents; ImVec2 sz; sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x)); sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y)); return sz + window->WindowPadding; } static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; if (window->Flags & ImGuiWindowFlags_Tooltip) { // Tooltip always resize return size_contents; } else { // Maximum window size is determined by the display size const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0; const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0; ImVec2 size_min = style.WindowMinSize; if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups) size_min = ImMin(size_min, ImVec2(4.0f, 4.0f)); ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f)); // When the window cannot fit all contents (either because of constraints, either because screen is too small), // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding. ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit); if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) size_auto_fit.y += style.ScrollbarSize; if (size_auto_fit_after_constraint.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) size_auto_fit.x += style.ScrollbarSize; return size_auto_fit; } } ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window) { ImVec2 size_contents = CalcSizeContents(window); return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents)); } float ImGui::GetWindowScrollMaxX(ImGuiWindow* window) { return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x)); } float ImGui::GetWindowScrollMaxY(ImGuiWindow* window) { return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y)); } static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges) { ImGuiContext& g = *GImGui; ImVec2 scroll = window->Scroll; if (window->ScrollTarget.x < FLT_MAX) { float cr_x = window->ScrollTargetCenterRatio.x; scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x); } if (window->ScrollTarget.y < FLT_MAX) { // 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding. float cr_y = window->ScrollTargetCenterRatio.y; float target_y = window->ScrollTarget.y; if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y) target_y = 0.0f; if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y - window->WindowPadding.y + g.Style.ItemSpacing.y) target_y = window->SizeContents.y; scroll.y = target_y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y); } scroll = ImMax(scroll, ImVec2(0.0f, 0.0f)); if (!window->Collapsed && !window->SkipItems) { scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window)); scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window)); } return scroll; } static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags) { if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) return ImGuiCol_PopupBg; if (flags & ImGuiWindowFlags_ChildWindow) return ImGuiCol_ChildBg; return ImGuiCol_WindowBg; } static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size) { ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right ImVec2 size_expected = pos_max - pos_min; ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected); *out_pos = pos_min; if (corner_norm.x == 0.0f) out_pos->x -= (size_constrained.x - size_expected.x); if (corner_norm.y == 0.0f) out_pos->y -= (size_constrained.y - size_expected.y); *out_size = size_constrained; } struct ImGuiResizeGripDef { ImVec2 CornerPosN; ImVec2 InnerDir; int AngleMin12, AngleMax12; }; static const ImGuiResizeGripDef resize_grip_def[4] = { { ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right { ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left { ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left { ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right }; static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness) { ImRect rect = window->Rect(); if (thickness == 0.0f) rect.Max -= ImVec2(1,1); if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left IM_ASSERT(0); return ImRect(); } // Handle resize for: Resize Grips, Borders, Gamepad static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]) { ImGuiContext& g = *GImGui; ImGuiWindowFlags flags = window->Flags; if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) return; if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window. return; const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0; const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f); const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f; ImVec2 pos_target(FLT_MAX, FLT_MAX); ImVec2 size_target(FLT_MAX, FLT_MAX); // Resize grips and borders are on layer 1 window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); // Manual resize grips PushID("#RESIZE"); for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) { const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size); if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x); if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y); bool hovered, held; ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus); //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255)); if (hovered || held) g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE; if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0) { // Manual auto-fit when double-clicking size_target = CalcSizeAfterConstraint(window, size_auto_fit); ClearActiveID(); } else if (held) { // Resize from any of the four corners // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target); } if (resize_grip_n == 0 || held || hovered) resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); } for (int border_n = 0; border_n < resize_border_count; border_n++) { bool hovered, held; ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren); //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255)); if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held) { g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS; if (held) *border_held = border_n; } if (held) { ImVec2 border_target = window->Pos; ImVec2 border_posn; if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target); } } PopID(); // Navigation resize (keyboard/gamepad) if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window) { ImVec2 nav_resize_delta; if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavInputSource == ImGuiInputSource_NavGamepad) nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down); if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f) { const float NAV_RESIZE_SPEED = 600.0f; nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); g.NavWindowingToggleLayer = false; g.NavDisableMouseHover = true; resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive); // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck. size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta); } } // Apply back modified position/size to window if (size_target.x != FLT_MAX) { window->SizeFull = size_target; MarkIniSettingsDirty(window); } if (pos_target.x != FLT_MAX) { window->Pos = ImFloor(pos_target); MarkIniSettingsDirty(window); } // Resize nav layer window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->Size = window->SizeFull; } static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding) { ImGuiContext& g = *GImGui; ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size; window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping); } static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window) { ImGuiContext& g = *GImGui; float rounding = window->WindowRounding; float border_size = window->WindowBorderSize; if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground)) window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size); int border_held = window->ResizeBorderHeld; if (border_held != -1) { struct ImGuiResizeBorderDef { ImVec2 InnerDir; ImVec2 CornerPosN1, CornerPosN2; float OuterAngle; }; static const ImGuiResizeBorderDef resize_border_def[4] = { { ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top { ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right { ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom { ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left }; const ImGuiResizeBorderDef& def = resize_border_def[border_held]; ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f); window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle); window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f); window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual } if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) { float y = window->Pos.y + window->TitleBarHeight() - 1; window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize); } } void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; ImGuiWindowFlags flags = window->Flags; // Draw window + handle manual resize // As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame. const float window_rounding = window->WindowRounding; const float window_border_size = window->WindowBorderSize; if (window->Collapsed) { // Title bar only float backup_border_size = style.FrameBorderSize; g.Style.FrameBorderSize = window->WindowBorderSize; ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed); RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding); g.Style.FrameBorderSize = backup_border_size; } else { // Window background if (!(flags & ImGuiWindowFlags_NoBackground)) { ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags)); float alpha = 1.0f; if (g.NextWindowData.BgAlphaCond != 0) alpha = g.NextWindowData.BgAlphaVal; if (alpha != 1.0f) bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT); window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot); } g.NextWindowData.BgAlphaCond = 0; // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) { ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg); window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top); } // Menu bar if (flags & ImGuiWindowFlags_MenuBar) { ImRect menu_bar_rect = window->MenuBarRect(); menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them. window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top); if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y) window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize); } // Scrollbars if (window->ScrollbarX) Scrollbar(ImGuiAxis_X); if (window->ScrollbarY) Scrollbar(ImGuiAxis_Y); // Render resize grips (after their input handling so we don't have a frame of latency) if (!(flags & ImGuiWindowFlags_NoResize)) { for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++) { const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n]; const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN); window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size))); window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size))); window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12); window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]); } } // Borders RenderWindowOuterBorders(window); } } void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open) { ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; ImGuiWindowFlags flags = window->Flags; // Close & collapse button are on layer 1 (same as menus) and don't default focus const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); // Collapse button if (!(flags & ImGuiWindowFlags_NoCollapse)) if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos)) window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function // Close button if (p_open != NULL) { const float rad = g.FontSize * 0.5f; if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x - rad, window->Pos.y + style.FramePadding.y + rad), rad + 1)) *p_open = false; } window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->DC.ItemFlags = item_flags_backup; // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker) // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code.. const char* UNSAVED_DOCUMENT_MARKER = "*"; const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f; const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f); ImRect text_r = title_bar_rect; float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x); if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x); text_r.Min.x += pad_left; text_r.Max.x -= pad_right; ImRect clip_rect = text_r; clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton() RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect); if (flags & ImGuiWindowFlags_UnsavedDocument) { ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f); ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f)); RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect); } } void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window) { window->ParentWindow = parent_window; window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window; if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) window->RootWindow = parent_window->RootWindow; if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight; while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened) { IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL); window->RootWindowForNav = window->RootWindowForNav->ParentWindow; } } // Push a new Dear ImGui window to add widgets to. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. // - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame() IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet // Find or create ImGuiWindow* window = FindWindowByName(name); const bool window_just_created = (window == NULL); if (window_just_created) { ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here. window = CreateNewWindow(name, size_on_first_use, flags); } // Automatically disable manual moving/resizing when NoInputs is set if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs) flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize; if (flags & ImGuiWindowFlags_NavFlattened) IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow); const int current_frame = g.FrameCount; const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame); // Update the Appearing flag bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0); if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed window_just_activated_by_user |= (window != popup_ref.Window); } window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true); // Update Flags, LastFrameActive, BeginOrderXXX fields if (first_begin_of_the_frame) { window->Flags = (ImGuiWindowFlags)flags; window->LastFrameActive = current_frame; window->BeginOrderWithinParent = 0; window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++); } else { flags = window->Flags; } // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back(); ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow; IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow)); // Add to stack // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow() g.CurrentWindowStack.push_back(window); g.CurrentWindow = NULL; CheckStacksSize(window, true); if (flags & ImGuiWindowFlags_Popup) { ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size]; popup_ref.Window = window; g.BeginPopupStack.push_back(popup_ref); window->PopupId = popup_ref.PopupId; } if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow)) window->NavLastIds[0] = 0; // Process SetNextWindow***() calls bool window_pos_set_by_api = false; bool window_size_x_set_by_api = false, window_size_y_set_by_api = false; if (g.NextWindowData.PosCond) { window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0; if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f) { // May be processed on the next frame if this is our first frame and we are measuring size // FIXME: Look into removing the branch so everything can go through this same code path for consistency. window->SetWindowPosVal = g.NextWindowData.PosVal; window->SetWindowPosPivot = g.NextWindowData.PosPivotVal; window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); } else { SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond); } } if (g.NextWindowData.SizeCond) { window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f); window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f); SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond); } if (g.NextWindowData.ContentSizeCond) { // Adjust passed "client size" to become a "window size" window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal; if (window->SizeContentsExplicit.y != 0.0f) window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight(); } else if (first_begin_of_the_frame) { window->SizeContentsExplicit = ImVec2(0.0f, 0.0f); } if (g.NextWindowData.CollapsedCond) SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond); if (g.NextWindowData.FocusCond) FocusWindow(window); if (window->Appearing) SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false); // When reusing window again multiple times a frame, just append content (don't need to setup again) if (first_begin_of_the_frame) { // Initialize const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345) UpdateWindowParentAndRootLinks(window, flags, parent_window); window->Active = true; window->HasCloseButton = (p_open != NULL); window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX); window->IDStack.resize(1); // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged). // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere. bool window_title_visible_elsewhere = false; if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB window_title_visible_elsewhere = true; if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0) { size_t buf_len = (size_t)window->NameBufLen; window->Name = ImStrdupcpy(window->Name, &buf_len, name); window->NameBufLen = (int)buf_len; } // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS // Update contents size from last frame for auto-fitting (or use explicit size) window->SizeContents = CalcSizeContents(window); if (window->HiddenFramesCanSkipItems > 0) window->HiddenFramesCanSkipItems--; if (window->HiddenFramesCannotSkipItems > 0) window->HiddenFramesCannotSkipItems--; // Hide new windows for one frame until they calculate their size if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api)) window->HiddenFramesCannotSkipItems = 1; // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows) // We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size. if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0) { window->HiddenFramesCannotSkipItems = 1; if (flags & ImGuiWindowFlags_AlwaysAutoResize) { if (!window_size_x_set_by_api) window->Size.x = window->SizeFull.x = 0.f; if (!window_size_y_set_by_api) window->Size.y = window->SizeFull.y = 0.f; window->SizeContents = ImVec2(0.f, 0.f); } } SetCurrentWindow(window); // Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies) if (flags & ImGuiWindowFlags_ChildWindow) window->WindowBorderSize = style.ChildBorderSize; else window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize; window->WindowPadding = style.WindowPadding; if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f) window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f); window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x); window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y; // Collapse window by double-clicking on title bar // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse)) { // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar. ImRect title_bar_rect = window->TitleBarRect(); if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]) window->WantCollapseToggle = true; if (window->WantCollapseToggle) { window->Collapsed = !window->Collapsed; MarkIniSettingsDirty(window); FocusWindow(window); } } else { window->Collapsed = false; } window->WantCollapseToggle = false; // SIZE // Calculate auto-fit size, handle automatic resize const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents); ImVec2 size_full_modified(FLT_MAX, FLT_MAX); if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed) { // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc. if (!window_size_x_set_by_api) window->SizeFull.x = size_full_modified.x = size_auto_fit.x; if (!window_size_y_set_by_api) window->SizeFull.y = size_full_modified.y = size_auto_fit.y; } else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0) { // Auto-fit may only grow window during the first few frames // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. if (!window_size_x_set_by_api && window->AutoFitFramesX > 0) window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x; if (!window_size_y_set_by_api && window->AutoFitFramesY > 0) window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y; if (!window->Collapsed) MarkIniSettingsDirty(window); } // Apply minimum/maximum window size constraints and final size window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull); window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull; // SCROLLBAR STATUS // Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size). if (!window->Collapsed) { // When reading the current size we need to read it after size constraints have been applied float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x; float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y; window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar)); window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar)); if (window->ScrollbarX && !window->ScrollbarY) window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar); window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f); } // POSITION // Popup latch its initial position, will position itself when it appears next frame if (window_just_activated_by_user) { window->AutoPosLastDirection = ImGuiDir_None; if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api) window->Pos = g.BeginPopupStack.back().OpenPopupPos; } // Position child window if (flags & ImGuiWindowFlags_ChildWindow) { IM_ASSERT(parent_window && parent_window->Active); window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size; parent_window->DC.ChildWindows.push_back(window); if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = parent_window->DC.CursorPos; } const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0); if (window_pos_with_pivot) SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering) else if ((flags & ImGuiWindowFlags_ChildMenu) != 0) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize) window->Pos = FindBestWindowPosForPopup(window); else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip) window->Pos = FindBestWindowPosForPopup(window); // Clamp position so it stays visible // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. ImRect viewport_rect(GetViewportRect()); if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) { if (g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding); ClampWindowRect(window, viewport_rect, clamp_padding); } } window->Pos = ImFloor(window->Pos); // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies) window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding; // Apply scrolling window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true); window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX); // Apply window focus (new and reactivated windows are moved to front) bool want_focus = false; if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing)) { if (flags & ImGuiWindowFlags_Popup) want_focus = true; else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0) want_focus = true; } // Handle manual resize: Resize Grips, Borders, Gamepad int border_held = -1; ImU32 resize_grip_col[4] = { 0 }; const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4 const float resize_grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f); if (!window->Collapsed) UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]); window->ResizeBorderHeld = (signed char)border_held; // Default item width. Make it proportional to window size if window manually resizes if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); else window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f); // Store a backup of SizeFull which we will use next frame to decide if we need scrollbars. window->SizeFullAtLastBegin = window->SizeFull; // UPDATE RECTANGLES // Update various regions. Variables they depends on are set above in this function. // FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it. // NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out. window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x; window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight(); window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize))); window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize))); // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() window->OuterRectClipped = window->Rect(); window->OuterRectClipped.ClipWith(window->ClipRect); // Inner rectangle // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize; window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize); window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize); window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize); // Inner clipping rectangle will extend a little bit outside the work region. // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space. // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result. window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y); window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize))); window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y); // DRAWING // Setup draw list and outer clipping rectangle window->DrawList->Clear(); window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0); window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true); else PushClipRect(viewport_rect.Min, viewport_rect.Max, true); // Draw modal window background (darkens what is behind them, all viewports) const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0; const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow); if (dim_bg_for_modal || dim_bg_for_window_list) { const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio); window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col); } // Draw navigation selection/windowing rectangle background if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim) { ImRect bb = window->Rect(); bb.Expand(g.FontSize); if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding); } const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow; const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight); RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size); // Draw navigation selection/windowing rectangle border if (g.NavWindowingTargetAnim == window) { float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding); ImRect bb = window->Rect(); bb.Expand(g.FontSize); if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward { bb.Expand(-g.FontSize - 1.0f); rounding = window->WindowRounding; } window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f); } // Setup drawing context // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.) window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x; window->DC.GroupOffset.x = 0.0f; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; window->DC.CurrentLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.NavHideHighlightOneFrame = false; window->DC.NavHasScroll = (GetWindowScrollMaxY(window) > 0.0f); window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext; window->DC.NavLayerActiveMaskNext = 0x00; window->DC.MenuBarAppending = false; window->DC.ChildWindows.resize(0); window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical; window->DC.FocusCounterAll = window->DC.FocusCounterTab = -1; window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_; window->DC.ItemWidth = window->ItemWidthDefault; window->DC.TextWrapPos = -1.0f; // disabled window->DC.ItemFlagsStack.resize(0); window->DC.ItemWidthStack.resize(0); window->DC.TextWrapPosStack.resize(0); window->DC.CurrentColumns = NULL; window->DC.TreeDepth = 0; window->DC.TreeStoreMayJumpToParentOnPop = 0x00; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user); if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags)) { window->DC.ItemFlags = parent_window->DC.ItemFlags; window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); } if (window->AutoFitFramesX > 0) window->AutoFitFramesX--; if (window->AutoFitFramesY > 0) window->AutoFitFramesY--; // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there) if (want_focus) { FocusWindow(window); NavInitWindow(window, false); } // Title bar if (!(flags & ImGuiWindowFlags_NoTitleBar)) RenderWindowTitleBarContents(window, title_bar_rect, name, p_open); // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. // Maybe we can support CTRL+C on every element? /* if (g.ActiveId == move_id) if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) LogToClipboard(); */ // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin(). // This is useful to allow creating context menus on title bar only, etc. window->DC.LastItemId = window->MoveId; window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0; window->DC.LastItemRect = title_bar_rect; #ifdef IMGUI_ENABLE_TEST_ENGINE if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId); #endif } else { // Append SetCurrentWindow(window); } PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true); // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused) if (first_begin_of_the_frame) window->WriteAccessed = false; window->BeginCount++; g.NextWindowData.Clear(); if (flags & ImGuiWindowFlags_ChildWindow) { // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar). IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y) window->HiddenFramesCanSkipItems = 1; // Completely hide along with parent or if parent is collapsed if (parent_window && (parent_window->Collapsed || parent_window->Hidden)) window->HiddenFramesCanSkipItems = 1; } // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point) if (style.Alpha <= 0.0f) window->HiddenFramesCanSkipItems = 1; // Update the Hidden flag window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0); // Update the SkipItems flag, used to early out of all items functions (no layout required) bool skip_items = false; if (window->Collapsed || !window->Active || window->Hidden) if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0) skip_items = true; window->SkipItems = skip_items; return !skip_items; } // Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags) { // Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file. if (size_first_use.x != 0.0f || size_first_use.y != 0.0f) SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver); // Old API feature: override the window background alpha with a parameter. if (bg_alpha_override >= 0.0f) SetNextWindowBgAlpha(bg_alpha_override); return Begin(name, p_open, flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS void ImGui::End() { ImGuiContext& g = *GImGui; if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow) { IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!"); return; // FIXME-ERRORHANDLING } IM_ASSERT(g.CurrentWindowStack.Size > 0); ImGuiWindow* window = g.CurrentWindow; if (window->DC.CurrentColumns != NULL) EndColumns(); PopClipRect(); // Inner window clip rectangle // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging LogFinish(); // Pop from window stack g.CurrentWindowStack.pop_back(); if (window->Flags & ImGuiWindowFlags_Popup) g.BeginPopupStack.pop_back(); CheckStacksSize(window, false); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } void ImGui::BringWindowToFocusFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.WindowsFocusOrder.back() == window) return; for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the front most window if (g.WindowsFocusOrder[i] == window) { memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*)); g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window; break; } } void ImGui::BringWindowToDisplayFront(ImGuiWindow* window) { ImGuiContext& g = *GImGui; ImGuiWindow* current_front_window = g.Windows.back(); if (current_front_window == window || current_front_window->RootWindow == window) return; for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window if (g.Windows[i] == window) { memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*)); g.Windows[g.Windows.Size - 1] = window; break; } } void ImGui::BringWindowToDisplayBack(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.Windows[0] == window) return; for (int i = 0; i < g.Windows.Size; i++) if (g.Windows[i] == window) { memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*)); g.Windows[0] = window; break; } } // Moving window to front of display and set focus (which happens to be back of our sorted list) void ImGui::FocusWindow(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (g.NavWindow != window) { g.NavWindow = window; if (window && g.NavDisableMouseHover) g.NavMousePosDirty = true; g.NavInitRequest = false; g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId g.NavIdIsAlive = false; g.NavLayer = ImGuiNavLayer_Main; //IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL); } // Close popups if any ClosePopupsOverWindow(window, false); // Passing NULL allow to disable keyboard focus if (!window) return; // Move the root window to the top of the pile if (window->RootWindow) window = window->RootWindow; // Steal focus on active widgets if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it.. if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window) ClearActiveID(); // Bring to front BringWindowToFocusFront(window); if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) BringWindowToDisplayFront(window); } void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window) { ImGuiContext& g = *GImGui; int start_idx = g.WindowsFocusOrder.Size - 1; if (under_this_window != NULL) { int under_this_window_idx = FindWindowFocusIndex(under_this_window); if (under_this_window_idx != -1) start_idx = under_this_window_idx - 1; } for (int i = start_idx; i >= 0; i--) { // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user. ImGuiWindow* window = g.WindowsFocusOrder[i]; if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow)) if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) { ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window); FocusWindow(focus_window); return; } } FocusWindow(NULL); } void ImGui::SetNextItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); window->DC.NextItemWidth = item_width; } void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width); window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); } void ImGui::PushMultiItemsWidths(int components, float w_full) { ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = GImGui->Style; const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); window->DC.ItemWidthStack.push_back(w_item_last); for (int i = 0; i < components-1; i++) window->DC.ItemWidthStack.push_back(w_item_one); window->DC.ItemWidth = window->DC.ItemWidthStack.back(); } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidthStack.pop_back(); window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back(); } // Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(), // Then consume the float ImGui::GetNextItemWidth() { ImGuiWindow* window = GImGui->CurrentWindow; float w; if (window->DC.NextItemWidth != FLT_MAX) { w = window->DC.NextItemWidth; window->DC.NextItemWidth = FLT_MAX; } else { w = window->DC.ItemWidth; } if (w < 0.0f) { float region_max_x = GetWorkRectMax().x; w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w); } w = (float)(int)w; return w; } // Calculate item width *without* popping/consuming NextItemWidth if it was set. // (rarely used, which is why we avoid calling this from GetNextItemWidth() and instead do a backup/restore here) float ImGui::CalcItemWidth() { ImGuiWindow* window = GImGui->CurrentWindow; float backup_next_item_width = window->DC.NextItemWidth; float w = GetNextItemWidth(); window->DC.NextItemWidth = backup_next_item_width; return w; } // [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == GetNextItemWidth(). // Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical. // Note that only CalcItemWidth() is publicly exposed. // The 4.0f here may be changed to match GetNextItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable) ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h) { ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 region_max; if (size.x < 0.0f || size.y < 0.0f) region_max = GetWorkRectMax(); if (size.x == 0.0f) size.x = default_w; else if (size.x < 0.0f) size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x); if (size.y == 0.0f) size.y = default_h; else if (size.y < 0.0f) size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y); return size; } void ImGui::SetCurrentFont(ImFont* font) { ImGuiContext& g = *GImGui; IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(font->Scale > 0.0f); g.Font = font; g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale); g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; ImFontAtlas* atlas = g.Font->ContainerAtlas; g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel; g.DrawListSharedData.Font = g.Font; g.DrawListSharedData.FontSize = g.FontSize; } void ImGui::PushFont(ImFont* font) { ImGuiContext& g = *GImGui; if (!font) font = GetDefaultFont(); SetCurrentFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { ImGuiContext& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back()); } void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (enabled) window->DC.ItemFlags |= option; else window->DC.ItemFlags &= ~option; window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags); } void ImGui::PopItemFlag() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemFlagsStack.pop_back(); window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back(); } // FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system. void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { PopItemFlag(); } void ImGui::PushButtonRepeat(bool repeat) { PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat); } void ImGui::PopButtonRepeat() { PopItemFlag(); } void ImGui::PushTextWrapPos(float wrap_pos_x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPos = wrap_pos_x; window->DC.TextWrapPosStack.push_back(wrap_pos_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPosStack.pop_back(); window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back(); } // FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32 void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col) { ImGuiContext& g = *GImGui; ImGuiColorMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = ColorConvertU32ToFloat4(col); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { ImGuiContext& g = *GImGui; ImGuiColorMod backup; backup.Col = idx; backup.BackupValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { ImGuiContext& g = *GImGui; while (count > 0) { ImGuiColorMod& backup = g.ColorModifiers.back(); g.Style.Colors[backup.Col] = backup.BackupValue; g.ColorModifiers.pop_back(); count--; } } struct ImGuiStyleVarInfo { ImGuiDataType Type; ImU32 Count; ImU32 Offset; void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); } }; static const ImGuiStyleVarInfo GStyleVarInfo[] = { { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign }; static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx) { IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT); IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT); return &GStyleVarInfo[idx]; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1) { ImGuiContext& g = *GImGui; float* pvar = (float*)var_info->GetVarPtr(&g.Style); g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!"); } void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx); if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2) { ImGuiContext& g = *GImGui; ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style); g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar)); *pvar = val; return; } IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!"); } void ImGui::PopStyleVar(int count) { ImGuiContext& g = *GImGui; while (count > 0) { // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it. ImGuiStyleMod& backup = g.StyleModifiers.back(); const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx); void* data = info->GetVarPtr(&g.Style); if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; } else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; } g.StyleModifiers.pop_back(); count--; } } const char* ImGui::GetStyleColorName(ImGuiCol idx) { // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; switch (idx) { case ImGuiCol_Text: return "Text"; case ImGuiCol_TextDisabled: return "TextDisabled"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildBg: return "ChildBg"; case ImGuiCol_PopupBg: return "PopupBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgActive: return "TitleBgActive"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; case ImGuiCol_MenuBarBg: return "MenuBarBg"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; case ImGuiCol_CheckMark: return "CheckMark"; case ImGuiCol_SliderGrab: return "SliderGrab"; case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; case ImGuiCol_Button: return "Button"; case ImGuiCol_ButtonHovered: return "ButtonHovered"; case ImGuiCol_ButtonActive: return "ButtonActive"; case ImGuiCol_Header: return "Header"; case ImGuiCol_HeaderHovered: return "HeaderHovered"; case ImGuiCol_HeaderActive: return "HeaderActive"; case ImGuiCol_Separator: return "Separator"; case ImGuiCol_SeparatorHovered: return "SeparatorHovered"; case ImGuiCol_SeparatorActive: return "SeparatorActive"; case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; case ImGuiCol_Tab: return "Tab"; case ImGuiCol_TabHovered: return "TabHovered"; case ImGuiCol_TabActive: return "TabActive"; case ImGuiCol_TabUnfocused: return "TabUnfocused"; case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_DragDropTarget: return "DragDropTarget"; case ImGuiCol_NavHighlight: return "NavHighlight"; case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight"; case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg"; case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg"; } IM_ASSERT(0); return "Unknown"; } bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent) { if (window->RootWindow == potential_parent) return true; while (window != NULL) { if (window == potential_parent) return true; window = window->ParentWindow; } return false; } bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags) { IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function ImGuiContext& g = *GImGui; if (flags & ImGuiHoveredFlags_AnyWindow) { if (g.HoveredWindow == NULL) return false; } else { switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) { case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows: if (g.HoveredRootWindow != g.CurrentWindow->RootWindow) return false; break; case ImGuiHoveredFlags_RootWindow: if (g.HoveredWindow != g.CurrentWindow->RootWindow) return false; break; case ImGuiHoveredFlags_ChildWindows: if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow)) return false; break; default: if (g.HoveredWindow != g.CurrentWindow) return false; break; } } if (!IsWindowContentHoverable(g.HoveredWindow, flags)) return false; if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId) return false; return true; } bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags) { ImGuiContext& g = *GImGui; if (flags & ImGuiFocusedFlags_AnyWindow) return g.NavWindow != NULL; IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End() switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows)) { case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows: return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow; case ImGuiFocusedFlags_RootWindow: return g.NavWindow == g.CurrentWindow->RootWindow; case ImGuiFocusedFlags_ChildWindows: return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow); default: return g.NavWindow == g.CurrentWindow; } } // Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext) // Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly. // If you want a window to never be focused, you may use the e.g. NoInputs flag. bool ImGui::IsWindowNavFocusable(ImGuiWindow* window) { return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus); } float ImGui::GetWindowWidth() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.x; } float ImGui::GetWindowHeight() { ImGuiWindow* window = GImGui->CurrentWindow; return window->Size.y; } ImVec2 ImGui::GetWindowPos() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; return window->Pos; } void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x) { window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. window->Scroll.x = new_scroll_x; window->DC.CursorMaxPos.x -= window->Scroll.x; } void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y) { window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it. window->Scroll.y = new_scroll_y; window->DC.CursorMaxPos.y -= window->Scroll.y; } void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX); // Set const ImVec2 old_pos = window->Pos; window->Pos = ImFloor(pos); window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. } void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond) { ImGuiWindow* window = GetCurrentWindowRead(); SetWindowPos(window, pos, cond); } void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowPos(window, pos, cond); } ImVec2 ImGui::GetWindowSize() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Size; } void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) return; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); // Set if (size.x > 0.0f) { window->AutoFitFramesX = 0; window->SizeFull.x = ImFloor(size.x); } else { window->AutoFitFramesX = 2; window->AutoFitOnlyGrows = false; } if (size.y > 0.0f) { window->AutoFitFramesY = 0; window->SizeFull.y = ImFloor(size.y); } else { window->AutoFitFramesY = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond) { SetWindowSize(GImGui->CurrentWindow, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowSize(window, size, cond); } void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing); // Set window->Collapsed = collapsed; } void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond) { SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond); } bool ImGui::IsWindowCollapsed() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Collapsed; } bool ImGui::IsWindowAppearing() { ImGuiWindow* window = GetCurrentWindowRead(); return window->Appearing; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond) { if (ImGuiWindow* window = FindWindowByName(name)) SetWindowCollapsed(window, collapsed, cond); } void ImGui::SetWindowFocus() { FocusWindow(GImGui->CurrentWindow); } void ImGui::SetWindowFocus(const char* name) { if (name) { if (ImGuiWindow* window = FindWindowByName(name)) FocusWindow(window); } else { FocusWindow(NULL); } } void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.PosVal = pos; g.NextWindowData.PosPivotVal = pivot; g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.SizeVal = size; g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data) { ImGuiContext& g = *GImGui; g.NextWindowData.SizeConstraintCond = ImGuiCond_Always; g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max); g.NextWindowData.SizeCallback = custom_callback; g.NextWindowData.SizeCallbackUserData = custom_callback_user_data; } void ImGui::SetNextWindowContentSize(const ImVec2& size) { ImGuiContext& g = *GImGui; g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value. g.NextWindowData.ContentSizeCond = ImGuiCond_Always; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond) { ImGuiContext& g = *GImGui; IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags. g.NextWindowData.CollapsedVal = collapsed; g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always; } void ImGui::SetNextWindowFocus() { ImGuiContext& g = *GImGui; g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) } void ImGui::SetNextWindowBgAlpha(float alpha) { ImGuiContext& g = *GImGui; g.NextWindowData.BgAlphaVal = alpha; g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op) } // FIXME: This is in window space (not screen space!). We should try to obsolete all those functions. ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max - window->Pos; if (window->DC.CurrentColumns) mx.x = GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x; return mx; } // [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features. ImVec2 ImGui::GetWorkRectMax() { ImGuiWindow* window = GImGui->CurrentWindow; ImVec2 mx = window->ContentsRegionRect.Max; if (window->DC.CurrentColumns) mx.x = window->Pos.x + GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x; return mx; } ImVec2 ImGui::GetContentRegionAvail() { ImGuiWindow* window = GImGui->CurrentWindow; return GetWorkRectMax() - window->DC.CursorPos; } // In window space (not screen space!) ImVec2 ImGui::GetWindowContentRegionMin() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Min - window->Pos; } ImVec2 ImGui::GetWindowContentRegionMax() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.Max - window->Pos; } float ImGui::GetWindowContentRegionWidth() { ImGuiWindow* window = GetCurrentWindowRead(); return window->ContentsRegionRect.GetWidth(); } float ImGui::GetTextLineHeight() { ImGuiContext& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } float ImGui::GetFrameHeight() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f; } float ImGui::GetFrameHeightWithSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y; } ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } ImFont* ImGui::GetFont() { return GImGui->Font; } float ImGui::GetFontSize() { return GImGui->FontSize; } ImVec2 ImGui::GetFontTexUvWhitePixel() { return GImGui->DrawListSharedData.TexUvWhitePixel; } void ImGui::SetWindowFontScale(float scale) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize(); } // User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient. // Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos - window->Pos + window->Scroll; } float ImGui::GetCursorPosX() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x; } float ImGui::GetCursorPosY() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y; } void ImGui::SetCursorPos(const ImVec2& local_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = window->Pos - window->Scroll + local_pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } ImVec2 ImGui::GetCursorStartPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorStartPos - window->Pos; } ImVec2 ImGui::GetCursorScreenPos() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CursorPos; } void ImGui::SetCursorScreenPos(const ImVec2& pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } float ImGui::GetScrollX() { return GImGui->CurrentWindow->Scroll.x; } float ImGui::GetScrollY() { return GImGui->CurrentWindow->Scroll.y; } float ImGui::GetScrollMaxX() { return GetWindowScrollMaxX(GImGui->CurrentWindow); } float ImGui::GetScrollMaxY() { return GetWindowScrollMaxY(GImGui->CurrentWindow); } void ImGui::SetScrollX(float scroll_x) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.x = scroll_x; window->ScrollTargetCenterRatio.x = 0.0f; } void ImGui::SetScrollY(float scroll_y) { ImGuiWindow* window = GetCurrentWindow(); window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY window->ScrollTargetCenterRatio.y = 0.0f; } void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio) { // We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f); window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y); window->ScrollTargetCenterRatio.y = center_y_ratio; } // center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item. void ImGui::SetScrollHereY(float center_y_ratio) { ImGuiWindow* window = GetCurrentWindow(); float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line. SetScrollFromPosY(target_y, center_y_ratio); } void ImGui::ActivateItem(ImGuiID id) { ImGuiContext& g = *GImGui; g.NavNextActivateId = id; } void ImGui::SetKeyboardFocusHere(int offset) { IM_ASSERT(offset >= -1); // -1 is allowed but not below ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; g.FocusRequestNextWindow = window; g.FocusRequestNextCounterAll = window->DC.FocusCounterAll + 1 + offset; g.FocusRequestNextCounterTab = INT_MAX; } void ImGui::SetItemDefaultFocus() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!window->Appearing) return; if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent) { g.NavInitRequest = false; g.NavInitResultId = g.NavWindow->DC.LastItemId; g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos); NavUpdateAnyRequestFlag(); if (!IsItemVisible()) SetScrollHereY(); } } void ImGui::SetStateStorage(ImGuiStorage* tree) { ImGuiWindow* window = GImGui->CurrentWindow; window->DC.StateStorage = tree ? tree : &window->StateStorage; } ImGuiStorage* ImGui::GetStateStorage() { ImGuiWindow* window = GImGui->CurrentWindow; return window->DC.StateStorage; } void ImGui::PushID(const char* str_id) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(str_id)); } void ImGui::PushID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end)); } void ImGui::PushID(const void* ptr_id) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id)); } void ImGui::PushID(int int_id) { const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id)); } // Push a given id value ignoring the ID stack as a seed. void ImGui::PushOverrideID(ImGuiID id) { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.push_back(id); } void ImGui::PopID() { ImGuiWindow* window = GImGui->CurrentWindow; window->IDStack.pop_back(); } ImGuiID ImGui::GetID(const char* str_id) { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(str_id); } ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(str_id_begin, str_id_end); } ImGuiID ImGui::GetID(const void* ptr_id) { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(ptr_id); } bool ImGui::IsRectVisible(const ImVec2& size) { ImGuiWindow* window = GImGui->CurrentWindow; return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size)); } bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max) { ImGuiWindow* window = GImGui->CurrentWindow; return window->ClipRect.Overlaps(ImRect(rect_min, rect_max)); } // Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.) void ImGui::BeginGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.BackupIndent = window->DC.Indent; group_data.BackupGroupOffset = window->DC.GroupOffset; group_data.BackupCurrentLineSize = window->DC.CurrentLineSize; group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive; group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive; group_data.AdvanceCursor = true; window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x; window->DC.Indent = window->DC.GroupOffset; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); if (g.LogEnabled) g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return } void ImGui::EndGroup() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls ImGuiGroupData& group_data = window->DC.GroupStack.back(); ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); group_bb.Max = ImMax(group_bb.Min, group_bb.Max); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); window->DC.Indent = group_data.BackupIndent; window->DC.GroupOffset = group_data.BackupGroupOffset; window->DC.CurrentLineSize = group_data.BackupCurrentLineSize; window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; if (g.LogEnabled) g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return if (group_data.AdvanceCursor) { window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now. ItemSize(group_bb.GetSize(), 0.0f); ItemAdd(group_bb, 0); } // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group. // It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets. // (and if you grep for LastItemId you'll notice it is only used in that context. if ((group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId) // && g.ActiveIdWindow->RootWindow == window->RootWindow) window->DC.LastItemId = g.ActiveId; else if (!group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive) // && g.ActiveIdPreviousFrameWindow->RootWindow == window->RootWindow) window->DC.LastItemId = g.ActiveIdPreviousFrame; window->DC.LastItemRect = group_bb; window->DC.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug] } // Gets back to previous line and continue with horizontal layout // offset_from_start_x == 0 : follow right after previous item // offset_from_start_x != 0 : align to specified x position (relative to window/group left) // spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0 // spacing_w >= 0 : enforce spacing amount void ImGui::SameLine(float offset_from_start_x, float spacing_w) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; if (offset_from_start_x != 0.0f) { if (spacing_w < 0.0f) spacing_w = 0.0f; window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } else { if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x; window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w; window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y; } window->DC.CurrentLineSize = window->DC.PrevLineSize; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; } void ImGui::Indent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; } void ImGui::Unindent(float indent_w) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x; } //----------------------------------------------------------------------------- // [SECTION] TOOLTIPS //----------------------------------------------------------------------------- void ImGui::BeginTooltip() { ImGuiContext& g = *GImGui; if (g.DragDropWithinSourceOrTarget) { // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor) // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor. // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do. //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding; ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale); SetNextWindowPos(tooltip_pos); SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f); //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :( BeginTooltipEx(0, true); } else { BeginTooltipEx(0, false); } } // Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first. void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip) { ImGuiContext& g = *GImGui; char window_name[16]; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount); if (override_previous_tooltip) if (ImGuiWindow* window = FindWindowByName(window_name)) if (window->Active) { // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one. window->Hidden = true; window->HiddenFramesCanSkipItems = 1; ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount); } ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; Begin(window_name, NULL, flags | extra_flags); } void ImGui::EndTooltip() { IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls End(); } void ImGui::SetTooltipV(const char* fmt, va_list args) { ImGuiContext& g = *GImGui; if (g.DragDropWithinSourceOrTarget) BeginTooltip(); else BeginTooltipEx(0, true); TextV(fmt, args); EndTooltip(); } void ImGui::SetTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); SetTooltipV(fmt, args); va_end(args); } //----------------------------------------------------------------------------- // [SECTION] POPUPS //----------------------------------------------------------------------------- bool ImGui::IsPopupOpen(ImGuiID id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id; } bool ImGui::IsPopupOpen(const char* str_id) { ImGuiContext& g = *GImGui; return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id); } ImGuiWindow* ImGui::GetFrontMostPopupModal() { ImGuiContext& g = *GImGui; for (int n = g.OpenPopupStack.Size-1; n >= 0; n--) if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window) if (popup->Flags & ImGuiWindowFlags_Modal) return popup; return NULL; } void ImGui::OpenPopup(const char* str_id) { ImGuiContext& g = *GImGui; OpenPopupEx(g.CurrentWindow->GetID(str_id)); } // Mark popup as open (toggle toward open state). // Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block. // Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level). // One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL) void ImGui::OpenPopupEx(ImGuiID id) { ImGuiContext& g = *GImGui; ImGuiWindow* parent_window = g.CurrentWindow; int current_stack_size = g.BeginPopupStack.Size; ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack. popup_ref.PopupId = id; popup_ref.Window = NULL; popup_ref.SourceWindow = g.NavWindow; popup_ref.OpenFrameCount = g.FrameCount; popup_ref.OpenParentId = parent_window->IDStack.back(); popup_ref.OpenPopupPos = NavCalcPreferredRefPos(); popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos; //IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id); if (g.OpenPopupStack.Size < current_stack_size + 1) { g.OpenPopupStack.push_back(popup_ref); } else { // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand. if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1) { g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount; } else { // Close child popups if any, then flag popup for open/reopen g.OpenPopupStack.resize(current_stack_size + 1); g.OpenPopupStack[current_stack_size] = popup_ref; } // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow(). // This is equivalent to what ClosePopupToLevel() does. //if (g.OpenPopupStack[current_stack_size].PopupId == id) // FocusWindow(parent_window); } } bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) OpenPopupEx(id); return true; } return false; } void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.empty()) return; // When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it. // Don't close our own child popup windows. int popup_count_to_keep = 0; if (ref_window) { // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow) for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++) { ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep]; if (!popup.Window) continue; IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0); if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow) continue; // Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow) bool popup_or_descendent_is_ref_window = false; for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++) if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window) if (popup_window->RootWindow == ref_window->RootWindow) popup_or_descendent_is_ref_window = true; if (!popup_or_descendent_is_ref_window) break; } } if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below { //IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep); ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup); } } void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup) { ImGuiContext& g = *GImGui; IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size); ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow; ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window; g.OpenPopupStack.resize(remaining); if (restore_focus_to_window_under_popup) { if (focus_window && !focus_window->WasActive && popup_window) { // Fallback FocusTopMostWindowUnderOne(popup_window, NULL); } else { if (g.NavLayer == 0 && focus_window) focus_window = NavRestoreLastChildNavWindow(focus_window); FocusWindow(focus_window); } } } // Close the popup we have begin-ed into. void ImGui::CloseCurrentPopup() { ImGuiContext& g = *GImGui; int popup_idx = g.BeginPopupStack.Size - 1; if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId) return; // Closing a menu closes its top-most parent popup (unless a modal) while (popup_idx > 0) { ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window; ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window; bool close_parent = false; if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu)) if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal)) close_parent = true; if (!close_parent) break; popup_idx--; } //IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx); ClosePopupToLevel(popup_idx, true); // A common pattern is to close a popup when selecting a menu item/selectable that will open another window. // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window. // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic. if (ImGuiWindow* window = g.NavWindow) window->DC.NavHideHighlightOneFrame = true; } bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags) { ImGuiContext& g = *GImGui; if (!IsPopupOpen(id)) { g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values return false; } char name[20]; if (extra_flags & ImGuiWindowFlags_ChildMenu) ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth else ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup); if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display) EndPopup(); return is_open; } bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance { g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values return false; } flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags); } // If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup. // Note that popup visibility status is owned by imgui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here. bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiID id = window->GetID(name); if (!IsPopupOpen(id)) { g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values return false; } // Center modal windows by default // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window. if (g.NextWindowData.PosCond == 0) SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f)); flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings; const bool is_open = Begin(name, p_open, flags); if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display) { EndPopup(); if (is_open) ClosePopupToLevel(g.BeginPopupStack.Size, true); return false; } return is_open; } void ImGui::EndPopup() { ImGuiContext& g = *GImGui; IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls IM_ASSERT(g.BeginPopupStack.Size > 0); // Make all menus and popups wrap around for now, may need to expose that policy. NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY); End(); } // This is a helper to handle the simplest case of associating one named popup to one given widget. // You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters). // You can pass a NULL str_id to use the identifier of the last item. bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button) { ImGuiWindow* window = GImGui->CurrentWindow; ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict! IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item) if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items) { if (!str_id) str_id = "window_context"; ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) if (also_over_items || !IsAnyItemHovered()) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button) { if (!str_id) str_id = "void_context"; ImGuiID id = GImGui->CurrentWindow->GetID(str_id); if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow)) OpenPopupEx(id); return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings); } // r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.) // r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it. ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy) { ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size); //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255)); //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255)); // Combo Box policy (we want a connecting edge) if (policy == ImGuiPopupPositionPolicy_ComboBox) { const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) { const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; ImVec2 pos; if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default) if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left if (!r_outer.Contains(ImRect(pos, pos + size))) continue; *last_dir = dir; return pos; } } // Default popup policy const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left }; for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++) { const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n]; if (n != -1 && dir == *last_dir) // Already tried this direction? continue; float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x); float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y); if (avail_w < size.x || avail_h < size.y) continue; ImVec2 pos; pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x; pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y; *last_dir = dir; return pos; } // Fallback, try to keep within display *last_dir = ImGuiDir_None; ImVec2 pos = ref_pos; pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x); pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y); return pos; } ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window) { IM_UNUSED(window); ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding; ImRect r_screen = GetViewportRect(); r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f)); return r_screen; } ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window) { ImGuiContext& g = *GImGui; ImRect r_outer = GetWindowAllowedExtentRect(window); if (window->Flags & ImGuiWindowFlags_ChildMenu) { // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds. // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu. IM_ASSERT(g.CurrentWindow == window); ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2]; float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x). ImRect r_avoid; if (parent_window->DC.MenuBarAppending) r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight()); else r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX); return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); } if (window->Flags & ImGuiWindowFlags_Popup) { ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1); return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); } if (window->Flags & ImGuiWindowFlags_Tooltip) { // Position tooltip (always follows mouse) float sc = g.Style.MouseCursorScale; ImVec2 ref_pos = NavCalcPreferredRefPos(); ImRect r_avoid; if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos)) r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8); else r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important. ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid); if (window->AutoPosLastDirection == ImGuiDir_None) pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible. return pos; } IM_ASSERT(0); return window->Pos; } //----------------------------------------------------------------------------- // [SECTION] KEYBOARD/GAMEPAD NAVIGATION //----------------------------------------------------------------------------- ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy) { if (ImFabs(dx) > ImFabs(dy)) return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left; return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up; } static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1) { if (a1 < b0) return a1 - b0; if (b1 < a0) return a0 - b1; return 0.0f; } static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect) { if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) { r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y); r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y); } else { r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x); r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x); } } // Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057 static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavLayer != window->DC.NavLayerCurrent) return false; const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width) g.NavScoringCount++; // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring if (window->ParentWindow == g.NavWindow) { IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened); if (!window->ClipRect.Contains(cand)) return false; cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window } // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items) // For example, this ensure that items in one column are not reached when moving vertically from items in another column. NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect); // Compute distance between boxes // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed. float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x); float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items if (dby != 0.0f && dbx != 0.0f) dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f); float dist_box = ImFabs(dbx) + ImFabs(dby); // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter) float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x); float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y); float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee) // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance ImGuiDir quadrant; float dax = 0.0f, day = 0.0f, dist_axial = 0.0f; if (dbx != 0.0f || dby != 0.0f) { // For non-overlapping boxes, use distance between boxes dax = dbx; day = dby; dist_axial = dist_box; quadrant = ImGetDirQuadrantFromDelta(dbx, dby); } else if (dcx != 0.0f || dcy != 0.0f) { // For overlapping boxes with different centers, use distance between centers dax = dcx; day = dcy; dist_axial = dist_center; quadrant = ImGetDirQuadrantFromDelta(dcx, dcy); } else { // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter) quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right; } #if IMGUI_DEBUG_NAV_SCORING char buf[128]; if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max)) { ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]); ImDrawList* draw_list = ImGui::GetForegroundDrawList(window); draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100)); draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200)); draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150)); draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf); } else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate. { if (ImGui::IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; } if (quadrant == g.NavMoveDir) { ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center); ImDrawList* draw_list = ImGui::GetForegroundDrawList(window); draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200)); draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf); } } #endif // Is it in the quadrant we're interesting in moving to? bool new_best = false; if (quadrant == g.NavMoveDir) { // Does it beat the current best candidate? if (dist_box < result->DistBox) { result->DistBox = dist_box; result->DistCenter = dist_center; return true; } if (dist_box == result->DistBox) { // Try using distance between center points to break ties if (dist_center < result->DistCenter) { result->DistCenter = dist_center; new_best = true; } else if (dist_center == result->DistCenter) { // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index), // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis. if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance new_best = true; } } } // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness) // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too. // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward. // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option? if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f)) { result->DistAxial = dist_axial; new_best = true; } return new_best; } // We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above) static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id) { ImGuiContext& g = *GImGui; //if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag. // return; const ImGuiItemFlags item_flags = window->DC.ItemFlags; const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos); // Process Init Request if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent) { // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0) { g.NavInitResultId = id; g.NavInitResultRectRel = nav_bb_rel; } if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus)) { g.NavInitRequest = false; // Found a match, clear request NavUpdateAnyRequestFlag(); } } // Process Move Request (scoring for navigation) // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy) if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav))) { ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; #if IMGUI_DEBUG_NAV_SCORING // [DEBUG] Score all items in NavWindow at all times if (!g.NavMoveRequest) g.NavMoveDir = g.NavMoveDirLast; bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest; #else bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb); #endif if (new_best) { result->ID = id; result->SelectScopeId = g.MultiSelectScopeId; result->Window = window; result->RectRel = nav_bb_rel; } const float VISIBLE_RATIO = 0.70f; if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb)) if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO) if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb)) { result = &g.NavMoveResultLocalVisibleSet; result->ID = id; result->SelectScopeId = g.MultiSelectScopeId; result->Window = window; result->RectRel = nav_bb_rel; } } // Update window-relative bounding box of navigated item if (g.NavId == id) { g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window. g.NavLayer = window->DC.NavLayerCurrent; g.NavIdIsAlive = true; g.NavIdTabCounter = window->DC.FocusCounterTab; window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position) } } bool ImGui::NavMoveRequestButNoResultYet() { ImGuiContext& g = *GImGui; return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0; } void ImGui::NavMoveRequestCancel() { ImGuiContext& g = *GImGui; g.NavMoveRequest = false; NavUpdateAnyRequestFlag(); } void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None); ImGui::NavMoveRequestCancel(); g.NavMoveDir = move_dir; g.NavMoveClipDir = clip_dir; g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; g.NavMoveRequestFlags = move_flags; g.NavWindow->NavRectRel[g.NavLayer] = bb_rel; } void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags) { ImGuiContext& g = *GImGui; if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0) return; IM_ASSERT(move_flags != 0); // No points calling this with no wrapping ImRect bb_rel = window->NavRectRel[0]; ImGuiDir clip_dir = g.NavMoveDir; if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) { bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x) - window->Scroll.x; if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX))) { bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x; if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) { bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y) - window->Scroll.y; if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY))) { bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y; if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; } NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags); } } // FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0). // This way we could find the last focused window among our children. It would be much less confusing this way? static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window) { ImGuiWindow* parent_window = nav_window; while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) parent_window = parent_window->ParentWindow; if (parent_window && parent_window != nav_window) parent_window->NavLastChildNavWindow = nav_window; } // Restore the last focused child. // Call when we are expected to land on the Main Layer (0) after FocusWindow() static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window) { return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window; } static void NavRestoreLayer(ImGuiNavLayer layer) { ImGuiContext& g = *GImGui; g.NavLayer = layer; if (layer == 0) g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow); if (layer == 0 && g.NavWindow->NavLastIds[0] != 0) ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]); else ImGui::NavInitWindow(g.NavWindow, true); } static inline void ImGui::NavUpdateAnyRequestFlag() { ImGuiContext& g = *GImGui; g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL); if (g.NavAnyRequest) IM_ASSERT(g.NavWindow != NULL); } // This needs to be called before we submit any widget (aka in or before Begin) void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit) { ImGuiContext& g = *GImGui; IM_ASSERT(window == g.NavWindow); bool init_for_nav = false; if (!(window->Flags & ImGuiWindowFlags_NoNavInputs)) if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit) init_for_nav = true; if (init_for_nav) { SetNavID(0, g.NavLayer); g.NavInitRequest = true; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; g.NavInitResultRectRel = ImRect(); NavUpdateAnyRequestFlag(); } else { g.NavId = window->NavLastIds[0]; } } static ImVec2 ImGui::NavCalcPreferredRefPos() { ImGuiContext& g = *GImGui; if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow) { // Mouse (we need a fallback in case the mouse becomes invalid after being used) if (IsMousePosValid(&g.IO.MousePos)) return g.IO.MousePos; return g.LastValidMousePos; } else { // When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item. const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer]; ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight())); ImRect visible_rect = GetViewportRect(); return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta. } } float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode) { ImGuiContext& g = *GImGui; if (mode == ImGuiInputReadMode_Down) return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user) const float t = g.IO.NavInputsDownDuration[n]; if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input. return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f); if (t < 0.0f) return 0.0f; if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input. return (t == 0.0f) ? 1.0f : 0.0f; if (mode == ImGuiInputReadMode_Repeat) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f); if (mode == ImGuiInputReadMode_RepeatSlow) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f); if (mode == ImGuiInputReadMode_RepeatFast) return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f); return 0.0f; } ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor) { ImVec2 delta(0.0f, 0.0f); if (dir_sources & ImGuiNavDirSourceFlags_Keyboard) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode)); if (dir_sources & ImGuiNavDirSourceFlags_PadDPad) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode)); if (dir_sources & ImGuiNavDirSourceFlags_PadLStick) delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode)); if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow)) delta *= slow_factor; if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast)) delta *= fast_factor; return delta; } // Scroll to keep newly navigated item fully into view // NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated. static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect) { ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1)); //GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG] if (window_rect.Contains(item_rect)) return; ImGuiContext& g = *GImGui; if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x) { window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x; window->ScrollTargetCenterRatio.x = 0.0f; } else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x) { window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x; window->ScrollTargetCenterRatio.x = 1.0f; } if (item_rect.Min.y < window_rect.Min.y) { window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y; window->ScrollTargetCenterRatio.y = 0.0f; } else if (item_rect.Max.y >= window_rect.Max.y) { window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y; window->ScrollTargetCenterRatio.y = 1.0f; } } static void ImGui::NavUpdate() { ImGuiContext& g = *GImGui; g.IO.WantSetMousePos = false; #if 0 if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest); #endif // Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard) bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0; bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0; if (nav_gamepad_active) if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f) g.NavInputSource = ImGuiInputSource_NavGamepad; // Update Keyboard->Nav inputs mapping if (nav_keyboard_active) { #define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; } NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate ); NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input ); NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel ); NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ ); NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_); NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ ); NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ ); NAV_MAP_KEY(ImGuiKey_Tab, ImGuiNavInput_KeyTab_ ); if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f; if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f; if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu. g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f; #undef NAV_MAP_KEY } memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration)); for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++) g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f; // Process navigation init request (select first/default focus) if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove)) { // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called) IM_ASSERT(g.NavWindow); if (g.NavInitRequestFromMove) SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel); else SetNavID(g.NavInitResultId, g.NavLayer); g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel; } g.NavInitRequest = false; g.NavInitRequestFromMove = false; g.NavInitResultId = 0; g.NavJustMovedToId = 0; // Process navigation move request if (g.NavMoveRequest) NavUpdateMoveResult(); // When a forwarded move request failed, we restore the highlight that we disabled during the forward frame if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive) { IM_ASSERT(g.NavMoveRequest); if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0) g.NavDisableHighlight = false; g.NavMoveRequestForward = ImGuiNavForward_None; } // Apply application mouse position movement, after we had a chance to process move request result. if (g.NavMousePosDirty && g.NavIdIsAlive) { // Set mouse position given our knowledge of the navigated item position from last frame if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos)) { if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow) { g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos(); g.IO.WantSetMousePos = true; } } g.NavMousePosDirty = false; } g.NavIdIsAlive = false; g.NavJustTabbedId = 0; IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1); // Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0 if (g.NavWindow) NavSaveLastChildNavWindowIntoParent(g.NavWindow); if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0) g.NavWindow->NavLastChildNavWindow = NULL; // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.) NavUpdateWindowing(); // Set output flags for user application g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs); g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL); // Process NavCancel input (to close a popup, get back to parent, clear focus) if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed)) { if (g.ActiveId != 0) { if (!(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_Cancel))) ClearActiveID(); } else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow) { // Exit child window ImGuiWindow* child_window = g.NavWindow; ImGuiWindow* parent_window = g.NavWindow->ParentWindow; IM_ASSERT(child_window->ChildId != 0); FocusWindow(parent_window); SetNavID(child_window->ChildId, 0); g.NavIdIsAlive = false; if (g.NavDisableMouseHover) g.NavMousePosDirty = true; } else if (g.OpenPopupStack.Size > 0) { // Close open popup/menu if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal)) ClosePopupToLevel(g.OpenPopupStack.Size - 1, true); } else if (g.NavLayer != 0) { // Leave the "menu" layer NavRestoreLayer(ImGuiNavLayer_Main); } else { // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow))) g.NavWindow->NavLastIds[0] = 0; g.NavId = 0; } } // Process manual activation request g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0; if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) { bool activate_down = IsNavInputDown(ImGuiNavInput_Activate); bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed); if (g.ActiveId == 0 && activate_pressed) g.NavActivateId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down) g.NavActivateDownId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed) g.NavActivatePressedId = g.NavId; if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed)) g.NavInputId = g.NavId; } if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) g.NavDisableHighlight = true; if (g.NavActivateId != 0) IM_ASSERT(g.NavActivateDownId == g.NavActivateId); g.NavMoveRequest = false; // Process programmatic activation request if (g.NavNextActivateId != 0) g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId; g.NavNextActivateId = 0; // Initiate directional inputs request const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags; if (g.NavMoveRequestForward == ImGuiNavForward_None) { g.NavMoveDir = ImGuiDir_None; g.NavMoveRequestFlags = ImGuiNavMoveFlags_None; if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs)) { if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left; if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right; if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up; if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down; } g.NavMoveClipDir = g.NavMoveDir; } else { // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window) // (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function) IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None); IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued); g.NavMoveRequestForward = ImGuiNavForward_ForwardActive; } // Update PageUp/PageDown scroll float nav_scoring_rect_offset_y = 0.0f; if (nav_keyboard_active) nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags); // If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match if (g.NavMoveDir != ImGuiDir_None) { g.NavMoveRequest = true; g.NavMoveDirLast = g.NavMoveDir; } if (g.NavMoveRequest && g.NavId == 0) { g.NavInitRequest = g.NavInitRequestFromMove = true; g.NavInitResultId = 0; g.NavDisableHighlight = false; } NavUpdateAnyRequestFlag(); // Scrolling if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget) { // *Fallback* manual-scroll with Nav directional keys when window has no navigable item ImGuiWindow* window = g.NavWindow; const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported. if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest) { if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed)); if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed)); } // *Normal* Manual scroll with NavScrollXXX keys // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds. ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f); if (scroll_dir.x != 0.0f && window->ScrollbarX) { SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed)); g.NavMoveFromClampedRefRect = true; } if (scroll_dir.y != 0.0f) { SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed)); g.NavMoveFromClampedRefRect = true; } } // Reset search results g.NavMoveResultLocal.Clear(); g.NavMoveResultLocalVisibleSet.Clear(); g.NavMoveResultOther.Clear(); // When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0) { ImGuiWindow* window = g.NavWindow; ImRect window_rect_rel(window->InnerMainRect.Min - window->Pos - ImVec2(1,1), window->InnerMainRect.Max - window->Pos + ImVec2(1,1)); if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer])) { float pad = window->CalcFontSize() * 0.5f; window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel); g.NavId = 0; } g.NavMoveFromClampedRefRect = false; } // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items) ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0); g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect(); g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y); g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x); g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x; IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem(). //GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG] g.NavScoringCount = 0; #if IMGUI_DEBUG_NAV_RECTS if (g.NavWindow) { ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow); if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG] if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); } } #endif } // Apply result from previous frame navigation directional move request static void ImGui::NavUpdateMoveResult() { ImGuiContext& g = *GImGui; if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0) { // In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result) if (g.NavId != 0) { g.NavDisableHighlight = false; g.NavDisableMouseHover = true; } return; } // Select which result to use ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther; // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page. if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId) result = &g.NavMoveResultLocalVisibleSet; // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules. if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter)) result = &g.NavMoveResultOther; IM_ASSERT(g.NavWindow && result->Window); // Scroll to keep newly navigated item fully into view. if (g.NavLayer == 0) { ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos); NavScrollToBringItemIntoView(result->Window, rect_abs); // Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate() ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false); ImVec2 delta_scroll = result->Window->Scroll - next_scroll; result->RectRel.Translate(delta_scroll); // Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy). if (result->Window->Flags & ImGuiWindowFlags_ChildWindow) NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll)); } ClearActiveID(); g.NavWindow = result->Window; if (g.NavId != result->ID) { // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId) g.NavJustMovedToId = result->ID; g.NavJustMovedToMultiSelectScopeId = result->SelectScopeId; } SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel); g.NavMoveFromClampedRefRect = false; } static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags) { ImGuiContext& g = *GImGui; if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0) { ImGuiWindow* window = g.NavWindow; bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up)); bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down)); if (page_up_held != page_down_held) // If either (not both) are pressed { if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll) { // Fallback manual-scroll when window has no navigable item if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) SetWindowScrollY(window, window->Scroll.y - window->InnerMainRect.GetHeight()); else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) SetWindowScrollY(window, window->Scroll.y + window->InnerMainRect.GetHeight()); } else { const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer]; const float page_offset_y = ImMax(0.0f, window->InnerMainRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight()); float nav_scoring_rect_offset_y = 0.0f; if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true)) { nav_scoring_rect_offset_y = -page_offset_y; g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Up; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true)) { nav_scoring_rect_offset_y = +page_offset_y; g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item) g.NavMoveClipDir = ImGuiDir_Down; g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet; } return nav_scoring_rect_offset_y; } } } return 0.0f; } static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--) if (g.WindowsFocusOrder[i] == window) return i; return -1; } static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N) { ImGuiContext& g = *GImGui; for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir) if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i])) return g.WindowsFocusOrder[i]; return NULL; } static void NavUpdateWindowingHighlightWindow(int focus_change_dir) { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindowingTarget); if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal) return; const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget); ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir); if (!window_target) window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir); if (window_target) // Don't reset windowing target if there's a single window in the list g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target; g.NavWindowingToggleLayer = false; } // Windowing management mode // Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer) // Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer) static void ImGui::NavUpdateWindowing() { ImGuiContext& g = *GImGui; ImGuiWindow* apply_focus_window = NULL; bool apply_toggle_layer = false; ImGuiWindow* modal_window = GetFrontMostPopupModal(); if (modal_window != NULL) { g.NavWindowingTarget = NULL; return; } // Fade out if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL) { g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f); if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f) g.NavWindowingTargetAnim = NULL; } // Start CTRL-TAB or Square+L/R window selection bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed); bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard); if (start_windowing_with_gamepad || start_windowing_with_keyboard) if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1)) { g.NavWindowingTarget = g.NavWindowingTargetAnim = window; g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f; g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true; g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad; } // Gamepad update g.NavWindowingTimer += g.IO.DeltaTime; if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad) { // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // Select window to focus const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow); if (focus_change_dir != 0) { NavUpdateWindowingHighlightWindow(focus_change_dir); g.NavWindowingHighlightAlpha = 1.0f; } // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most) if (!IsNavInputDown(ImGuiNavInput_Menu)) { g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore. if (g.NavWindowingToggleLayer && g.NavWindow) apply_toggle_layer = true; else if (!g.NavWindowingToggleLayer) apply_focus_window = g.NavWindowingTarget; g.NavWindowingTarget = NULL; } } // Keyboard: Focus if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard) { // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f if (IsKeyPressedMap(ImGuiKey_Tab, true)) NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1); if (!g.IO.KeyCtrl) apply_focus_window = g.NavWindowingTarget; } // Keyboard: Press and Release ALT to toggle menu layer // FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB if (IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed)) g.NavWindowingToggleLayer = true; if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released)) if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev)) apply_toggle_layer = true; // Move window if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove)) { ImVec2 move_delta; if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down); if (g.NavInputSource == ImGuiInputSource_NavGamepad) move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down); if (move_delta.x != 0.0f || move_delta.y != 0.0f) { const float NAV_MOVE_SPEED = 800.0f; const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well g.NavWindowingTarget->RootWindow->Pos += move_delta * move_speed; g.NavDisableMouseHover = true; MarkIniSettingsDirty(g.NavWindowingTarget); } } // Apply final focus if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow)) { ClearActiveID(); g.NavDisableHighlight = false; g.NavDisableMouseHover = true; apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window); ClosePopupsOverWindow(apply_focus_window, false); FocusWindow(apply_focus_window); if (apply_focus_window->NavLastIds[0] == 0) NavInitWindow(apply_focus_window, false); // If the window only has a menu layer, select it directly if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu)) g.NavLayer = ImGuiNavLayer_Menu; } if (apply_focus_window) g.NavWindowingTarget = NULL; // Apply menu/layer toggle if (apply_toggle_layer && g.NavWindow) { // Move to parent menu if necessary ImGuiWindow* new_nav_window = g.NavWindow; while (new_nav_window->ParentWindow && (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0) new_nav_window = new_nav_window->ParentWindow; if (new_nav_window != g.NavWindow) { ImGuiWindow* old_nav_window = g.NavWindow; FocusWindow(new_nav_window); new_nav_window->NavLastChildNavWindow = old_nav_window; } g.NavDisableHighlight = false; g.NavDisableMouseHover = true; // When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID. const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main; NavRestoreLayer(new_nav_layer); } } // Window has already passed the IsWindowNavFocusable() static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window) { if (window->Flags & ImGuiWindowFlags_Popup) return "(Popup)"; if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0) return "(Main menu bar)"; return "(Untitled)"; } // Overlay displayed when using CTRL+TAB. Called by EndFrame(). void ImGui::NavUpdateWindowingList() { ImGuiContext& g = *GImGui; IM_ASSERT(g.NavWindowingTarget != NULL); if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY) return; if (g.NavWindowingList == NULL) g.NavWindowingList = FindWindowByName("###NavWindowingList"); SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX)); SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f); Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings); for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--) { ImGuiWindow* window = g.WindowsFocusOrder[n]; if (!IsWindowNavFocusable(window)) continue; const char* label = window->Name; if (label == FindRenderedTextEnd(label)) label = GetFallbackWindowNameForWindowingList(window); Selectable(label, g.NavWindowingTarget == window); } End(); PopStyleVar(); } //----------------------------------------------------------------------------- // [SECTION] COLUMNS // In the current version, Columns are very weak. Needs to be replaced with a more full-featured system. //----------------------------------------------------------------------------- void ImGui::NextColumn() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems || window->DC.CurrentColumns == NULL) return; ImGuiContext& g = *GImGui; ImGuiColumns* columns = window->DC.CurrentColumns; if (columns->Count == 1) { window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); IM_ASSERT(columns->Current == 0); return; } PopItemWidth(); PopClipRect(); columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); if (++columns->Current < columns->Count) { // New column (columns 1+ cancels out IndentX) window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x; window->DrawList->ChannelsSetCurrent(columns->Current + 1); } else { // New row/line window->DC.ColumnsOffset.x = 0.0f; window->DrawList->ChannelsSetCurrent(1); columns->Current = 0; columns->LineMinY = columns->LineMaxY; } window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); window->DC.CursorPos.y = columns->LineMinY; window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f); window->DC.CurrentLineTextBaseOffset = 0.0f; PushColumnClipRect(columns->Current); PushItemWidth(GetColumnWidth() * 0.65f); // FIXME-COLUMNS: Move on columns setup } int ImGui::GetColumnIndex() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0; } int ImGui::GetColumnsCount() { ImGuiWindow* window = GetCurrentWindowRead(); return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1; } static float OffsetNormToPixels(const ImGuiColumns* columns, float offset_norm) { return offset_norm * (columns->OffMaxX - columns->OffMinX); } static float PixelsToOffsetNorm(const ImGuiColumns* columns, float offset) { return offset / (columns->OffMaxX - columns->OffMinX); } static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f; static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing // window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning. ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(column_index > 0); // We are not supposed to drag column 0. IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index)); float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x; x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing); if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths)) x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing); return x; } float ImGui::GetColumnOffset(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); const float t = columns->Columns[column_index].OffsetNorm; const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t); return x_offset; } static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false) { if (column_index < 0) column_index = columns->Current; float offset_norm; if (before_resize) offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize; else offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm; return OffsetNormToPixels(columns, offset_norm); } float ImGui::GetColumnWidth(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm); } void ImGui::SetColumnOffset(int column_index, float offset) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; IM_ASSERT(column_index < columns->Columns.Size); const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1); const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f; if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow)) offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index)); columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->OffMinX); if (preserve_width) SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width)); } void ImGui::SetColumnWidth(int column_index, float width) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); if (column_index < 0) column_index = columns->Current; SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width); } void ImGui::PushColumnClipRect(int column_index) { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; if (column_index < 0) column_index = columns->Current; ImGuiColumnData* column = &columns->Columns[column_index]; PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false); } // Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns) void ImGui::PushColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; window->DrawList->ChannelsSetCurrent(0); int cmd_size = window->DrawList->CmdBuffer.Size; PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false); IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd } void ImGui::PopColumnsBackground() { ImGuiWindow* window = GetCurrentWindowRead(); ImGuiColumns* columns = window->DC.CurrentColumns; window->DrawList->ChannelsSetCurrent(columns->Current + 1); PopClipRect(); } ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id) { // We have few columns per window so for now we don't need bother much with turning this into a faster lookup. for (int n = 0; n < window->ColumnsStorage.Size; n++) if (window->ColumnsStorage[n].ID == id) return &window->ColumnsStorage[n]; window->ColumnsStorage.push_back(ImGuiColumns()); ImGuiColumns* columns = &window->ColumnsStorage.back(); columns->ID = id; return columns; } ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count) { ImGuiWindow* window = GetCurrentWindow(); // Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget. // In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer. PushID(0x11223347 + (str_id ? 0 : columns_count)); ImGuiID id = window->GetID(str_id ? str_id : "columns"); PopID(); return id; } void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported // Acquire storage for the columns set ImGuiID id = GetColumnsID(str_id, columns_count); ImGuiColumns* columns = FindOrCreateColumns(window, id); IM_ASSERT(columns->ID == id); columns->Current = 0; columns->Count = columns_count; columns->Flags = flags; window->DC.CurrentColumns = columns; // Set state for first column const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x); columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range columns->OffMaxX = ImMax(content_region_width - window->Scroll.x, columns->OffMinX + 1.0f); columns->HostCursorPosY = window->DC.CursorPos.y; columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x; columns->HostClipRect = window->ClipRect; columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Clear data if columns count changed if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1) columns->Columns.resize(0); // Initialize default widths columns->IsFirstFrame = (columns->Columns.Size == 0); if (columns->Columns.Size == 0) { columns->Columns.reserve(columns_count + 1); for (int n = 0; n < columns_count + 1; n++) { ImGuiColumnData column; column.OffsetNorm = n / (float)columns_count; columns->Columns.push_back(column); } } for (int n = 0; n < columns_count; n++) { // Compute clipping rectangle ImGuiColumnData* column = &columns->Columns[n]; float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n)); float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f); column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX); column->ClipRect.ClipWith(window->ClipRect); } if (columns->Count > 1) { window->DrawList->ChannelsSplit(1 + columns->Count); window->DrawList->ChannelsSetCurrent(1); PushColumnClipRect(0); } PushItemWidth(GetColumnWidth() * 0.65f); } void ImGui::EndColumns() { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImGuiColumns* columns = window->DC.CurrentColumns; IM_ASSERT(columns != NULL); PopItemWidth(); if (columns->Count > 1) { PopClipRect(); window->DrawList->ChannelsMerge(); } const ImGuiColumnsFlags flags = columns->Flags; columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = columns->LineMaxY; if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize)) window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent // Draw columns borders and handle resize // The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy bool is_being_resized = false; if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems) { // We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers. const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y); const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y); int dragging_column = -1; for (int n = 1; n < columns->Count; n++) { ImGuiColumnData* column = &columns->Columns[n]; float x = window->Pos.x + GetColumnOffset(n); const ImGuiID column_id = columns->ID + ImGuiID(n); const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH; const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2)); KeepAliveID(column_id); if (IsClippedEx(column_hit_rect, column_id, false)) continue; bool hovered = false, held = false; if (!(flags & ImGuiColumnsFlags_NoResize)) { ButtonBehavior(column_hit_rect, column_id, &hovered, &held); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; if (held && !(column->Flags & ImGuiColumnsFlags_NoResize)) dragging_column = n; } // Draw column const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); const float xi = (float)(int)x; window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col); } // Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame. if (dragging_column != -1) { if (!columns->IsBeingResized) for (int n = 0; n < columns->Count + 1; n++) columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm; columns->IsBeingResized = is_being_resized = true; float x = GetDraggedColumnOffset(columns, dragging_column); SetColumnOffset(dragging_column, x); } } columns->IsBeingResized = is_being_resized; window->DC.CurrentColumns = NULL; window->DC.ColumnsOffset.x = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); } // [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing] void ImGui::Columns(int columns_count, const char* id, bool border) { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(columns_count >= 1); ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder); //flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior ImGuiColumns* columns = window->DC.CurrentColumns; if (columns != NULL && columns->Count == columns_count && columns->Flags == flags) return; if (columns != NULL) EndColumns(); if (columns_count != 1) BeginColumns(id, columns_count, flags); } //----------------------------------------------------------------------------- // [SECTION] DRAG AND DROP //----------------------------------------------------------------------------- void ImGui::ClearDragDrop() { ImGuiContext& g = *GImGui; g.DragDropActive = false; g.DragDropPayload.Clear(); g.DragDropAcceptFlags = ImGuiDragDropFlags_None; g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0; g.DragDropAcceptIdCurrRectSurface = FLT_MAX; g.DragDropAcceptFrameCount = -1; g.DragDropPayloadBufHeap.clear(); memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); } // Call when current ID is active. // When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource() bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; bool source_drag_active = false; ImGuiID source_id = 0; ImGuiID source_parent_id = 0; int mouse_button = 0; if (!(flags & ImGuiDragDropFlags_SourceExtern)) { source_id = window->DC.LastItemId; if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case return false; if (g.IO.MouseDown[mouse_button] == false) return false; if (source_id == 0) { // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to: // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride. if (!(flags & ImGuiDragDropFlags_SourceAllowNullID)) { IM_ASSERT(0); return false; } // Early out if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window)) return false; // Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image() // We build a throwaway ID based on current ID stack + relative AABB of items in window. // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled. // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive. source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect); bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id); if (is_hovered && g.IO.MouseClicked[mouse_button]) { SetActiveID(source_id, window); FocusWindow(window); } if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker. g.ActiveIdAllowOverlap = is_hovered; } else { g.ActiveIdAllowOverlap = false; } if (g.ActiveId != source_id) return false; source_parent_id = window->IDStack.back(); source_drag_active = IsMouseDragging(mouse_button); } else { window = NULL; source_id = ImHashStr("#SourceExtern"); source_drag_active = true; } if (source_drag_active) { if (!g.DragDropActive) { IM_ASSERT(source_id != 0); ClearDragDrop(); ImGuiPayload& payload = g.DragDropPayload; payload.SourceId = source_id; payload.SourceParentId = source_parent_id; g.DragDropActive = true; g.DragDropSourceFlags = flags; g.DragDropMouseButton = mouse_button; } g.DragDropSourceFrameCount = g.FrameCount; g.DragDropWithinSourceOrTarget = true; if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) { // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit) // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents. BeginTooltip(); if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip)) { ImGuiWindow* tooltip_window = g.CurrentWindow; tooltip_window->SkipItems = true; tooltip_window->HiddenFramesCanSkipItems = 1; } } if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern)) window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect; return true; } return false; } void ImGui::EndDragDropSource() { ImGuiContext& g = *GImGui; IM_ASSERT(g.DragDropActive); IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?"); if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip)) EndTooltip(); // Discard the drag if have not called SetDragDropPayload() if (g.DragDropPayload.DataFrameCount == -1) ClearDragDrop(); g.DragDropWithinSourceOrTarget = false; } // Use 'cond' to choose to submit payload on drag start or every frame bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond) { ImGuiContext& g = *GImGui; ImGuiPayload& payload = g.DragDropPayload; if (cond == 0) cond = ImGuiCond_Always; IM_ASSERT(type != NULL); IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long"); IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0)); IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once); IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource() if (cond == ImGuiCond_Always || payload.DataFrameCount == -1) { // Copy payload ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType)); g.DragDropPayloadBufHeap.resize(0); if (data_size > sizeof(g.DragDropPayloadBufLocal)) { // Store in heap g.DragDropPayloadBufHeap.resize((int)data_size); payload.Data = g.DragDropPayloadBufHeap.Data; memcpy(payload.Data, data, data_size); } else if (data_size > 0) { // Store locally memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal)); payload.Data = g.DragDropPayloadBufLocal; memcpy(payload.Data, data, data_size); } else { payload.Data = NULL; } payload.DataSize = (int)data_size; } payload.DataFrameCount = g.FrameCount; return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1); } bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id) { ImGuiContext& g = *GImGui; if (!g.DragDropActive) return false; ImGuiWindow* window = g.CurrentWindow; if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) return false; IM_ASSERT(id != 0); if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId)) return false; if (window->SkipItems) return false; IM_ASSERT(g.DragDropWithinSourceOrTarget == false); g.DragDropTargetRect = bb; g.DragDropTargetId = id; g.DragDropWithinSourceOrTarget = true; return true; } // We don't use BeginDragDropTargetCustom() and duplicate its code because: // 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them. // 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can. // Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case) bool ImGui::BeginDragDropTarget() { ImGuiContext& g = *GImGui; if (!g.DragDropActive) return false; ImGuiWindow* window = g.CurrentWindow; if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect)) return false; if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow) return false; const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect; ImGuiID id = window->DC.LastItemId; if (id == 0) id = window->GetIDFromRectangle(display_rect); if (g.DragDropPayload.SourceId == id) return false; IM_ASSERT(g.DragDropWithinSourceOrTarget == false); g.DragDropTargetRect = display_rect; g.DragDropTargetId = id; g.DragDropWithinSourceOrTarget = true; return true; } bool ImGui::IsDragDropPayloadBeingAccepted() { ImGuiContext& g = *GImGui; return g.DragDropActive && g.DragDropAcceptIdPrev != 0; } const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiPayload& payload = g.DragDropPayload; IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ? IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ? if (type != NULL && !payload.IsDataType(type)) return NULL; // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints. // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function! const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId); ImRect r = g.DragDropTargetRect; float r_surface = r.GetWidth() * r.GetHeight(); if (r_surface < g.DragDropAcceptIdCurrRectSurface) { g.DragDropAcceptFlags = flags; g.DragDropAcceptIdCurr = g.DragDropTargetId; g.DragDropAcceptIdCurrRectSurface = r_surface; } // Render default drop visuals payload.Preview = was_accepted_previously; flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame) if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview) { // FIXME-DRAG: Settle on a proper default visuals for drop target. r.Expand(3.5f); bool push_clip_rect = !window->ClipRect.Contains(r); if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1)); window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f); if (push_clip_rect) window->DrawList->PopClipRect(); } g.DragDropAcceptFrameCount = g.FrameCount; payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased() if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery)) return NULL; return &payload; } const ImGuiPayload* ImGui::GetDragDropPayload() { ImGuiContext& g = *GImGui; return g.DragDropActive ? &g.DragDropPayload : NULL; } // We don't really use/need this now, but added it for the sake of consistency and because we might need it later. void ImGui::EndDragDropTarget() { ImGuiContext& g = *GImGui; IM_ASSERT(g.DragDropActive); IM_ASSERT(g.DragDropWithinSourceOrTarget); g.DragDropWithinSourceOrTarget = false; } //----------------------------------------------------------------------------- // [SECTION] LOGGING/CAPTURING //----------------------------------------------------------------------------- // All text output from the interface can be captured into tty/file/clipboard. // By default, tree nodes are automatically opened during logging. //----------------------------------------------------------------------------- // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; va_list args; va_start(args, fmt); if (g.LogFile) vfprintf(g.LogFile, fmt, args); else g.LogBuffer.appendfv(fmt, args); va_end(args); } // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (!text_end) text_end = FindRenderedTextEnd(text, text_end); const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1); if (ref_pos) g.LogLinePosY = ref_pos->y; if (log_new_line) g.LogLineFirstItem = true; const char* text_remaining = text; if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth g.LogDepthRef = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. // We don't add a trailing \n to allow a subsequent item on the same line to be captured. const char* line_start = text_remaining; const char* line_end = ImStreolRange(line_start, text_end); const bool is_first_line = (line_start == text); const bool is_last_line = (line_end == text_end); if (!is_last_line || (line_start != line_end)) { const int char_count = (int)(line_end - line_start); if (log_new_line || !is_first_line) LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start); else if (g.LogLineFirstItem) LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start); else LogText(" %.*s", char_count, line_start); g.LogLineFirstItem = false; } else if (log_new_line) { // An empty "" string at a different Y position should output a carriage return. LogText(IM_NEWLINE); break; } if (is_last_line) break; text_remaining = line_end + 1; } } // Start logging/capturing text output void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; IM_ASSERT(g.LogEnabled == false); IM_ASSERT(g.LogFile == NULL); IM_ASSERT(g.LogBuffer.empty()); g.LogEnabled = true; g.LogType = type; g.LogDepthRef = window->DC.TreeDepth; g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault); g.LogLinePosY = FLT_MAX; g.LogLineFirstItem = true; } void ImGui::LogToTTY(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; LogBegin(ImGuiLogType_TTY, auto_open_depth); g.LogFile = stdout; } // Start logging/capturing text output to given file void ImGui::LogToFile(int auto_open_depth, const char* filename) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE. // By opening the file in binary mode "ab" we have consistent output everywhere. if (!filename) filename = g.IO.LogFilename; if (!filename || !filename[0]) return; FILE* f = ImFileOpen(filename, "ab"); if (f == NULL) { IM_ASSERT(0); return; } LogBegin(ImGuiLogType_File, auto_open_depth); g.LogFile = f; } // Start logging/capturing text output to clipboard void ImGui::LogToClipboard(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; LogBegin(ImGuiLogType_Clipboard, auto_open_depth); } void ImGui::LogToBuffer(int auto_open_depth) { ImGuiContext& g = *GImGui; if (g.LogEnabled) return; LogBegin(ImGuiLogType_Buffer, auto_open_depth); } void ImGui::LogFinish() { ImGuiContext& g = *GImGui; if (!g.LogEnabled) return; LogText(IM_NEWLINE); switch (g.LogType) { case ImGuiLogType_TTY: fflush(g.LogFile); break; case ImGuiLogType_File: fclose(g.LogFile); break; case ImGuiLogType_Buffer: break; case ImGuiLogType_Clipboard: if (!g.LogBuffer.empty()) SetClipboardText(g.LogBuffer.begin()); break; case ImGuiLogType_None: IM_ASSERT(0); break; } g.LogEnabled = false; g.LogType = ImGuiLogType_None; g.LogFile = NULL; g.LogBuffer.clear(); } // Helper to display logging buttons // FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!) void ImGui::LogButtons() { ImGuiContext& g = *GImGui; PushID("LogButtons"); const bool log_to_tty = Button("Log To TTY"); SameLine(); const bool log_to_file = Button("Log To File"); SameLine(); const bool log_to_clipboard = Button("Log To Clipboard"); SameLine(); PushAllowKeyboardFocus(false); SetNextItemWidth(80.0f); SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL); PopAllowKeyboardFocus(); PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) LogToTTY(); if (log_to_file) LogToFile(); if (log_to_clipboard) LogToClipboard(); } //----------------------------------------------------------------------------- // [SECTION] SETTINGS //----------------------------------------------------------------------------- void ImGui::MarkIniSettingsDirty() { ImGuiContext& g = *GImGui; if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } void ImGui::MarkIniSettingsDirty(ImGuiWindow* window) { ImGuiContext& g = *GImGui; if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name) { ImGuiContext& g = *GImGui; g.SettingsWindows.push_back(ImGuiWindowSettings()); ImGuiWindowSettings* settings = &g.SettingsWindows.back(); settings->Name = ImStrdup(name); settings->ID = ImHashStr(name); return settings; } ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id) { ImGuiContext& g = *GImGui; for (int i = 0; i != g.SettingsWindows.Size; i++) if (g.SettingsWindows[i].ID == id) return &g.SettingsWindows[i]; return NULL; } ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name) { if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name))) return settings; return CreateNewWindowSettings(name); } void ImGui::LoadIniSettingsFromDisk(const char* ini_filename) { size_t file_data_size = 0; char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size); if (!file_data) return; LoadIniSettingsFromMemory(file_data, (size_t)file_data_size); IM_FREE(file_data); } ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name) { ImGuiContext& g = *GImGui; const ImGuiID type_hash = ImHashStr(type_name); for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) if (g.SettingsHandlers[handler_n].TypeHash == type_hash) return &g.SettingsHandlers[handler_n]; return NULL; } // Zero-tolerance, no error reporting, cheap .ini parsing void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size) { ImGuiContext& g = *GImGui; IM_ASSERT(g.Initialized); IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0); // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter). // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy.. if (ini_size == 0) ini_size = strlen(ini_data); char* buf = (char*)IM_ALLOC(ini_size + 1); char* buf_end = buf + ini_size; memcpy(buf, ini_data, ini_size); buf[ini_size] = 0; void* entry_data = NULL; ImGuiSettingsHandler* entry_handler = NULL; char* line_end = NULL; for (char* line = buf; line < buf_end; line = line_end + 1) { // Skip new lines markers, then find end of the line while (*line == '\n' || *line == '\r') line++; line_end = line; while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++; line_end[0] = 0; if (line[0] == ';') continue; if (line[0] == '[' && line_end > line && line_end[-1] == ']') { // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code. line_end[-1] = 0; const char* name_end = line_end - 1; const char* type_start = line + 1; char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']'); const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL; if (!type_end || !name_start) { name_start = type_start; // Import legacy entries that have no type type_start = "Window"; } else { *type_end = 0; // Overwrite first ']' name_start++; // Skip second '[' } entry_handler = FindSettingsHandler(type_start); entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL; } else if (entry_handler != NULL && entry_data != NULL) { // Let type handler parse the line entry_handler->ReadLineFn(&g, entry_handler, entry_data, line); } } IM_FREE(buf); g.SettingsLoaded = true; } void ImGui::SaveIniSettingsToDisk(const char* ini_filename) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; if (!ini_filename) return; size_t ini_data_size = 0; const char* ini_data = SaveIniSettingsToMemory(&ini_data_size); FILE* f = ImFileOpen(ini_filename, "wt"); if (!f) return; fwrite(ini_data, sizeof(char), ini_data_size, f); fclose(f); } // Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer const char* ImGui::SaveIniSettingsToMemory(size_t* out_size) { ImGuiContext& g = *GImGui; g.SettingsDirtyTimer = 0.0f; g.SettingsIniData.Buf.resize(0); g.SettingsIniData.Buf.push_back(0); for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++) { ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n]; handler->WriteAllFn(&g, handler, &g.SettingsIniData); } if (out_size) *out_size = (size_t)g.SettingsIniData.size(); return g.SettingsIniData.c_str(); } static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name) { ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name)); if (!settings) settings = ImGui::CreateNewWindowSettings(name); return (void*)settings; } static void SettingsHandlerWindow_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void* entry, const char* line) { ImGuiContext& g = *ctx; ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry; float x, y; int i; if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { // Gather data from windows that were active during this session // (if a window wasn't opened in this session we preserve its settings) ImGuiContext& g = *ctx; for (int i = 0; i != g.Windows.Size; i++) { ImGuiWindow* window = g.Windows[i]; if (window->Flags & ImGuiWindowFlags_NoSavedSettings) continue; ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID); if (!settings) { settings = ImGui::CreateNewWindowSettings(window->Name); window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings); } IM_ASSERT(settings->ID == window->ID); settings->Pos = window->Pos; settings->Size = window->SizeFull; settings->Collapsed = window->Collapsed; } // Write to text buffer buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve for (int i = 0; i != g.SettingsWindows.Size; i++) { const ImGuiWindowSettings* settings = &g.SettingsWindows[i]; if (settings->Pos.x == FLT_MAX) continue; const char* name = settings->Name; if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() name = p; buf->appendf("[%s][%s]\n", handler->TypeName, name); buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); buf->appendf("Collapsed=%d\n", settings->Collapsed); buf->appendf("\n"); } } //----------------------------------------------------------------------------- // [SECTION] VIEWPORTS, PLATFORM WINDOWS //----------------------------------------------------------------------------- // (this section is filled in the 'docking' branch) //----------------------------------------------------------------------------- // [SECTION] DOCKING //----------------------------------------------------------------------------- // (this section is filled in the 'docking' branch) //----------------------------------------------------------------------------- // [SECTION] PLATFORM DEPENDENT HELPERS //----------------------------------------------------------------------------- #if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef __MINGW32__ #include <Windows.h> #else #include <windows.h> #endif #endif // Win32 API clipboard implementation #if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) #ifdef _MSC_VER #pragma comment(lib, "user32") #endif static const char* GetClipboardTextFn_DefaultImpl(void*) { static ImVector<char> buf_local; buf_local.clear(); if (!::OpenClipboard(NULL)) return NULL; HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) { ::CloseClipboard(); return NULL; } if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle)) { int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; buf_local.resize(buf_len); ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL); } ::GlobalUnlock(wbuf_handle); ::CloseClipboard(); return buf_local.Data; } static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { if (!::OpenClipboard(NULL)) return; const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); if (wbuf_handle == NULL) { ::CloseClipboard(); return; } ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle); ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); ::GlobalUnlock(wbuf_handle); ::EmptyClipboard(); if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL) ::GlobalFree(wbuf_handle); ::CloseClipboard(); } #else // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static const char* GetClipboardTextFn_DefaultImpl(void*) { ImGuiContext& g = *GImGui; return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin(); } // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static void SetClipboardTextFn_DefaultImpl(void*, const char* text) { ImGuiContext& g = *GImGui; g.PrivateClipboard.clear(); const char* text_end = text + strlen(text); g.PrivateClipboard.resize((int)(text_end - text) + 1); memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text)); g.PrivateClipboard[(int)(text_end - text)] = 0; } #endif // Win32 API IME support (for Asian languages, etc.) #if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) #include <imm.h> #ifdef _MSC_VER #pragma comment(lib, "imm32") #endif static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { // Notify OS Input Method Editor of text input position if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) if (HIMC himc = ::ImmGetContext(hwnd)) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = x; cf.ptCurrentPos.y = y; cf.dwStyle = CFS_FORCE_POSITION; ::ImmSetCompositionWindow(himc, &cf); ::ImmReleaseContext(hwnd, himc); } } #else static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {} #endif //----------------------------------------------------------------------------- // [SECTION] METRICS/DEBUG WINDOW //----------------------------------------------------------------------------- void ImGui::ShowMetricsWindow(bool* p_open) { if (!ImGui::Begin("ImGui Metrics", p_open)) { ImGui::End(); return; } enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerMainRect, RT_InnerClipRect, RT_ContentsRegionRect, RT_ContentsFullRect }; static bool show_windows_begin_order = false; static bool show_windows_rects = false; static int show_windows_rect_type = RT_ContentsRegionRect; static bool show_drawcmd_clip_rects = true; ImGuiIO& io = ImGui::GetIO(); ImGui::Text("Dear ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate); ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3); ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows); ImGui::Text("%d active allocations", io.MetricsActiveAllocations); ImGui::Separator(); struct Funcs { static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label) { bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) if (node_open) ImGui::TreePop(); return; } ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list if (window && IsItemHovered()) fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255)); if (!node_open) return; int elem_offset = 0; for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++) { if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0) continue; if (pcmd->UserCallback) { ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData); continue; } ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w); if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered()) { ImRect clip_rect = pcmd->ClipRect; ImRect vtxs_rect; for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++) vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos); clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255)); vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255)); } if (!pcmd_node_open) continue; // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted. ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible. while (clipper.Step()) for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++) { char buf[300]; char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf); ImVec2 triangles_pos[3]; for (int n = 0; n < 3; n++, idx_i++) { int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i; ImDrawVert& v = draw_list->VtxBuffer[vtx_i]; triangles_pos[n] = v.pos; buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "idx" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col); } ImGui::Selectable(buf, false); if (fg_draw_list && ImGui::IsItemHovered()) { ImDrawListFlags backup_flags = fg_draw_list->Flags; fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles. fg_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f); fg_draw_list->Flags = backup_flags; } } ImGui::TreePop(); } ImGui::TreePop(); } static void NodeColumns(const ImGuiColumns* columns) { if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags)) return; ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX); for (int column_n = 0; column_n < columns->Columns.Size; column_n++) ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm)); ImGui::TreePop(); } static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label) { if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size)) return; for (int i = 0; i < windows.Size; i++) Funcs::NodeWindow(windows[i], "Window"); ImGui::TreePop(); } static void NodeWindow(ImGuiWindow* window, const char* label) { if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window)) return; ImGuiWindowFlags flags = window->Flags; NodeDrawList(window, window->DrawList, "DrawList"); ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y); ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags, (flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "", (flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "", (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : ""); ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window)); ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1); ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems); ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask); ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL"); if (!window->NavRectRel[0].IsInverted()) ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y); else ImGui::BulletText("NavRectRel[0]: <None>"); if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow"); if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size)) { for (int n = 0; n < window->ColumnsStorage.Size; n++) NodeColumns(&window->ColumnsStorage[n]); ImGui::TreePop(); } ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair)); ImGui::TreePop(); } static void NodeTabBar(ImGuiTabBar* tab_bar) { // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings. char buf[256]; char* p = buf; const char* buf_end = buf + IM_ARRAYSIZE(buf); ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : ""); if (ImGui::TreeNode(tab_bar, "%s", buf)) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; ImGui::PushID(tab); if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2); if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine(); ImGui::Text("%02d%c Tab 0x%08X", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID); ImGui::PopID(); } ImGui::TreePop(); } } }; // Access private state, we are going to display the draw lists from last frame ImGuiContext& g = *GImGui; Funcs::NodeWindows(g.Windows, "Windows"); if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size)) { for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++) Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList"); ImGui::TreePop(); } if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size)) { for (int i = 0; i < g.OpenPopupStack.Size; i++) { ImGuiWindow* window = g.OpenPopupStack[i].Window; ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : ""); } ImGui::TreePop(); } if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size)) { for (int n = 0; n < g.TabBars.Data.Size; n++) Funcs::NodeTabBar(g.TabBars.GetByIndex(n)); ImGui::TreePop(); } if (ImGui::TreeNode("Internal state")) { const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT); ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL"); ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL"); ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]); ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL"); ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL"); ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL"); ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer); ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]); ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible); ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId); ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover); ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL"); ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize); ImGui::TreePop(); } if (ImGui::TreeNode("Tools")) { ImGui::Checkbox("Show windows begin order", &show_windows_begin_order); ImGui::Checkbox("Show windows rectangles", &show_windows_rects); ImGui::SameLine(); ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12); show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerMainRect\0" "InnerClipRect\0" "ContentsRegionRect\0"); ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects); ImGui::TreePop(); } if (show_windows_rects || show_windows_begin_order) { for (int n = 0; n < g.Windows.Size; n++) { ImGuiWindow* window = g.Windows[n]; if (!window->WasActive) continue; ImDrawList* draw_list = GetForegroundDrawList(window); if (show_windows_rects) { ImRect r; if (show_windows_rect_type == RT_OuterRect) { r = window->Rect(); } else if (show_windows_rect_type == RT_OuterRectClipped) { r = window->OuterRectClipped; } else if (show_windows_rect_type == RT_InnerMainRect) { r = window->InnerMainRect; } else if (show_windows_rect_type == RT_InnerClipRect) { r = window->InnerClipRect; } else if (show_windows_rect_type == RT_ContentsRegionRect) { r = window->ContentsRegionRect; } draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255)); } if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow)) { char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext); float font_size = ImGui::GetFontSize(); draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255)); draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf); } } } ImGui::End(); } //----------------------------------------------------------------------------- // Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed. // Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL #include "imgui_user.inl" #endif //-----------------------------------------------------------------------------
sherief/ImGuizmo
example/imgui.cpp
C++
mit
483,056
using System.Runtime.InteropServices; using System; using OpenGL; namespace Rox.Geom { [StructLayout(LayoutKind.Sequential, Pack = 2)] public struct Quad { public UvVertex V0 { get; private set; } public UvVertex V1 { get; private set; } public UvVertex V2 { get; private set; } public UvVertex V3 { get; private set; } // TODO: Optimize out if necessary public Vector3 Normal { get; private set; } public Quad(Vector3 normal, UvVertex v0, UvVertex v1, UvVertex v2, UvVertex v3) { Normal = normal; V0 = v0; V1 = v1; V2 = v2; V3 = v3; } public UvVertex At(int index) { switch(index) { case 0: return V0; case 1: return V1; case 2: return V2; case 3: return V3; default: throw new IndexOutOfRangeException($"Index: {index} is out of range."); } } } }
mbolt35/Rox
Rox/Rox/Geom/Quad.cs
C#
mit
1,017
# typed: strict # frozen_string_literal: true module Ffprober module Parsers class FileParser extend T::Sig sig do params( file_to_parse: String, exec: T.any(Ffprober::Ffmpeg::Exec, T.untyped) ).void end def initialize(file_to_parse, exec = Ffprober::Ffmpeg::Exec.new) raise ArgumentError, "File not found #{file_to_parse}" unless ::File.exist?(file_to_parse) @file_to_parse = file_to_parse @exec = exec end sig { returns(Ffprober::Parsers::JsonParser) } def load JsonParser.new(@exec.json_output(@file_to_parse)) end end end end
beanieboi/ffprober
lib/ffprober/parsers/file.rb
Ruby
mit
662
"""Molt Web API with Interface.""" import re import redis import docker import subprocess import os import shlex import requests import sys import argparse from flask import Flask, Response, render_template, abort, request from molt import Molt, MoltError app = Flask(__name__) # コマンドライン引数のパース parser = argparse.ArgumentParser() parser.add_argument('-c', '--config', help='config file path') args = parser.parse_args() if args.config: cfg_file = args.config else: cfg_file = 'config/molt_app.cfg' if not os.path.exists(cfg_file): app.logger.error("{} が存在しません".format(cfg_file)) sys.exit(1) app.config.from_pyfile(cfg_file, silent=True) @app.route('/<virtual_host>', strict_slashes=False) def index(virtual_host): """Moltの実行をプレビューするページ.""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) vhost = {'rev': rev, 'repo': repo, 'user': user, 'full': virtual_host} redirect_url = '//{}.{}/'.format(virtual_host, app.config['BASE_DOMAIN']) return render_template('index.html', vhost=vhost, redirect_url=redirect_url) @app.route('/molt/<virtual_host>', methods=['GET'], strict_slashes=False) def molt(virtual_host): """Moltの実行をストリーミングする(Server-Sent Eventを使ったAPI).""" try: rev, repo, user = virtual_host_parse(virtual_host) except Exception: abort(404) m = Molt(rev, repo, user, app.config['BASE_DOMAIN'], app.config['GITHUB_USER'], app.config['GITHUB_TOKEN']) r = redis.StrictRedis(host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT']) def generate(m, r): """Dockerイメージ立ち上げ(ストリーミングするための関数). git clone から docker-compose upまでの一連の処理のSTDIOの送信と、Dockerイメージ の情報取得・設定をする """ # コマンド群の実行 try: for row in m.molt(): row = row.decode() data = row.split('\r')[-1] # CRのみの行は保留されるので取り除く yield event_stream_parser(data) except MoltError as e: yield event_stream_parser(e, event='failure') except Exception: yield event_stream_parser('Molt内部でエラーが発生しました。終了します...', event='failure') else: # RedisへIPアドレスとバーチャルホストの対応を書き込む r.hset('mirror-store', virtual_host, m.get_container_ip()) yield event_stream_parser('', event='success') return Response(generate(m, r), mimetype='text/event-stream') @app.route('/favicon.ico') def favicon(): """favicon.ico.""" abort(404) @app.template_filter('base_domain') def base_domain_filter(path): """Staticファイルを呼び出す際のドメインを指定する.""" return '//' + app.config['BASE_DOMAIN'] + ':' + str(app.config['PORT']) + \ '/' + path @app.route("/hook", methods=['POST']) def hook(): event = request.headers["X-GitHub-Event"] req = request.json if event != "pull_request": return "ok", 200 elif req["action"] not in {"opened", "synchronize"}: return "ok", 200 pr = req["pull_request"] pr_url = pr["comments_url"] pr_sha = pr["head"]["sha"][:7] pr_reponame = pr["head"]["repo"]["name"] pr_owner = pr["head"]["repo"]["owner"]["login"] payload = { "event": "COMMENT", "body": "Launched the preview environment!\nhttp://{}.{}.{}.{}\ ".format(pr_sha, pr_reponame, pr_owner, app.config["BASE_DOMAIN"]), } headers = { "Accept": "application/vnd.github.v3+json", "Content-Type": "application/json", "Authorization": "token {}".format(app.config["GITHUB_TOKEN"]), } requests.post( pr_url, json=payload, headers=headers, ) return "ok", 200 def virtual_host_parse(virtual_host): """Virtual_hostの文字列を 'rev', 'repo', 'user' に分割する. e.g.(1) "host.repo.sitory.user" => "host", "repo.sitory", "user" e.g.(2) "host.repository.user" => "host", "repository", "user" """ p = re.compile(r'(?P<rev>^.+?)\.(?P<repo>.+)\.(?P<user>.+)$') m = p.search(virtual_host) return m.group('rev'), m.group('repo'), m.group('user') def event_stream_parser(data, event=None, id=None, retry=None): """Server-Sent Event 形式へのパーサ.""" event_stream = '' if event: event_stream += 'event: {}\n'.format(event) event_stream += 'data: {}\n'.format(data) if id: event_stream += 'id: {}\n'.format(id) if retry: event_stream += 'retry: {}\n'.format(id) event_stream += '\n' return event_stream if __name__ == '__main__': # RSA鍵の生成 user = os.getenv('USER') ssh_key_path = os.path.expanduser("~")+"/.ssh/molt_deploy_key" if not os.path.exists(ssh_key_path): command = 'ssh-keygen -t rsa -N "" -f {}'.format(ssh_key_path) command = shlex.split(command) subprocess.Popen(command) # Dockerネットワークの作成 clinet = docker.from_env() networks = clinet.networks.list() if 'molt-network' not in [network.name for network in networks]: command = 'docker network create --subnet=172.31.255.0/24 \ --ip-range=172.31.255.0/24 --gateway=172.31.255.254 \ -o "com.docker.network.bridge.host_binding_ipv4"="0.0.0.0" \ molt-network' command = shlex.split(command) subprocess.Popen(command) app.run(host=app.config['HOST'], port=app.config['PORT'])
swkoubou/molt
molt_app.py
Python
mit
5,850
package com.sdl.selenium.extjs6.form; import com.sdl.selenium.InputData; import com.sdl.selenium.TestBase; import com.sdl.selenium.extjs6.panel.Panel; import com.sdl.selenium.web.SearchType; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; public class RadioGroupIntegrationTest extends TestBase { private Panel radioGroupPanel = new Panel(null, "Radio Group Example").setClasses("x-panel-default-framed"); private RadioGroup radioGroup = new RadioGroup(radioGroupPanel, "Auto Layout:", SearchType.DEEP_CHILD_NODE_OR_SELF); @BeforeClass public void startTests() { driver.get(InputData.EXTJS_EXAMPLE_URL + "#form-radiogroup"); driver.switchTo().frame("examples-iframe"); radioGroup.setVersion(version); radioGroup.ready(Duration.ofSeconds(20)); } @Test public void selectRadioGroup() { assertThat(radioGroup.selectByLabel("Item 2"), is(true)); assertThat(radioGroup.isSelectedByLabel("Item 2"), is(true)); assertThat(radioGroup.selectByLabel("5", SearchType.CONTAINS), is(true)); assertThat(radioGroup.isSelectedByLabel("Item 5"), is(true)); assertThat(radioGroup.selectByLabel("Item 4"), is(true)); assertThat(radioGroup.isSelectedByLabel("Item 4"), is(true)); assertThat(radioGroup.selectByLabel("Item 1"), is(true)); assertThat(radioGroup.isSelectedByLabel("Item 1"), is(true)); } @Test public void getLabelNameRadioGroup() { assertThat(radioGroup.getLabelName("1"), equalTo("Item 1")); assertThat(radioGroup.getLabelName("1"), equalTo("Item 1")); } }
sdl/Testy
src/test/functional/java/com/sdl/selenium/extjs6/form/RadioGroupIntegrationTest.java
Java
mit
1,813
require "rails_helper" RSpec.describe UserMailer, type: :mailer do # describe "follow_up_email" do # let(:mail) { UserMailer.follow_up_email } # # it "renders the headers" do # expect(mail.subject).to eq("Follow up email") # expect(mail.to).to eq(["to@example.org"]) # expect(mail.from).to eq(["from@example.com"]) # end # # it "renders the body" do # expect(mail.body.encoded).to match("Hi") # end # end end
kirbrown/movies_sherlock_rails
spec/mailers/user_mailer_spec.rb
Ruby
mit
463
// server.js // BASE SETUP // ============================================================================= // call the packages we need var express = require('express'); // call express var app = express(); // define our app using express var bodyParser = require('body-parser'); var json2csv = require('json2csv'); var fs = require('fs'); var path = require('path'); // var fields = ['car', 'price', 'color']; // var myCars = [ // { // "car": "Audi", // "price": 40000, // "color": "blue" // }, { // "car": "BMW", // "price": 35000, // "color": "black" // }, { // "car": "Porsche", // "price": 60000, // "color": "green" // } // ]; // json2csv({ data: myCars, fields: fields }, function(err, csv) { // if (err) console.log(err); // fs.writeFile('file.csv', csv, function(err) { // if (err) throw err; // console.log('file saved'); // }); // }); var mongoose = require('mongoose'); mongoose.connect('mongodb://192.168.10.62:27000/tempTW'); // connect to our database var Bear = require('./models/bear'); var CFSOrg = require('./models/CFSOrganization'); // configure app to use bodyParser() // this will let us get the data from a POST app.use(bodyParser.urlencoded({extended:true,limit:1024*1024*20,type:'application/x-www-form-urlencoding'})); app.use(bodyParser.json({limit:1024*1024*20, type:'application/json'})); var port = process.env.PORT || 9001; // set our port // ROUTES FOR OUR API // ============================================================================= var router = express.Router(); // get an instance of the express Router // Add headers app.use(function (req, res, next) { // Website you wish to allow to connect res.setHeader('Access-Control-Allow-Origin', 'http://localhost:9999'); // Request methods you wish to allow res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); // Request headers you wish to allow res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); // Set to true if you need the website to include cookies in the requests sent // to the API (e.g. in case you use sessions) res.setHeader('Access-Control-Allow-Credentials', true); // Pass to next layer of middleware next(); }); // middleware to use for all requests router.use(function(req, res, next) { // do logging console.log('Something is happening.'); next(); // make sure we go to the next routes and don't stop here }); // test route to make sure everything is working (accessed at GET http://localhost:8080/api) router.get('/', function(req, res) { res.json({ message: 'hooray! welcome to our api!' }); }); app.use('/downloadFile', express.static(path.join(__dirname, 'exports'))); // more routes for our API will happen here // on routes that end in /bears // ---------------------------------------------------- router.route('/bears') // create a bear (accessed at POST http://localhost:8080/api/bears) .post(function(req, res) { var bear = new Bear(); // create a new instance of the Bear model bear.name = req.body.name; // set the bears name (comes from the request) bear.shortName = req.body.shortName; bear.subName = req.body.subName; bear.city = req.body.city; bear.state = req.body.state; bear.country = req.body.country; // save the bear and check for errors bear.save(function(err) { if (err) res.send(err); res.json({ message: 'Bear created!' }); }); }) // get all the bears (accessed at GET http://localhost:8080/api/bears) .get(function(req, res) { Bear.find(function(err, result) { if (err) res.send(err); res.json(result); }); }); router.route('/export') .post(function(req, res) { debugger; console.log(req); var fields = [ '_id', 'name', 'shortName', 'subName', 'city', 'state', 'country' ]; var myBears = []; myBears = req.body; json2csv({ data: myBears, fields: fields }, function(err, csv) { if (err) console.log(err); var exportDir = '/exports' var fileName = 'myBears_file_' + new Date().getTime() + '.csv'; fs.writeFile(path.join(__dirname, exportDir, fileName), csv, function(err) { if (err) throw err; console.log('file saved as : ' + fileName); res.send({csvFile: fileName}); // res.send(path.join(__dirname, exportDir, fileName)); var filePath = path.join(__dirname, exportDir, fileName); var readStream = fs.createReadStream(filePath); readStream.pipe(res); // res.sendFile(exportDir, fileName); }); }); }); // get all the bears (accessed at GET http://localhost:8080/api/bears) // .get(function(req, res) { // var fields = ['name', 'shortName', 'subName']; // var myBears = []; // myBears = req.body; // json2csv({ data: myBears, fields: fields }, function(err, csv) { // if (err) console.log(err); // var fileName = 'myBears_file_' + new Date().getTime() + '_.csv'; // fs.writeFile(fileName, csv, function(err) { // if (err) throw err; // console.log('file saved as : ' + filename); // res.send({csvFile: filename}); // }); // }); // // res.sendFile('myBears_file.csv'); // }); router.route('/CFSOrganizations') .get(function(req, res) { // CFSOrg.find(function(err, result) { // if (err) // res.send(err); // res.json(result); // }); CFSOrg.find(function(err, records) { if (err) { handleError(res, err.message, "Failed to get contacts."); } else { res.status(200).json(records); } }); }); // REGISTER OUR ROUTES ------------------------------- // all of our routes will be prefixed with /api app.use('/api', router); // START THE SERVER // ============================================================================= app.listen(port); console.log('Magic happens on port ' + port);
vilaskumkar/test-jenkins
API/server.js
JavaScript
mit
6,479
<?php /* * This file is part of the PHPExifTool package. * * (c) Alchemy <support@alchemy.fr> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Pentax; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class DigitalFilter01 extends AbstractTag { protected $Id = 5; protected $Name = 'DigitalFilter01'; protected $FullName = 'Pentax::FilterInfo'; protected $GroupName = 'Pentax'; protected $g0 = 'MakerNotes'; protected $g1 = 'Pentax'; protected $g2 = 'Image'; protected $Type = 'undef'; protected $Writable = true; protected $Description = 'Digital Filter 01'; protected $flag_Permanent = true; protected $MaxLength = 17; protected $Values = array( 0 => array( 'Id' => 0, 'Label' => 'Off', ), 1 => array( 'Id' => 1, 'Label' => 'Base Parameter Adjust', ), 2 => array( 'Id' => 2, 'Label' => 'Soft Focus', ), 3 => array( 'Id' => 3, 'Label' => 'High Contrast', ), 4 => array( 'Id' => 4, 'Label' => 'Color Filter', ), 5 => array( 'Id' => 5, 'Label' => 'Extract Color', ), 6 => array( 'Id' => 6, 'Label' => 'Monochrome', ), 7 => array( 'Id' => 7, 'Label' => 'Slim', ), 9 => array( 'Id' => 9, 'Label' => 'Fisheye', ), 10 => array( 'Id' => 10, 'Label' => 'Toy Camera', ), 11 => array( 'Id' => 11, 'Label' => 'Retro', ), 12 => array( 'Id' => 12, 'Label' => 'Pastel', ), 13 => array( 'Id' => 13, 'Label' => 'Water Color', ), 14 => array( 'Id' => 14, 'Label' => 'HDR', ), 16 => array( 'Id' => 16, 'Label' => 'Miniature', ), 17 => array( 'Id' => 17, 'Label' => 'Starburst', ), 18 => array( 'Id' => 18, 'Label' => 'Posterization', ), 19 => array( 'Id' => 19, 'Label' => 'Sketch Filter', ), 20 => array( 'Id' => 20, 'Label' => 'Shading', ), 21 => array( 'Id' => 21, 'Label' => 'Invert Color', ), 23 => array( 'Id' => 23, 'Label' => 'Tone Expansion', ), 254 => array( 'Id' => 254, 'Label' => 'Custom Filter', ), ); }
bburnichon/PHPExiftool
lib/PHPExiftool/Driver/Tag/Pentax/DigitalFilter01.php
PHP
mit
2,944
/** * @fileoverview * Base types and classes used by chem editor. * @author Partridge Jiang */ /* * requires /lan/classes.js * requires /chemDoc/issueCheckers/kekule.issueCheckers.js * requires /widgets/operation/kekule.operations.js * requires /render/kekule.render.base.js * requires /render/kekule.render.boundInfoRecorder.js * requires /html/xbrowsers/kekule.x.js * requires /widgets/kekule.widget.base.js * requires /widgets/chem/kekule.chemWidget.chemObjDisplayers.js * requires /widgets/chem/editor/kekule.chemEditor.extensions.js * requires /widgets/chem/editor/kekule.chemEditor.editorUtils.js * requires /widgets/chem/editor/kekule.chemEditor.configs.js * requires /widgets/chem/editor/kekule.chemEditor.operations.js * requires /widgets/chem/editor/kekule.chemEditor.modifications.js */ (function(){ "use strict"; var OU = Kekule.ObjUtils; var AU = Kekule.ArrayUtils; var EU = Kekule.HtmlElementUtils; var CU = Kekule.CoordUtils; var CNS = Kekule.Widget.HtmlClassNames; var CCNS = Kekule.ChemWidget.HtmlClassNames; /** @ignore */ Kekule.ChemWidget.HtmlClassNames = Object.extend(Kekule.ChemWidget.HtmlClassNames, { EDITOR: 'K-Chem-Editor', EDITOR_CLIENT: 'K-Chem-Editor-Client', EDITOR_UIEVENT_RECEIVER: 'K-Chem-Editor-UiEvent-Receiver', EDITOR2D: 'K-Chem-Editor2D', EDITOR3D: 'K-Chem-Editor3D' }); /** * Namespace for chem editor. * @namespace */ Kekule.ChemWidget.Editor = {}; /** * Alias to {@link Kekule.ChemWidget.Editor}. * @namespace */ Kekule.Editor = Kekule.ChemWidget.Editor; /** * In editor, there exist three types of coord: one based on object system (inner coord), * another one based on context of editor (outer coord, context coord), * and the third based on screen. * This enum is an alias of Kekule.Render.CoordSystem * @class */ Kekule.Editor.CoordSys = Kekule.Render.CoordSystem; /** * Enumeration of regions in/out box. * @enum * @ignore */ Kekule.Editor.BoxRegion = { OUTSIDE: 0, CORNER_TL: 1, CORNER_TR: 2, CORNER_BL: 3, CORNER_BR: 4, EDGE_TOP: 11, EDGE_LEFT: 12, EDGE_BOTTOM: 13, EDGE_RIGHT: 14, INSIDE: 20 }; /** * Enumeration of mode in selecting object in editor. * @enum * @ignore */ Kekule.Editor.SelectMode = { /** Draw a box in editor when selecting, select all object inside a box. **/ RECT: 0, /** Draw a curve in editor when selecting, select all object inside this curve polygon. **/ POLYGON: 1, /** Draw a curve in editor when selecting, select all object intersecting this curve. **/ POLYLINE: 2, /** Click on a child object to select the whole standalone ancestor. **/ ANCESTOR: 10 }; // add some global options Kekule.globalOptions.add('chemWidget.editor', { 'enableIssueCheck': true, 'enableCreateNewDoc': true, 'enableOperHistory': true, 'enableOperContext': true, 'initOnNewDoc': true, 'enableSelect': true, 'enableMove': true, 'enableResize': true, 'enableAspectRatioLockedResize': true, 'enableRotate': true, 'enableGesture': true }); Kekule.globalOptions.add('chemWidget.editor.issueChecker', { 'enableAutoIssueCheck': true, 'enableAutoScrollToActiveIssue': true, 'enableIssueMarkerHint': true, 'durationLimit': 50 // issue check must be finished in 50ms, avoid blocking the UI }); /** * A base chem editor. * @class * @augments Kekule.ChemWidget.ChemObjDisplayer * @param {Variant} parentOrElementOrDocument * @param {Kekule.ChemObject} chemObj initially loaded chemObj. * @param {Int} renderType Display in 2D or 3D. Value from {@link Kekule.Render.RendererType}. * @param {Kekule.Editor.BaseEditorConfigs} editorConfigs Configuration of this editor. * * @property {Kekule.Editor.BaseEditorConfigs} editorConfigs Configuration of this editor. * @property {Bool} enableCreateNewDoc Whether create new object in editor is allowed. * @property {Bool} initOnNewDoc Whether create a new doc when editor instance is initialized. * Note, the new doc will only be created when property enableCreateNewDoc is true. * @property {Bool} enableOperHistory Whether undo/redo is enabled. * @property {Kekule.OperationHistory} operHistory History of operations. Used to enable undo/redo function. * @property {Int} renderType Display in 2D or 3D. Value from {@link Kekule.Render.RendererType}. * @property {Kekule.ChemObject} chemObj The root object in editor. * @property {Bool} enableIssueCheck Whether issue check is available in editor. * @property {Array} issueCheckerIds Issue checker class IDs used in editor. * @property {Bool} enableAutoIssueCheck Whether the issue checking is automatically executed when objects changing in editor. * @property {Array} issueCheckResults Array of {@link Kekule.IssueCheck.CheckResult}, results of auto or manual check. * @property {Kekule.IssueCheck.CheckResult} activeIssueCheckResult Current selected issue check result in issue inspector. * @property {Bool} showAllIssueMarkers Whether all issue markers shouled be marked in editor. * Note, the active issue will always be marked. * @property {Bool} enableIssueMarkerHint Whether display hint text on issue markers. * @property {Bool} enableAutoScrollToActiveIssue Whether the editor will automatically scroll to the issue object when selecting in issue inspector. * @property {Bool} enableOperContext If this property is set to true, object being modified will be drawn in a * separate context to accelerate the interface refreshing. * @property {Object} objContext Context to draw basic chem objects. Can be 2D or 3D context. Alias of property drawContext * @property {Object} operContext Context to draw objects being operated. Can be 2D or 3D context. * @property {Object} uiContext Context to draw UI marks. Usually this is a 2D context. * @property {Object} objDrawBridge Bridge to draw chem objects. Alias of property drawBridge. * @property {Object} uiDrawBridge Bridge to draw UI markers. * @property {Int} selectMode Value from Kekule.Editor.SelectMode, set the mode of selecting operation in editor. * @property {Array} selection An array of selected basic object. * @property {Hash} zoomCenter The center coord (based on client element) when zooming editor. * //@property {Bool} standardizeObjectsBeforeSaving Whether standardize molecules (and other possible objects) before saving them. */ /** * Invoked when the an chem object is loaded into editor. * event param of it has one fields: {obj: Object} * @name Kekule.Editor.BaseEditor#load * @event */ /** * Invoked when the chem object inside editor is changed. * event param of it has one fields: {obj: Object, propNames: Array} * @name Kekule.Editor.BaseEditor#editObjChanged * @event */ /** * Invoked when multiple chem objects inside editor is changed. * event param of it has one fields: {details}. * @name Kekule.Editor.BaseEditor#editObjsChanged * @event */ /** * Invoked when chem objects inside editor is changed and the changes has been updated by editor. * event param of it has one fields: {details}. * Note: this event is not the same as editObjsChanged. When beginUpdateObj is called, editObjsChanged * event still will be invoked but editObjsUpdated event will be suppressed. * @name Kekule.Editor.BaseEditor#editObjsUpdated * @event */ /** * Invoked when the selected objects in editor has been changed. * When beginUpdateObj is called, selectedObjsUpdated event will be suppressed. * event param of it has one fields: {objs}. * @name Kekule.Editor.BaseEditor#selectedObjsUpdated * @event */ /** * Invoked when the pointer (usually the mouse) hovering on basic objects(s) in editor. * Event param of it has field {objs}. When the pointer move out of the obj, the objs field will be a empty array. * @name Kekule.Editor.BaseEditor#hoverOnObjs * @event */ /** * Invoked when the selection in editor has been changed. * @name Kekule.Editor.BaseEditor#selectionChange * @event */ /** * Invoked when the operation history has modifications. * @name Kekule.Editor.BaseEditor#operChange * @event */ /** * Invoked when the an operation is pushed into operation history. * event param of it has one fields: {operation: Kekule.Operation} * @name Kekule.Editor.BaseEditor#operPush * @event */ /** * Invoked when the an operation is popped from history. * event param of it has one fields: {operation: Kekule.Operation} * @name Kekule.Editor.BaseEditor#operPop * @event */ /** * Invoked when one operation is undone. * event param of it has two fields: {operation: Kekule.Operation, currOperIndex: Int} * @name Kekule.Editor.BaseEditor#operUndo * @event */ /** * Invoked when one operation is redone. * event param of it has two fields: {operation: Kekule.Operation, currOperIndex: Int} * @name Kekule.Editor.BaseEditor#operRedo * @event */ /** * Invoked when the operation history is cleared. * event param of it has one field: {currOperIndex: Int} * @name Kekule.Editor.BaseEditor#operHistoryClear * @event */ Kekule.Editor.BaseEditor = Class.create(Kekule.ChemWidget.ChemObjDisplayer, /** @lends Kekule.Editor.BaseEditor# */ { /** @private */ CLASS_NAME: 'Kekule.Editor.BaseEditor', /** @private */ BINDABLE_TAG_NAMES: ['div', 'span'], /** @private */ OBSERVING_GESTURES: ['rotate', 'rotatestart', 'rotatemove', 'rotateend', 'rotatecancel', 'pinch', 'pinchstart', 'pinchmove', 'pinchend', 'pinchcancel', 'pinchin', 'pinchout'], /** @constructs */ initialize: function(/*$super, */parentOrElementOrDocument, chemObj, renderType, editorConfigs) { this._objSelectFlag = 0; // used internally this._objectUpdateFlag = 0; // used internally this._objectManipulateFlag = 0; // used internally this._uiMarkerUpdateFlag = 0; // used internally this._updatedObjectDetails = []; // used internally this._operatingObjs = []; // used internally this._operatingRenderers = []; // used internally this._initialRenderTransformParams = null; // used internally, must init before $super // as in $super, chemObj may be loaded and _initialRenderTransformParams will be set at that time this._objChanged = false; // used internally, mark whether some changes has been made to chem object this._lengthCaches = {}; // used internally, stores some value related to distance and length var getOptionValue = Kekule.globalOptions.get; /* this.setPropStoreFieldValue('enableIssueCheck', true); this.setPropStoreFieldValue('enableCreateNewDoc', true); this.setPropStoreFieldValue('enableOperHistory', true); this.setPropStoreFieldValue('enableOperContext', true); this.setPropStoreFieldValue('initOnNewDoc', true); */ this.setPropStoreFieldValue('enableIssueCheck', getOptionValue('chemWidget.editor.enableIssueCheck', true)); this.setPropStoreFieldValue('enableCreateNewDoc', getOptionValue('chemWidget.editor.enableCreateNewDoc', true)); this.setPropStoreFieldValue('enableOperHistory', getOptionValue('chemWidget.editor.enableOperHistory', true)); this.setPropStoreFieldValue('enableOperContext', getOptionValue('chemWidget.editor.enableOperContext', true)); this.setPropStoreFieldValue('initOnNewDoc', getOptionValue('chemWidget.editor.initOnNewDoc', true)); //this.setPropStoreFieldValue('initialZoom', 1.5); //this.setPropStoreFieldValue('selectMode', Kekule.Editor.SelectMode.POLYGON); // debug this.tryApplySuper('initialize', [parentOrElementOrDocument, chemObj, renderType]) /* $super(parentOrElementOrDocument, chemObj, renderType) */; //this.initEventHandlers(); if (!this.getChemObj() && this.getInitOnNewDoc() && this.getEnableCreateNewDoc()) this.newDoc(); this.setPropStoreFieldValue('editorConfigs', editorConfigs || this.createDefaultConfigs()); //this.setPropStoreFieldValue('uiMarkers', []); //this.setEnableGesture(true); this.setEnableGesture(getOptionValue('chemWidget.editor.enableGesture', true)); }, /** @private */ initProperties: function() { this.defineProp('editorConfigs', {'dataType': 'Kekule.Editor.BaseEditorConfigs', 'serializable': false, 'getter': function() { return this.getDisplayerConfigs(); }, 'setter': function(value) { return this.setDisplayerConfigs(value); } }); this.defineProp('defBondLength', {'dataType': DataType.FLOAT, 'serializable': false, 'getter': function() { var result = this.getPropStoreFieldValue('defBondLength'); if (!result) result = this.getEditorConfigs().getStructureConfigs().getDefBondLength(); return result; } }); this.defineProp('defBondScreenLength', {'dataType': DataType.FLOAT, 'serializable': false, 'setter': null, 'getter': function() { /* var result = this.getPropStoreFieldValue('defBondScreenLength'); if (!result) { var bLength = this.getDefBondLength(); result = this.translateDistance(bLength, Kekule.Render.CoordSys.CHEM, Kekule.Render.CoordSys.SCREEN); } return result; */ var cached = this._lengthCaches.defBondScreenLength; if (cached) return cached; else { var bLength = this.getDefBondLength() || 0; var result = this.translateDistance(bLength, Kekule.Render.CoordSystem.CHEM, Kekule.Render.CoordSystem.SCREEN); this._lengthCaches.defBondScreenLength = result; return result; } } }); // Different pointer event (mouse, touch) has different bound inflation settings, stores here this.defineProp('currBoundInflation', {'dataType': DataType.NUMBER, 'serializable': false, 'setter': null, 'getter': function(){ var pType = this.getCurrPointerType(); return this.getInteractionBoundInflation(pType); } }); // The recent pointer device interacted with this editor this.defineProp('currPointerType', {'dataType': DataType.STRING, 'serializable': false}); //this.defineProp('standardizeObjectsBeforeSaving', {'dataType': DataType.BOOL}); this.defineProp('enableCreateNewDoc', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('initOnNewDoc', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('enableOperHistory', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('operHistory', { 'dataType': 'Kekule.OperationHistory', 'serializable': false, 'getter': function() { /* if (!this.getEnableOperHistory()) return null; */ var result = this.getPropStoreFieldValue('operHistory'); if (!result) { result = new Kekule.OperationHistory(); this.setPropStoreFieldValue('operHistory', result); // install event handlers result.addEventListener('push', this.reactOperHistoryPush, this); result.addEventListener('pop', this.reactOperHistoryPop, this); result.addEventListener('undo', this.reactOperHistoryUndo, this); result.addEventListener('redo', this.reactOperHistoryRedo, this); result.addEventListener('clear', this.reactOperHistoryClear, this); result.addEventListener('change', this.reactOperHistoryChange, this); } return result; }, 'setter': null }); this.defineProp('operationsInCurrManipulation', {'dataType': DataType.ARRAY, 'scope': Class.PropertyScope.PRIVATE, 'serializable': false}); // private this.defineProp('selection', {'dataType': DataType.ARRAY, 'serializable': false, 'getter': function() { var result = this.getPropStoreFieldValue('selection'); if (!result) { result = []; this.setPropStoreFieldValue('selection', result); } return result; }, 'setter': function(value) { this.setPropStoreFieldValue('selection', value); this.selectionChanged(); } }); this.defineProp('selectMode', {'dataType': DataType.INT, 'getter': function() { var result = this.getPropStoreFieldValue('selectMode'); if (Kekule.ObjUtils.isUnset(result)) result = Kekule.Editor.SelectMode.RECT; // default value return result; }, 'setter': function(value) { if (this.getSelectMode() !== value) { //console.log('set select mode', value); this.setPropStoreFieldValue('selectMode', value); this.hideSelectingMarker(); } } }); // private, whether defaultly select in toggle mode this.defineProp('isToggleSelectOn', {'dataType': DataType.BOOL}); this.defineProp('hotTrackedObjs', {'dataType': DataType.ARRAY, 'serializable': false, 'setter': function(value) { /* if (this.getHotTrackedObjs() === value) return; */ var objs = value? Kekule.ArrayUtils.toArray(value): []; //console.log('setHotTrackedObjs', objs); if (this.getEditorConfigs() && this.getEditorConfigs().getInteractionConfigs().getEnableHotTrack()) { this.setPropStoreFieldValue('hotTrackedObjs', objs); var bounds; if (objs && objs.length) { bounds = []; for (var i = 0, l = objs.length; i < l; ++i) { var bound = this.getBoundInfoRecorder().getBound(this.getObjContext(), objs[i]); if (bounds) { //bounds.push(bound); Kekule.ArrayUtils.pushUnique(bounds, bound); // bound may be an array of composite shape } } } if (bounds) { this.changeHotTrackMarkerBounds(bounds); //console.log('show'); } else { if (this.getUiHotTrackMarker().getVisible()) this.hideHotTrackMarker(); //console.log('hide'); } } } }); this.defineProp('hotTrackedObj', {'dataType': DataType.OBJECT, 'serializable': false, 'getter': function() { return this.getHotTrackedObjs() && this.getHotTrackedObjs()[0]; }, 'setter': function(value) { this.setHotTrackedObjs(value); } }); this.defineProp('hoveredBasicObjs', {'dataType': DataType.ARRAY, 'serializable': false}); // a readonly array caching the basic objects at current pointer position this.defineProp('enableOperContext', {'dataType': DataType.BOOL, 'setter': function(value) { this.setPropStoreFieldValue('enableOperContext', !!value); if (!value) // release operContext { var ctx = this.getPropStoreFieldValue('operContext'); var b = this.getPropStoreFieldValue('drawBridge'); if (b && ctx) b.releaseContext(ctx); } } }); this.defineProp('issueCheckExecutor', {'dataType': 'Kekule.IssueCheck.Executor', 'serializable': false, 'setter': null, 'getter': function() { var result = this.getPropStoreFieldValue('issueCheckExecutor'); if (!result) // create default executor { result = this.createIssueCheckExecutor(); // new Kekule.IssueCheck.Executor(); var self = this; result.addEventListener('execute', function(e){ self.setIssueCheckResults(e.checkResults); }); this.setPropStoreFieldValue('issueCheckExecutor', result); } return result; } }); this.defineProp('issueCheckerIds', {'dataType': DataType.ARRAY, 'getter': function() { return this.getIssueCheckExecutor().getCheckerIds(); }, 'setter': function(value) { this.getIssueCheckExecutor().setCheckerIds(value); } }); this.defineProp('enableIssueCheck', {'dataType': DataType.BOOL, 'getter': function() { return this.getIssueCheckExecutor().getEnabled(); }, 'setter': function(value) { this.getIssueCheckExecutor().setEnabled(!!value); if (!value) // when disable issue check, clear the check results { this.setIssueCheckResults(null); } } }); this.defineProp('issueCheckDurationLimit', {'dataType': DataType.NUMBER, 'getter': function() { return this.getIssueCheckExecutor().getDurationLimit(); }, 'setter': function(value) { this.getIssueCheckExecutor().setDurationLimit(value); } }); this.defineProp('enableAutoIssueCheck', {'dataType': DataType.BOOL, 'setter': function(value) { if (!!value !== this.getEnableAutoIssueCheck()) { this.setPropStoreFieldValue('enableAutoIssueCheck', !!value); if (value) // when turn on from off, do a issue check this.checkIssues(); // adjust property showAllIssueMarkers according to enableAutoIssueCheck // If auto check is on, markers should be defaultly opened; // if auto check is off, markers should be defaultly hidden. this.setShowAllIssueMarkers(!!value); } }}); this.defineProp('issueCheckResults', {'dataType': DataType.ARRAY, 'serializable': false, 'setter': function(value) { var oldActive = this.getActiveIssueCheckResult(); this.setPropStoreFieldValue('issueCheckResults', value); if (oldActive && (value || []).indexOf(oldActive) < 0) this.setPropStoreFieldValue('activeIssueCheckResult', null); this.issueCheckResultsChanged(); } }); this.defineProp('activeIssueCheckResult', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': function(value) { if (this.getActiveIssueCheckResult() !== value) { this.setPropStoreFieldValue('activeIssueCheckResult', value); if (value) // when set active issue, deselect all selections to extrusive it this.deselectAll(); this.issueCheckResultsChanged(); } } }); this.defineProp('enableAutoScrollToActiveIssue', {'dataType': DataType.BOOL}); this.defineProp('showAllIssueMarkers', {'dataType': DataType.BOOL, 'setter': function(value) { if (!!value !== this.getShowAllIssueMarkers()) { this.setPropStoreFieldValue('showAllIssueMarkers', !!value); this.recalcIssueCheckUiMarkers(); } } }); this.defineProp('enableIssueMarkerHint', {'dataType': DataType.BOOL}); this.defineProp('enableGesture', {'dataType': DataType.BOOL, 'setter': function(value) { var bValue = !!value; if (this.getEnableGesture() !== bValue) { this.setPropStoreFieldValue('enableGesture', bValue); if (bValue) { this.startObservingGestureEvents(this.OBSERVING_GESTURES); } else { this.startObservingGestureEvents(this.OBSERVING_GESTURES); } } } }); // private this.defineProp('uiEventReceiverElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null}); // context parent properties, private this.defineProp('objContextParentElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null}); this.defineProp('operContextParentElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null}); this.defineProp('uiContextParentElem', {'dataType': DataType.OBJECT, 'serializable': false, setter: null}); this.defineProp('objContext', {'dataType': DataType.OBJECT, 'serializable': false, setter: null, 'getter': function() { return this.getDrawContext(); } }); this.defineProp('operContext', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null, 'getter': function() { if (!this.getEnableOperContext()) return null; else { var result = this.getPropStoreFieldValue('operContext'); if (!result) { var bridge = this.getDrawBridge(); if (bridge) { var elem = this.getOperContextParentElem(); if (!elem) return null; else { var dim = Kekule.HtmlElementUtils.getElemScrollDimension(elem); result = bridge.createContext(elem, dim.width, dim.height); this.setPropStoreFieldValue('operContext', result); } } } return result; } } }); this.defineProp('uiContext', {'dataType': DataType.OBJECT, 'serializable': false, 'getter': function() { var result = this.getPropStoreFieldValue('uiContext'); if (!result) { var bridge = this.getUiDrawBridge(); if (bridge) { var elem = this.getUiContextParentElem(); if (!elem) return null; else { var dim = Kekule.HtmlElementUtils.getElemScrollDimension(elem); //var dim = Kekule.HtmlElementUtils.getElemClientDimension(elem); result = bridge.createContext(elem, dim.width, dim.height); this.setPropStoreFieldValue('uiContext', result); } } } return result; } }); this.defineProp('objDrawBridge', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null, 'getter': function() { return this.getDrawBridge(); } }); this.defineProp('uiDrawBridge', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null, 'getter': function() { var result = this.getPropStoreFieldValue('uiDrawBridge'); if (!result && !this.__$uiDrawBridgeInitialized$__) { this.__$uiDrawBridgeInitialized$__ = true; result = this.createUiDrawBridge(); this.setPropStoreFieldValue('uiDrawBridge', result); } return result; } }); this.defineProp('uiPainter', {'dataType': 'Kekule.Render.ChemObjPainter', 'serializable': false, 'setter': null, 'getter': function() { var result = this.getPropStoreFieldValue('uiPainter'); if (!result) { // ui painter will always in 2D mode var markers = this.getUiMarkers(); result = new Kekule.Render.ChemObjPainter(Kekule.Render.RendererType.R2D, markers, this.getUiDrawBridge()); result.setCanModifyTargetObj(true); this.setPropStoreFieldValue('uiPainter', result); return result; } return result; } }); this.defineProp('uiRenderer', {'dataType': 'Kekule.Render.AbstractRenderer', 'serializable': false, 'setter': null, 'getter': function() { var p = this.getUiPainter(); if (p) { var r = p.getRenderer(); if (!r) p.prepareRenderer(); return p.getRenderer() || null; } else return null; } }); // private ui marks properties //this.defineProp('uiMarkers', {'dataType': DataType.ARRAY, 'serializable': false, 'setter': null}); this.defineProp('uiMarkers', {'dataType': 'Kekule.ChemWidget.UiMarkerCollection', 'serializable': false, 'setter': null, 'getter': function() { var result = this.getPropStoreFieldValue('uiMarkers'); if (!result) { result = new Kekule.ChemWidget.UiMarkerCollection(); this.setPropStoreFieldValue('uiMarkers', result); } return result; } }); /* this.defineProp('uiHotTrackMarker', {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false, 'getter': function() { return this.getUiMarkers().hotTrackMarker; }, 'setter': function(value) { this.getUiMarkers().hotTrackMarker = value; } }); this.defineProp('uiSelectionAreaMarker', {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false, 'getter': function() { return this.getUiMarkers().selectionAreaMarker; }, 'setter': function(value) { this.getUiMarkers().selectionAreaMarker = value; } }); this.defineProp('uiSelectingMarker', {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false, 'getter': function() { return this.getUiMarkers().selectingMarker; }, 'setter': function(value) { this.getUiMarkers().selectingMarker = value; } }); // marker of selecting rubber band */ this._defineUiMarkerProp('uiHotTrackMarker'); this._defineUiMarkerProp('uiSelectionAreaMarker'); // marker of selected range this._defineUiMarkerProp('uiSelectingMarker'); // marker of selecting rubber band this._defineIssueCheckUiMarkerGroupProps(); // error check marker group this.defineProp('uiSelectionAreaContainerBox', {'dataType': DataType.Object, 'serializable': false, 'scope': Class.PropertyScope.PRIVATE}); // a private chemObj-renderer map this.defineProp('objRendererMap', {'dataType': 'Kekule.MapEx', 'serializable': false, 'setter': null, 'getter': function() { var result = this.getPropStoreFieldValue('objRendererMap'); if (!result) { result = new Kekule.MapEx(true); this.setPropStoreFieldValue('objRendererMap', result); } return result; } }); // private object to record all bound infos //this.defineProp('boundInfoRecorder', {'dataType': 'Kekule.Render.BoundInfoRecorder', 'serializable': false, 'setter': null}); this.defineProp('zoomCenter', {'dataType': DataType.HASH}); }, /** @ignore */ initPropValues: function(/*$super*/) { this.tryApplySuper('initPropValues') /* $super() */; this.setOperationsInCurrManipulation([]); /* this.setEnableAutoIssueCheck(false); this.setEnableAutoScrollToActiveIssue(true); var ICIDs = Kekule.IssueCheck.CheckerIds; this.setIssueCheckerIds([ICIDs.ATOM_VALENCE, ICIDs.BOND_ORDER, ICIDs.NODE_DISTANCE_2D]); */ var ICIDs = Kekule.IssueCheck.CheckerIds; var getGlobalOptionValue = Kekule.globalOptions.get; this.setEnableAutoIssueCheck(getGlobalOptionValue('chemWidget.editor.issueChecker.enableAutoIssueCheck', true)); this.setEnableAutoScrollToActiveIssue(getGlobalOptionValue('chemWidget.editor.issueChecker.enableAutoScrollToActiveIssue', true)); this.setIssueCheckerIds(getGlobalOptionValue('chemWidget.editor.issueChecker.issueCheckerIds', [ICIDs.ATOM_VALENCE, ICIDs.BOND_ORDER, ICIDs.NODE_DISTANCE_2D])); this.setIssueCheckDurationLimit(getGlobalOptionValue('chemWidget.editor.issueChecker.durationLimit') || null); this.setEnableIssueMarkerHint(getGlobalOptionValue('chemWidget.editor.issueChecker.enableIssueMarkerHint') || this.getEnableAutoIssueCheck()); }, /** @private */ _defineUiMarkerProp: function(propName, uiMarkerCollection) { return this.defineProp(propName, {'dataType': 'Kekule.ChemWidget.AbstractUIMarker', 'serializable': false, 'getter': function() { var result = this.getPropStoreFieldValue(propName); if (!result) { result = this.createShapeBasedMarker(propName, null, null, false); // prop value already be set in createShapeBasedMarker method } return result; }, 'setter': function(value) { if (!uiMarkerCollection) uiMarkerCollection = this.getUiMarkers(); var old = this.getPropValue(propName); if (old) { uiMarkerCollection.removeMarker(old); old.finalize(); } uiMarkerCollection.addMarker(value); this.setPropStoreFieldValue(propName, value); } }); }, /** @private */ _defineIssueCheckUiMarkerGroupProps: function(uiMarkerCollection) { var EL = Kekule.ErrorLevel; var getSubPropName = function(baseName, errorLevel) { return baseName + '_' + EL.levelToString(errorLevel); }; var baseName = 'issueCheckUiMarker'; var errorLevels = [EL.ERROR, EL.WARNING, EL.NOTE, EL.LOG]; for (var i = 0, l = errorLevels.length; i < l; ++i) { var pname = getSubPropName(baseName, errorLevels[i]); this._defineUiMarkerProp(pname, uiMarkerCollection); } this._defineUiMarkerProp(baseName + '_active', uiMarkerCollection); // 'active' is special marker to mark the selected issue objects // define getter/setter method for group this['get' + baseName.upperFirst()] = function(level){ var p = getSubPropName(baseName, level); return this.getPropValue(p); }; this['set' + baseName.upperFirst()] = function(level, value){ var p = getSubPropName(baseName, level); return this.setPropValue(p, value); }; this['getActive' + baseName.upperFirst()] = function() { return this.getPropValue(baseName + '_active'); }; this['getAll' + baseName.upperFirst() + 's'] = function(){ var result = []; for (var i = 0, l = errorLevels.length; i < l; ++i) { result.push(this.getIssueCheckUiMarker(errorLevels[i])); } var activeMarker = this.getActiveIssueCheckUiMarker(); if (activeMarker) result.push(activeMarker); return result; } }, /** @private */ doFinalize: function(/*$super*/) { var h = this.getPropStoreFieldValue('operHistory'); if (h) { h.finalize(); this.setPropStoreFieldValue('operHistory', null); } var b = this.getPropStoreFieldValue('objDrawBridge'); var ctx = this.getPropStoreFieldValue('operContext'); if (b && ctx) { b.releaseContext(ctx); } this.setPropStoreFieldValue('operContext', null); var b = this.getPropStoreFieldValue('uiDrawBridge'); var ctx = this.getPropStoreFieldValue('uiContext'); if (b && ctx) { b.releaseContext(ctx); } this.setPropStoreFieldValue('uiDrawBridge', null); this.setPropStoreFieldValue('uiContext', null); var m = this.getPropStoreFieldValue('objRendererMap'); if (m) m.finalize(); this.setPropStoreFieldValue('objRendererMap', null); var e = this.getPropStoreFieldValue('issueCheckExecutor'); if (e) e.finalize(); this.setPropStoreFieldValue('issueCheckExecutor', null); this.tryApplySuper('doFinalize') /* $super() */; }, /** @ignore */ elementBound: function(element) { this.setObserveElemResize(true); }, /** * Create a default editor config object. * Descendants may override this method. * @returns {Kekule.Editor.BaseEditorConfigs} * @ignore */ createDefaultConfigs: function() { return new Kekule.Editor.BaseEditorConfigs(); }, /** @ignore */ doCreateRootElement: function(doc) { var result = doc.createElement('div'); return result; }, /** @ignore */ doCreateSubElements: function(doc, rootElem) { var elem = doc.createElement('div'); elem.className = CCNS.EDITOR_CLIENT; rootElem.appendChild(elem); this._editClientElem = elem; return [elem]; }, /** @ignore */ getCoreElement: function(/*$super*/) { return this._editClientElem || this.tryApplySuper('getCoreElement') /* $super() */; }, /** @private */ getEditClientElem: function() { return this._editClientElem; }, /** @ignore */ doGetWidgetClassName: function(/*$super*/) { var result = this.tryApplySuper('doGetWidgetClassName') /* $super() */ + ' ' + CCNS.EDITOR; var additional = (this.getRenderType() === Kekule.Render.RendererType.R3D)? CCNS.EDITOR3D: CCNS.EDITOR2D; result += ' ' + additional; return result; }, /** @private */ doBindElement: function(element) { this.createContextParentElems(); this.createUiEventReceiverElem(); }, // override getter and setter of intialZoom property /** @ignore */ doGetInitialZoom: function(/*$super*/) { var result; var config = this.getEditorConfigs(); if (config) result = config.getInteractionConfigs().getEditorInitialZoom(); if (!result) result = this.tryApplySuper('doGetInitialZoom') /* $super() */; return result; }, /** @ignore */ doSetInitialZoom: function(/*$super, */value) { var config = this.getEditorConfigs(); if (config) config.getInteractionConfigs().setEditorInitialZoom(value); this.tryApplySuper('doSetInitialZoom', [value]) /* $super(value) */; }, /** @ignore */ zoomTo: function(/*$super, */value, suspendRendering, zoomCenterCoord) { var CU = Kekule.CoordUtils; var currZoomLevel = this.getCurrZoom(); var zoomLevel = value; var result = this.tryApplySuper('zoomTo', [value, suspendRendering]) /* $super(value, suspendRendering) */; // adjust zoom center var selfElem = this.getElement(); var currScrollCoord = {'x': selfElem.scrollLeft, 'y': selfElem.scrollTop}; if (!zoomCenterCoord) zoomCenterCoord = this.getZoomCenter(); if (!zoomCenterCoord ) // use the center of client as the zoom center { zoomCenterCoord = CU.add(currScrollCoord, {'x': selfElem.clientWidth / 2, 'y': selfElem.clientHeight / 2}); } //console.log('zoom center info', this.getZoomCenter(), zoomCenterCoord); //if (zoomCenterCoord) { var scrollDelta = CU.multiply(zoomCenterCoord, zoomLevel / currZoomLevel - 1); selfElem.scrollLeft += scrollDelta.x; selfElem.scrollTop += scrollDelta.y; } return result; }, /** * Zoom in. */ /* zoomIn: function(step, zoomCenterCoord) { var curr = this.getCurrZoom(); var ratio = Kekule.ZoomUtils.getNextZoomInRatio(curr, step || 1); return this.zoomTo(ratio, null, zoomCenterCoord); }, */ /** * Zoom out. */ /* zoomOut: function(step, zoomCenterCoord) { var curr = this.getCurrZoom(); var ratio = Kekule.ZoomUtils.getNextZoomOutRatio(curr, step || 1); return this.zoomTo(ratio, null, zoomCenterCoord); }, */ /** * Reset to normal size. */ /* resetZoom: function(zoomCenterCoord) { return this.zoomTo(this.getInitialZoom() || 1, null, zoomCenterCoord); }, */ /** * Change the size of client element. * Width and height is based on px. * @private */ changeClientSize: function(width, height, zoomLevel) { this._initialRenderTransformParams = null; var elem = this.getCoreElement(); var style = elem.style; if (!zoomLevel) zoomLevel = 1; var w = width * zoomLevel; var h = height * zoomLevel; if (w) style.width = w + 'px'; if (h) style.height = h + 'px'; var ctxes = [this.getObjContext(), this.getOperContext(), this.getUiContext()]; for (var i = 0, l = ctxes.length; i < l; ++i) { var ctx = ctxes[i]; if (ctx) // change ctx size also { this.getDrawBridge().setContextDimension(ctx, w, h); } } this.repaint(); }, /** * Returns the screen box (x1, y1, x2, y2) of current visible client area in editor. * @returns {Hash} */ getVisibleClientScreenBox: function() { var elem = this.getEditClientElem().parentNode; var result = Kekule.HtmlElementUtils.getElemClientDimension(elem); var pos = this.getClientScrollPosition(); result.x1 = pos.x; result.y1 = pos.y; result.x2 = result.x1 + result.width; result.y2 = result.y1 + result.height; return result; }, /** * Returns the context box (x1, y1, x2, y2, in a specified coord system) of current visible client area in editor. * @param {Int} coordSys * @returns {Hash} */ getVisibleClientBoxOfSys: function(coordSys) { var screenBox = this.getVisibleClientScreenBox(); var coords = Kekule.BoxUtils.getMinMaxCoords(screenBox); var c1 = this.translateCoord(coords.min, Kekule.Editor.CoordSys.SCREEN, coordSys); var c2 = this.translateCoord(coords.max, Kekule.Editor.CoordSys.SCREEN, coordSys); var result = Kekule.BoxUtils.createBox(c1, c2); return result; }, /** * Returns the context box (x1, y1, x2, y2, in object coord system) of current visible client area in editor. * @param {Int} coordSys * @returns {Hash} */ getVisibleClientObjBox: function(coordSys) { return this.getVisibleClientBoxOfSys(Kekule.Editor.CoordSys.CHEM); }, /** * Returns whether the chem object inside editor has been modified since load. * @returns {Bool} */ isDirty: function() { if (this.getEnableOperHistory()) return this.getOperHistory().getCurrIndex() >= 0; else return this._objChanged; }, /** * Returns srcInfo of chemObj. If editor is dirty (object been modified), srcInfo will be unavailable. * @param {Kekule.ChemObject} chemObj * @returns {Object} */ getChemObjSrcInfo: function(chemObj) { if (this.isDirty()) return null; else return chemObj.getSrcInfo? chemObj.getSrcInfo(): null; }, /* @private */ /* _calcPreferedTransformOptions: function() { var drawOptions = this.getDrawOptions(); return this.getPainter().calcPreferedTransformOptions( this.getObjContext(), this.calcDrawBaseCoord(drawOptions), drawOptions); }, */ /** @private */ getActualDrawOptions: function(/*$super*/) { var old = this.tryApplySuper('getActualDrawOptions') /* $super() */; if (this._initialRenderTransformParams) { var result = Object.extend({}, this._initialRenderTransformParams); result = Object.extend(result, old); //var result = Object.create(old); //result.initialRenderTransformParams = this._initialRenderTransformParams; //console.log('extended', this._initialRenderTransformParams, result); return result; } else return old; }, /** @ignore */ /* getDrawClientDimension: function() { }, */ /** @ignore */ repaint: function(/*$super, */overrideOptions) { var ops = overrideOptions; //console.log('repaint called', overrideOptions); //console.log('repaint', this._initialRenderTransformParams); /* if (this._initialRenderTransformParams) { ops = Object.create(overrideOptions || {}); //console.log(this._initialRenderTransformParams); ops = Object.extend(ops, this._initialRenderTransformParams); } else { ops = overrideOptions; //this._initialRenderTransformParams = this._calcPreferedTransformOptions(); //console.log('init params: ', this._initialRenderTransformParams, drawOptions); } */ var result = this.tryApplySuper('repaint', [ops]) /* $super(ops) */; if (this.isRenderable()) { // after paint the new obj the first time, save up the transform params (especially the translates) if (!this._initialRenderTransformParams) { this._initialRenderTransformParams = this.getPainter().getActualInitialRenderTransformOptions(this.getObjContext()); /* if (transParam) { var trans = {} var unitLength = transParam.unitLength || 1; if (Kekule.ObjUtils.notUnset(transParam.translateX)) trans.translateX = transParam.translateX / unitLength; if (Kekule.ObjUtils.notUnset(transParam.translateY)) trans.translateY = transParam.translateY / unitLength; if (Kekule.ObjUtils.notUnset(transParam.translateZ)) trans.translateZ = transParam.translateZ / unitLength; if (transParam.center) trans.center = transParam.center; //var zoom = transParam.zoom || 1; var zoom = 1; trans.scaleX = transParam.scaleX / zoom; trans.scaleY = transParam.scaleY / zoom; trans.scaleZ = transParam.scaleZ / zoom; this._initialRenderTransformParams = trans; console.log(this._initialRenderTransformParams, this); } */ } // redraw ui markers this.recalcUiMarkers(); } return result; }, /** * Create a new object and load it in editor. */ newDoc: function() { //if (this.getEnableCreateNewDoc()) // enable property only affects UI, always could create new doc in code this.load(this.doCreateNewDocObj()); }, /** * Create a new object for new document. * Descendants may override this method. * @private */ doCreateNewDocObj: function() { return new Kekule.Molecule(); }, /** * Returns array of classes that can be exported (saved) from editor. * Descendants can override this method. * @returns {Array} */ getExportableClasses: function() { var obj = this.getChemObj(); if (!obj) return []; else return obj.getClass? [obj.getClass()]: []; }, /** * Returns exportable object for specified class. * Descendants can override this method. * @param {Class} objClass Set null to export default object. * @returns {Object} */ exportObj: function(objClass) { return this.exportObjs(objClass)[0]; }, /** * Returns all exportable objects for specified class. * Descendants can override this method. * @param {Class} objClass Set null to export default object. * @returns {Array} */ exportObjs: function(objClass) { var obj = this.getChemObj(); if (!objClass) return [obj]; else { return (obj && (obj instanceof objClass))? [obj]: []; } }, /** @private */ doLoad: function(/*$super, */chemObj) { // deselect all old objects first this.deselectAll(); this._initialRenderTransformParams = null; // clear rendererMap so that all old renderer info is removed this.getObjRendererMap().clear(); if (this.getOperHistory()) this.getOperHistory().clear(); this.tryApplySuper('doLoad', [chemObj]) /* $super(chemObj) */; this._objChanged = false; // clear hovered object cache this.setPropStoreFieldValue('hoveredBasicObjs', null); // clear issue results this.setIssueCheckResults(null); this.requestAutoCheckIssuesIfNecessary(); }, /** @private */ doLoadEnd: function(/*$super, */chemObj) { this.tryApplySuper('doLoadEnd') /* $super() */; //console.log('loadend: ', chemObj); if (!chemObj) this._initialRenderTransformParams = null; /* else { // after load the new obj the first time, save up the transform params (especially the translates) var transParam = this.getPainter().getActualRenderTransformParams(this.getObjContext()); if (transParam) { var trans = {} var unitLength = transParam.unitLength || 1; if (Kekule.ObjUtils.notUnset(transParam.translateX)) trans.translateX = transParam.translateX / unitLength; if (Kekule.ObjUtils.notUnset(transParam.translateY)) trans.translateY = transParam.translateY / unitLength; if (Kekule.ObjUtils.notUnset(transParam.translateZ)) trans.translateZ = transParam.translateZ / unitLength; this._initialRenderTransformParams = trans; console.log(this._initialRenderTransformParams, this); } } */ }, /** @private */ doResize: function(/*$super*/) { //console.log('doResize'); this._initialRenderTransformParams = null; // transform should be recalculated after resize this.tryApplySuper('doResize') /* $super() */; }, /** @ignore */ geometryOptionChanged: function(/*$super*/) { var zoom = this.getDrawOptions().zoom; this.zoomChanged(zoom); // clear some length related caches this._clearLengthCaches(); this.tryApplySuper('geometryOptionChanged') /* $super() */; }, /** @private */ zoomChanged: function(zoomLevel) { // do nothing here }, /** @private */ _clearLengthCaches: function() { this._lengthCaches = {}; }, /** * @private */ chemObjChanged: function(/*$super, */newObj, oldObj) { this.tryApplySuper('chemObjChanged', [newObj, oldObj]) /* $super(newObj, oldObj) */; if (newObj !== oldObj) { if (oldObj) this._uninstallChemObjEventListener(oldObj); if (newObj) this._installChemObjEventListener(newObj); } }, /** @private */ _installChemObjEventListener: function(chemObj) { chemObj.addEventListener('change', this.reactChemObjChange, this); }, /** @private */ _uninstallChemObjEventListener: function(chemObj) { chemObj.removeEventListener('change', this.reactChemObjChange, this); }, /** * Create a transparent div element above all other elems of editor, * this element is used to receive all UI events. */ createUiEventReceiverElem: function() { var parent = this.getCoreElement(); if (parent) { var result = parent.ownerDocument.createElement('div'); result.className = CCNS.EDITOR_UIEVENT_RECEIVER; /* result.id = 'overlayer'; */ /* var style = result.style; style.background = 'transparent'; //style.background = 'yellow'; //style.opacity = 0; style.position = 'absolute'; style.left = 0; style.top = 0; style.width = '100%'; style.height = '100%'; */ //style.zIndex = 1000; parent.appendChild(result); EU.addClass(result, CNS.DYN_CREATED); this.setPropStoreFieldValue('uiEventReceiverElem', result); return result; } }, /** @private */ createContextParentElems: function() { var parent = this.getCoreElement(); if (parent) { var doc = parent.ownerDocument; this._createContextParentElem(doc, parent, 'objContextParentElem'); this._createContextParentElem(doc, parent, 'operContextParentElem'); this._createContextParentElem(doc, parent, 'uiContextParentElem'); } }, /** @private */ _createContextParentElem: function(doc, parentElem, contextElemPropName) { var result = doc.createElement('div'); result.style.position = 'absolute'; result.style.width = '100%'; result.style.height = '100%'; result.className = contextElemPropName + ' ' + CNS.DYN_CREATED; // debug this.setPropStoreFieldValue(contextElemPropName, result); parentElem.appendChild(result); return result; }, /** @private */ createNewPainter: function(/*$super, */chemObj) { var result = this.tryApplySuper('createNewPainter', [chemObj]) /* $super(chemObj) */; if (result) { result.setCanModifyTargetObj(true); this.installPainterEventHandlers(result); /* Moved up to class ChemObjDisplayer // create new bound info recorder this.createNewBoundInfoRecorder(this.getPainter()); */ } return result; }, /** @private */ /* Moved up to class ChemObjDisplayer createNewBoundInfoRecorder: function(renderer) { var old = this.getPropStoreFieldValue('boundInfoRecorder'); if (old) old.finalize(); var recorder = new Kekule.Render.BoundInfoRecorder(renderer); //recorder.setTargetContext(this.getObjContext()); this.setPropStoreFieldValue('boundInfoRecorder', recorder); }, */ /** @private */ getDrawContextParentElem: function() { return this.getObjContextParentElem(); }, /** @private */ createUiDrawBridge: function() { // UI marker will always be in 2D var result = Kekule.Render.DrawBridge2DMananger.getPreferredBridgeInstance(); if (!result) // can not find suitable draw bridge { //Kekule.error(Kekule.$L('ErrorMsg.DRAW_BRIDGE_NOT_SUPPORTED')); var errorMsg = Kekule.Render.DrawBridge2DMananger.getUnavailableMessage() || Kekule.error(Kekule.$L('ErrorMsg.DRAW_BRIDGE_NOT_SUPPORTED')); if (errorMsg) this.reportException(errorMsg, Kekule.ExceptionLevel.NOT_FATAL_ERROR); } return result; }, /* @private */ /* refitDrawContext: function($super, doNotRepaint) { //var dim = Kekule.HtmlElementUtils.getElemScrollDimension(this.getElement()); var dim = Kekule.HtmlElementUtils.getElemClientDimension(this.getElement()); //this._resizeContext(this.getObjDrawContext(), this.getObjDrawBridge(), dim.width, dim.height); this._resizeContext(this.getOperContext(), this.getObjDrawBridge(), dim.width, dim.height); this._resizeContext(this.getUiContext(), this.getUiDrawBridge(), dim.width, dim.height); $super(doNotRepaint); }, */ /** @private */ changeContextDimension: function(/*$super, */newDimension) { var result = this.tryApplySuper('changeContextDimension', [newDimension]) /* $super(newDimension) */; if (result) { this._resizeContext(this.getOperContext(), this.getObjDrawBridge(), newDimension.width, newDimension.height); this._resizeContext(this.getUiContext(), this.getUiDrawBridge(), newDimension.width, newDimension.height); } return result; }, /** @private */ _clearSpecContext: function(context, bridge) { if (bridge && context) bridge.clearContext(context); }, /** @private */ _renderSpecContext: function(context, bridge) { if (bridge && context) bridge.renderContext(context); }, /** * Clear the main context. * @private */ clearObjContext: function() { //console.log('clear obj context', this.getObjContext() === this.getDrawContext()); this._clearSpecContext(this.getObjContext(), this.getDrawBridge()); if (this.getBoundInfoRecorder()) this.getBoundInfoRecorder().clear(this.getObjContext()); }, /** * Clear the operating context. * @private */ clearOperContext: function() { this._clearSpecContext(this.getOperContext(), this.getDrawBridge()); }, /** * Clear the UI layer context. * @private */ clearUiContext: function() { this._clearSpecContext(this.getUiContext(), this.getUiDrawBridge()); }, /** @private */ clearContext: function() { this.clearObjContext(); if (this._operatingRenderers) this.clearOperContext(); }, /** * Repaint the operating context only (not the whole obj context). * @private */ repaintOperContext: function(ignoreUiMarker) { if (this._operatingRenderers && this._operatingObjs) { this.clearOperContext(); try { var options = {'partialDrawObjs': this._operatingObjs, 'doNotClear': true}; this.repaint(options); } finally { this._renderSpecContext(this.getOperContext(), this.getDrawBridge()); // important, done the rendering of oper context } /* var context = this.getObjContext(); //console.log(this._operatingRenderers.length); for (var i = 0, l = this._operatingRenderers.length; i < l; ++i) { var renderer = this._operatingRenderers[i]; console.log('repaint oper', renderer.getClassName(), renderer.getChemObj().getId(), !!renderer.getRedirectContext(), this._operatingRenderers.length); renderer.redraw(context); } if (!ignoreUiMarker) this.recalcUiMarkers(); */ } }, /** @private */ getOperatingRenderers: function() { if (!this._operatingRenderers) this._operatingRenderers = []; return this._operatingRenderers; }, /** @private */ setOperatingRenderers: function(value) { this._operatingRenderers = value; }, ////////////////////////////////////////////////////////////////////// /////////////////// methods about painter //////////////////////////// /** @private */ installPainterEventHandlers: function(painter) { painter.addEventListener('prepareDrawing', this.reactChemObjPrepareDrawing, this); painter.addEventListener('clear', this.reactChemObjClear, this); }, /** @private */ reactChemObjPrepareDrawing: function(e) { var ctx = e.context; var obj = e.obj; if (obj && ((ctx === this.getObjContext()) || (ctx === this.getOperContext()))) { var renderer = e.target; this.getObjRendererMap().set(obj, renderer); //console.log('object drawn', obj, obj.getClassName(), renderer, renderer.getClassName()); // check if renderer should be redirected to oper context if (this.getEnableOperContext()) { var operObjs = this._operatingObjs || []; var needRedirect = false; for (var i = 0, l = operObjs.length; i < l; ++i) { if (this._isChemObjDirectlyRenderedByRenderer(this.getObjContext(), operObjs[i], renderer)) { needRedirect = true; break; } } if (needRedirect) { this._setRendererToOperContext(renderer); //console.log('do redirect', renderer.getClassName(), obj && obj.getId && obj.getId()); AU.pushUnique(this.getOperatingRenderers(), renderer); } /* else { this._unsetRendererToOperContext(renderer); console.log('unset redirect', renderer.getClassName(), obj && obj.getId && obj.getId()); } */ } } }, /** @private */ reactChemObjClear: function(e) { var ctx = e.context; var obj = e.obj; if (obj && ((ctx === this.getObjContext()) || (ctx === this.getOperContext()))) { var renderer = e.target; this.getObjRendererMap().remove(obj); AU.remove(this.getOperatingRenderers(), renderer); } }, ////////////////////////////////////////////////////////////////////// /////////////////// event handlers of nested objects /////////////////////// /** * React to change event of loaded chemObj. * @param {Object} e */ reactChemObjChange: function(e) { var target = e.target; var propNames = e.changedPropNames || []; var bypassPropNames = ['id', 'owner', 'ownedObjs']; // these properties do not affect rendering propNames = Kekule.ArrayUtils.exclude(propNames, bypassPropNames); if (propNames.length || !e.changedPropNames) // when changedPropNames is not set, may be change event invoked by parent when suppressing child objects { //console.log('chem obj change', target.getClassName(), propNames, e); this.objectChanged(target, propNames); } }, /** @private */ reactOperHistoryPush: function(e) { this.invokeEvent('operPush', e); }, /** @private */ reactOperHistoryPop: function(e) { this.invokeEvent('operPop', e); }, /** @private */ reactOperHistoryUndo: function(e) { this.invokeEvent('operUndo', e); }, /** @private */ reactOperHistoryRedo: function(e) { this.invokeEvent('operRedo', e); }, reactOperHistoryClear: function(e) { this.invokeEvent('operHistoryClear', e); }, reactOperHistoryChange: function(e) { this.invokeEvent('operChange', e); }, ///////////////////////////////////////////////////////////////////////////// ///////////// Methods about object changing notification //////////////////// /** * Call this method to temporarily suspend object change notification. */ beginUpdateObject: function() { if (this._objectUpdateFlag >= 0) { this.invokeEvent('beginUpdateObject'); } --this._objectUpdateFlag; }, /** * Call this method to indicate the update process is over and objectChanged will be immediately called. */ endUpdateObject: function() { ++this._objectUpdateFlag; if (!this.isUpdatingObject()) { if ((this._updatedObjectDetails && this._updatedObjectDetails.length)) { this.objectsChanged(this._updatedObjectDetails); this._updatedObjectDetails = []; } this._execAfterUpdateObjectProcs(); this.invokeEvent('endUpdateObject'/*, {'details': Object.extend({}, this._updatedObjectDetails)}*/); } }, /** * Check if beginUpdateObject is called and should not send object change notification immediately. */ isUpdatingObject: function() { return (this._objectUpdateFlag < 0); }, /** * Register suspended function called right after endUpdateObject method. * @private */ _registerAfterUpdateObjectProc: function(proc) { if (this.isUpdatingObject()) { if (!this.endUpdateObject.suspendedProcs) this.endUpdateObject.suspendedProcs = []; this.endUpdateObject.suspendedProcs.push(proc); } else proc.apply(this); }, /** @private */ _execAfterUpdateObjectProcs: function() { var procs = this.endUpdateObject.suspendedProcs; if (procs) { while (procs.length) { var proc = procs.shift(); if (proc) proc.apply(this); } } }, /** @private */ _mergeObjUpdatedDetails: function(dest, target) { for (var i = 0, l = target.length; i < l; ++i) { this._mergeObjUpdatedDetailItem(dest, target[i]); } }, /** @private */ _mergeObjUpdatedDetailItem: function(dest, targetItem) { for (var i = 0, l = dest.length; i < l; ++i) { var destItem = dest[i]; // can merge if (destItem.obj === targetItem.obj) { if (!destItem.propNames) destItem.propNames = []; if (targetItem.propNames) Kekule.ArrayUtils.pushUnique(destItem.propNames, targetItem.propNames); return; } } // can not merge dest.push(targetItem); }, /** @private */ _logUpdatedDetail: function(details) { var msg = ''; details.forEach(function(d){ msg += 'Obj: ' + d.obj.getId() + '[' + d.obj.getClassName() + '] '; msg += 'Props: [' + d.propNames.join(', ') + ']'; msg += '\n'; }); console.log(msg); }, /** * Notify the object(s) property has been changed and need to be updated. * @param {Variant} obj An object or a object array. * @param {Array} changedPropNames * @private */ objectChanged: function(obj, changedPropNames) { var data = {'obj': obj, 'propNames': changedPropNames}; //console.log('obj changed', obj.getClassName(), obj.getId(), changedPropNames); var result = this.objectsChanged(data); this.invokeEvent('editObjChanged', Object.extend({}, data)); // avoid change data return result; }, /** * Notify the object(s) property has been changed and need to be updated. * @param {Variant} objDetails An object detail or an object detail array. * @private */ objectsChanged: function(objDetails) { var a = DataType.isArrayValue(objDetails)? objDetails: [objDetails]; if (this.isUpdatingObject()) // suspend notification, just push objs in cache { //Kekule.ArrayUtils.pushUnique(this._updatedObjectDetails, a); this._mergeObjUpdatedDetails(this._updatedObjectDetails, a); //console.log('updating objects, suspending...', this._updatedObjectDetails); //this._logUpdatedDetail(this._updatedObjectDetails); } else { //console.log('object changed', objDetails); var updateObjs = Kekule.Render.UpdateObjUtils._extractObjsOfUpdateObjDetails(a); this.doObjectsChanged(a, updateObjs); // IMPORTANT: must do issue check after the doObjectsChanged method (invoking repainting) this.requestAutoCheckIssuesIfNecessary(); this.invokeEvent('editObjsUpdated', {'details': Object.extend({}, objDetails)}); } this._objChanged = true; // mark object changed this.invokeEvent('editObjsChanged', {'details': Object.extend({}, objDetails)}); var selectedObjs = this.getSelection(); if (selectedObjs && updateObjs) { var changedSelectedObjs = AU.intersect(selectedObjs, updateObjs); if (changedSelectedObjs.length) this.invokeEvent('selectedObjsUpdated', {'objs': changedSelectedObjs}); } }, /** * Do actual job of objectsChanged. Descendants should override this method. * @private */ doObjectsChanged: function(objDetails, updateObjs) { var oDetails = Kekule.ArrayUtils.clone(objDetails); if (!updateObjs) updateObjs = Kekule.Render.UpdateObjUtils._extractObjsOfUpdateObjDetails(oDetails); //console.log('origin updateObjs', updateObjs); var additionalObjs = this._getAdditionalRenderRelatedObjs(updateObjs); // also push related objects into changed objs list if (additionalObjs.length) { var additionalDetails = Kekule.Render.UpdateObjUtils._createUpdateObjDetailsFromObjs(additionalObjs); Kekule.ArrayUtils.pushUnique(oDetails, additionalDetails); } // merge updateObjs and additionalObjs //updateObjs = updateObjs.concat(additionalObjs); Kekule.ArrayUtils.pushUnique(updateObjs, additionalObjs); //console.log('changed objects', updateObjs); var operRenderers = this._operatingRenderers; var updateOperContextOnly = operRenderers && this._isAllObjsRenderedByRenderers(this.getObjContext(), updateObjs, operRenderers); var canDoPartialUpdate = this.canModifyPartialGraphic(); //console.log('update objs and operRenderers', updateObjs, operRenderers); //console.log('object changed', updateOperContextOnly, canDoPartialUpdate); if (canDoPartialUpdate) // partial update { //var updateObjDetails = Kekule.Render.UpdateObjUtils._createUpdateObjDetailsFromObjs(updateObjs); this.getRootRenderer().modify(this.getObjContext(),/* updateObjDetails*/oDetails); // always repaint UI markers this.recalcUiMarkers(); //console.log('partial update', oDetails); } else // update whole context { if (updateOperContextOnly) { //console.log('repaint oper context only'); this.repaintOperContext(); } else // need to update whole context { //console.log('[repaint whole]'); this.repaint(); /* var self = this; (function(){ self.repaint(); }).defer(); */ } } }, /** * Call this method to indicate a continuous manipulation operation is doing (e.g. moving or rotating objects). */ beginManipulateObject: function() { //console.log('[BEGIN MANIPULATE]'); //console.log('[Call begin update]', this._objectManipulateFlag); if (this._objectManipulateFlag >= 0) { this.invokeEvent('beginManipulateObject'); } --this._objectManipulateFlag; }, /** * Call this method to indicate the update process is over and objectChanged will be immediately called. */ endManipulateObject: function() { ++this._objectManipulateFlag; //console.log('[END MANIPULATE]'); if (!this.isManipulatingObject()) { this._objectManipulateFlag = 0; this.doManipulationEnd(); this.requestAutoCheckIssuesIfNecessary(); //console.log('[MANIPULATE DONE]'); //this.invokeEvent('endManipulateObject'/*, {'details': Object.extend({}, this._updatedObjectDetails)}*/); } }, /** * Check if beginUpdateObject is called and should not send object change notification immediately. */ isManipulatingObject: function() { return (this._objectManipulateFlag < 0); }, /** * Called when endManipulateObject is called and the object manipulation is really done. * @private */ doManipulationEnd: function() { //console.log('[MANIPULATE END]'); this.setOperationsInCurrManipulation([]); this.invokeEvent('endManipulateObject'/*, {'details': Object.extend({}, this._updatedObjectDetails)}*/); }, /** * A combination of method beginUpdateObject/beginManipulateObject. */ beginManipulateAndUpdateObject: function() { this.beginManipulateObject(); this.beginUpdateObject(); }, /** * A combination of method endUpdateObject/endManipulateObject. */ endManipulateAndUpdateObject: function() { this.endUpdateObject(); this.endManipulateObject(); }, /* * Try apply modification to a series of objects in editor. * @param {Variant} modificationOrName Modification object or name. * @param {Variant} targets Target object or objects. * @returns {Kekule.Operation} operation actually done. */ /* applyModification: function(modificationOrName, targets) { var objs = AU.toArray(targets); var modification = (typeof(modificationOrName) === 'string')? Kekule.Editor.ChemObjModificationManager.getModification(modificationOrName): modificationOrName; if (objs.length && modification) { var opers = []; for (var i = 0, l = objs.length; i < l; ++i) { if (modification.match(objs[i], this)) { var oper = modification.createOperation(objs[i], this); if (oper) opers.push(oper); } } } if (opers.length) { var finalOper = (opers.length === 1) ? opers[0] : new Kekule.MacroOperation(opers); this.execOperation(finalOper); return finalOper; } else return null; }, */ /** @private */ _needToCanonicalizeBeforeSaving: function() { return true; // !!this.getStandardizeObjectsBeforeSaving(); }, /** @private */ _getAdditionalRenderRelatedObjs: function(objs) { var result = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; //Kekule.ArrayUtils.pushUnique(result, obj); var relatedObjs = obj.getCoordDeterminateObjects? obj.getCoordDeterminateObjects(): []; //console.log('obj', obj.getClassName(), 'related', relatedObjs); Kekule.ArrayUtils.pushUnique(result, relatedObjs); } return result; }, /** @private */ _isAllObjsRenderedByRenderers: function(context, objs, renders) { //console.log('check objs by renderers', objs, renders); for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var isRendered = false; for (var j = 0, k = renders.length; j < k; ++j) { var renderer = renders[j]; if (renderer.isChemObjRenderedBySelf(context, obj)) { isRendered = true; break; } } if (!isRendered) return false; } return true; }, ///////////////////////////////////////////////////////////////////////////// ////////////// Method about operContext rendering /////////////////////////// /** * Prepare to do a modification work in editor (e.g., move some atoms). * The objs to be modified will be rendered in operContext separately (if enableOperContext is true). * @param {Array} objs */ prepareOperatingObjs: function(objs) { // Check if already has old operating renderers. If true, just end them. if (this._operatingRenderers && this._operatingRenderers.length) this.endOperatingObjs(true); if (this.getEnableOperContext()) { // prepare operating renderers this._prepareRenderObjsInOperContext(objs); this._operatingObjs = objs; //console.log('oper objs', this._operatingObjs); //console.log('oper renderers', this._operatingRenderers); } // finally force repaint the whole client area, both objContext and operContext this.repaint(); }, /** * Modification work in editor (e.g., move some atoms) is done. * The objs to be modified will be rendered back into objContext. * @param {Bool} noRepaint */ endOperatingObjs: function(noRepaint) { // notify to render all objs in main context if (this.getEnableOperContext()) { this._endRenderObjsInOperContext(); this._operatingObjs = null; if (!noRepaint) { //console.log('end operation objs'); this.repaint(); } } }, /** @private */ _isChemObjDirectlyRenderedByRenderer: function(context, obj, renderer) { var standaloneObj = obj.getStandaloneAncestor? obj.getStandaloneAncestor(): obj; return renderer.isChemObjRenderedDirectlyBySelf(context, standaloneObj); }, /** @private */ _getStandaloneRenderObjsInOperContext: function(objs) { var standAloneObjs = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj.getStandaloneAncestor) obj = obj.getStandaloneAncestor(); Kekule.ArrayUtils.pushUnique(standAloneObjs, obj); } return standAloneObjs; }, /** @private */ _prepareRenderObjsInOperContext: function(objs) { //console.log('redirect objs', objs); var renderers = []; var map = this.getObjRendererMap(); var rs = map.getValues(); var context = this.getObjContext(); var standAloneObjs = this._getStandaloneRenderObjsInOperContext(objs); /* if (standAloneObjs.length) console.log(standAloneObjs[0].getId(), standAloneObjs); else console.log('(no standalone)'); */ //for (var i = 0, l = objs.length; i < l; ++i) for (var i = 0, l = standAloneObjs.length; i < l; ++i) { //var obj = objs[i]; var obj = standAloneObjs[i]; for (var j = 0, k = rs.length; j < k; ++j) { var renderer = rs[j]; //if (renderer.isChemObjRenderedBySelf(context, obj)) if (renderer.isChemObjRenderedDirectlyBySelf(context, obj)) { //console.log('direct rendered by', obj.getClassName(), renderer.getClassName()); Kekule.ArrayUtils.pushUnique(renderers, renderer); } /* if (parentFragment && renderer.isChemObjRenderedDirectlyBySelf(context, parentFragment)) Kekule.ArrayUtils.pushUnique(renderers, renderer); // when modify node or connector, mol will also be changed */ } /* var renderer = map.get(objs[i]); if (renderer) Kekule.ArrayUtils.pushUnique(renderers, renderer); */ } //console.log('oper renderers', renderers); if (renderers.length > 0) { for (var i = 0, l = renderers.length; i < l; ++i) { var renderer = renderers[i]; this._setRendererToOperContext(renderer); //console.log('begin context redirect', renderer.getClassName()); //console.log(renderer.getRedirectContext()); } this._operatingRenderers = renderers; } else this._operatingRenderers = null; //console.log('<total renderer count>', rs.length, '<redirected>', renderers.length); /* if (renderers.length) console.log('redirected obj 0: ', renderers[0].getChemObj().getId()); */ }, /** @private */ _endRenderObjsInOperContext: function() { var renderers = this._operatingRenderers; if (renderers && renderers.length) { for (var i = 0, l = renderers.length; i < l; ++i) { var renderer = renderers[i]; //renderer.setRedirectContext(null); this._unsetRendererToOperContext(renderer); //console.log('end context redirect', renderer.getClassName()); } this.clearOperContext(); } this._operatingRenderers = null; }, /** @private */ _setRendererToOperContext: function(renderer) { renderer.setRedirectContext(this.getOperContext()); }, /** @private */ _unsetRendererToOperContext: function(renderer) { renderer.setRedirectContext(null); }, ///////////////////////////////////////////////////////////////////////////// //////////////////////// methods about bound maps //////////////////////////// /** * Returns bound inflation for interaction with a certain pointer device (mouse, touch, etc.) * @param {String} pointerType */ getInteractionBoundInflation: function(pointerType) { var cache = this._lengthCaches.interactionBoundInflations; var cacheKey = pointerType || 'default'; if (cache) { if (cache[cacheKey]) { //console.log('cached!') return cache[cacheKey]; } } // no cache, calculate var iaConfigs = this.getEditorConfigs().getInteractionConfigs(); var defRatioPropName = 'objBoundTrackInflationRatio'; var typedRatio, defRatio = iaConfigs.getPropValue(defRatioPropName); if (pointerType) { var sPointerType = pointerType.upperFirst(); var typedRatioPropName = defRatioPropName + sPointerType; if (iaConfigs.hasProperty(typedRatioPropName)) typedRatio = iaConfigs.getPropValue(typedRatioPropName); } var actualRatio = typedRatio || defRatio; var ratioValue = actualRatio && this.getDefBondScreenLength() * actualRatio; var minValuePropName = 'objBoundTrackMinInflation'; var typedMinValue, defMinValue = iaConfigs.getPropValue(minValuePropName); if (pointerType) { var typedMinValuePropName = minValuePropName + sPointerType; if (iaConfigs.hasProperty(typedMinValuePropName)) typedMinValue = iaConfigs.getPropValue(typedMinValuePropName); } var actualMinValue = typedMinValue || defMinValue; var actualValue = Math.max(ratioValue || 0, actualMinValue); // stores to cache if (!cache) { cache = {}; this._lengthCaches.interactionBoundInflations = cache; } cache[cacheKey] = actualValue; //console.log('to cache'); return actualValue; }, /** * Returns all bound map item at x/y. * Input coord is based on the screen coord system. * @returns {Array} * @private */ getBoundInfosAtCoord: function(screenCoord, filterFunc, boundInflation) { /* if (!boundInflation) throw 'boundInflation not set!'; */ var delta = boundInflation || this.getCurrBoundInflation() || this.getEditorConfigs().getInteractionConfigs().getObjBoundTrackMinInflation(); return this.tryApplySuper('getBoundInfosAtCoord', [screenCoord, filterFunc, delta]); /* var boundRecorder = this.getBoundInfoRecorder(); var delta = boundInflation || this.getCurrBoundInflation() || this.getEditorConfigs().getInteractionConfigs().getObjBoundTrackMinInflation(); //var coord = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord); var coord = this.screenCoordToContext(screenCoord); var refCoord = (this.getRenderType() === Kekule.Render.RendererType.R3D)? {'x': 0, 'y': 0}: null; //console.log(coord, delta); var matchedInfos = boundRecorder.getIntersectionInfos(this.getObjContext(), coord, refCoord, delta, filterFunc); return matchedInfos; */ }, /** * returns the topmost bound map item at x/y. * Input coord is based on the screen coord system. * @param {Hash} screenCoord * @param {Array} excludeObjs Objects in this array will not be returned. * @returns {Object} */ getTopmostBoundInfoAtCoord: function(screenCoord, excludeObjs, boundInflation) { var enableTrackNearest = this.getEditorConfigs().getInteractionConfigs().getEnableTrackOnNearest(); if (!enableTrackNearest) //return this.findTopmostBoundInfo(this.getBoundInfosAtCoord(screenCoord, null, boundInflation), excludeObjs, boundInflation); return this.tryApplySuper('getTopmostBoundInfoAtCoord', [screenCoord, excludeObjs, boundInflation]); // else, track on nearest // new approach, find nearest boundInfo at coord var SU = Kekule.Render.MetaShapeUtils; var boundInfos = this.getBoundInfosAtCoord(screenCoord, null, boundInflation); //var filteredBoundInfos = []; var result, lastShapeInfo, lastDistance; var setResult = function(boundInfo, shapeInfo, distance) { result = boundInfo; lastShapeInfo = shapeInfo || boundInfo.boundInfo; if (Kekule.ObjUtils.notUnset(distance)) lastDistance = distance; else lastDistance = SU.getDistance(screenCoord, lastShapeInfo); }; for (var i = boundInfos.length - 1; i >= 0; --i) { var info = boundInfos[i]; if (excludeObjs && (excludeObjs.indexOf(info.obj) >= 0)) continue; if (!result) setResult(info); else { var shapeInfo = info.boundInfo; if (shapeInfo.shapeType < lastShapeInfo.shapeType) setResult(info, shapeInfo); else if (shapeInfo.shapeType === lastShapeInfo.shapeType) { var currDistance = SU.getDistance(screenCoord, shapeInfo); if (currDistance < lastDistance) { //console.log('distanceCompare', currDistance, lastDistance); setResult(info, shapeInfo, currDistance); } } } } return result; }, /** * Returns all basic drawn object at coord (with inflation) based on screen system. * @params {Hash} screenCoord * @param {Number} boundInflation * @param {Array} excludeObjs * @param {Array} filterObjClasses If this param is set, only obj match these types will be returned * @returns {Array} * @private */ getBasicObjectsAtCoord: function(screenCoord, boundInflation, excludeObjs, filterObjClasses) { var boundInfos = this.getBoundInfosAtCoord(screenCoord, null, boundInflation); var result = []; if (boundInfos) { if (excludeObjs) { boundInfos = AU.filter(boundInfos, function(boundInfo){ var obj = boundInfos[i].obj; if (!obj) return false; if (obj) { if (excludeObjs && excludeObjs.indexOf(obj) >= 0) return false; } return true; }); } // the coord sticked obj should be firstly selected for unstick operation, even it is under the back layer var _getStickLevel = function(obj){ var stickTarget = obj && obj.getCoordStickTarget && obj.getCoordStickTarget(); return stickTarget? 1: 0; }; boundInfos.sort(function(b1, b2){ var stickLevel1 = _getStickLevel(b1.obj); var stickLevel2 = _getStickLevel(b2.obj); return (stickLevel1 - stickLevel2); }); var enableTrackNearest = this.getEditorConfigs().getInteractionConfigs().getEnableTrackOnNearest(); if (enableTrackNearest) // sort by bound distances to screenCoord { var SU = Kekule.Render.MetaShapeUtils; boundInfos.sort(function(b1, b2){ // the topmost boundinfo at tail var result = 0; var shapeInfo1 = b1.boundInfo; var shapeInfo2 = b2.boundInfo; result = -(shapeInfo1.shapeType - shapeInfo2.shapeType); if (!result) { var d1 = SU.getDistance(screenCoord, shapeInfo1); var d2 = SU.getDistance(screenCoord, shapeInfo2); result = -(d1 - d2); } return result; }); } for (var i = boundInfos.length - 1; i >= 0; --i) { var obj = boundInfos[i].obj; if (obj) { if (excludeObjs && excludeObjs.indexOf(obj) >= 0) continue; } result.push(obj); } if (result && filterObjClasses) // filter { result = AU.filter(result, function(obj) { for (var i = 0, l = filterObjClasses.length; i < l; ++i) { if (obj instanceof filterObjClasses[i]) return true; } return false; }); } } return result; }, /** * Returns the topmost basic drawn object at coord based on screen system. * @params {Hash} screenCoord * @param {Number} boundInflation * @param {Array} filterObjClasses If this param is set, only obj match these types will be returned * @returns {Object} * @private */ getTopmostBasicObjectAtCoord: function(screenCoord, boundInflation, filterObjClasses) { /* var boundItem = this.getTopmostBoundInfoAtCoord(screenCoord, null, boundInflation); return boundItem? boundItem.obj: null; */ var objs = this.getBasicObjectsAtCoord(screenCoord, boundInflation, null, filterObjClasses); return objs && objs[0]; }, /** * Returns geometry bounds of a obj in editor. * @param {Kekule.ChemObject} obj * @param {Number} boundInflation * @returns {Array} */ getChemObjBounds: function(obj, boundInflation) { var bounds = []; var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj); if (infos && infos.length) { for (var j = 0, k = infos.length; j < k; ++j) { var info = infos[j]; var bound = info.boundInfo; if (bound) { // inflate bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, boundInflation); bounds.push(bound); } } } return bounds; }, //////////////////// methods about UI markers /////////////////////////////// /** * Returns the ui markers at screen coord. * @param {Hash} screenCoord * @param {Float} boundInflation * @param {Array} filterClasses * @returns {Array} */ getUiMarkersAtCoord: function(screenCoord, boundInflation, filterClasses) { var markers = this.getUiMarkers(); var filterFunc = (filterClasses && filterClasses.length)? function(marker) { for (var i = 0, l = filterClasses.length; i < l; ++i) { if (marker instanceof filterClasses[i]) return true; } return false; }: null; var SU = Kekule.Render.MetaShapeUtils; var result = []; for (var i = markers.getMarkerCount() - 1; i >= 0; --i) { var marker = markers.getMarkerAt(i); if (marker.getVisible()) { if (!filterFunc || filterFunc(marker)) { var shapeInfo = marker.shapeInfo; if (SU.isCoordInside(screenCoord, shapeInfo, boundInflation)) result.push(marker); } } } return result; }, /** * Notify that currently is modifing UI markers and the editor need not to repaint them. */ beginUpdateUiMarkers: function() { --this._uiMarkerUpdateFlag; }, /** * Call this method to indicate the UI marker update process is over and should be immediately updated. */ endUpdateUiMarkers: function() { ++this._uiMarkerUpdateFlag; if (!this.isUpdatingUiMarkers()) this.repaintUiMarker(); }, /** Check if the editor is under continuous UI marker update. */ isUpdatingUiMarkers: function() { return (this._uiMarkerUpdateFlag < 0); }, /** * Called when transform has been made to objects and UI markers need to be modified according to it. * The UI markers will also be repainted. * @private */ recalcUiMarkers: function() { //this.setHotTrackedObj(null); if (this.getUiDrawBridge()) { this.beginUpdateUiMarkers(); try { this.recalcHotTrackMarker(); this.recalcSelectionAreaMarker(); this.recalcIssueCheckUiMarkers(); } finally { this.endUpdateUiMarkers(); } } }, /** @private */ repaintUiMarker: function() { if (this.isUpdatingUiMarkers()) return; if (this.getUiDrawBridge() && this.getUiContext()) { this.clearUiContext(); var drawParams = this.calcDrawParams(); this.getUiPainter().draw(this.getUiContext(), drawParams.baseCoord, drawParams.drawOptions); } }, /** * Create a new marker based on shapeInfo. * @private */ createShapeBasedMarker: function(markerPropName, shapeInfo, drawStyles, updateRenderer) { var marker = new Kekule.ChemWidget.MetaShapeUIMarker(); if (shapeInfo) marker.setShapeInfo(shapeInfo); if (drawStyles) marker.setDrawStyles(drawStyles); this.setPropStoreFieldValue(markerPropName, marker); this.getUiMarkers().addMarker(marker); if (updateRenderer) { //var updateType = Kekule.Render.ObjectUpdateType.ADD; //this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, updateType); this.repaintUiMarker(); } return marker; }, /** * Change the shape info of a meta shape based marker, or create a new marker based on shape info. * @private */ modifyShapeBasedMarker: function(marker, newShapeInfo, drawStyles, updateRenderer) { var updateType = Kekule.Render.ObjectUpdateType.MODIFY; if (newShapeInfo) marker.setShapeInfo(newShapeInfo); if (drawStyles) marker.setDrawStyles(drawStyles); // notify change and update renderer if (updateRenderer) { //this.getUiPainter().redraw(); //this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, updateType); this.repaintUiMarker(); } }, /** * Hide a UI marker. * @param marker */ hideUiMarker: function(marker, updateRenderer) { marker.setVisible(false); // notify change and update renderer if (updateRenderer) { //this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, Kekule.Render.ObjectUpdateType.MODIFY); this.repaintUiMarker(); } }, /** * Show an UI marker. * @param marker * @param updateRenderer */ showUiMarker: function(marker, updateRenderer) { marker.setVisible(true); if (updateRenderer) { //this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, Kekule.Render.ObjectUpdateType.MODIFY); this.repaintUiMarker(); } }, /** * Remove a marker from collection. * @private */ removeUiMarker: function(marker) { if (marker) { this.getUiMarkers().removeMarker(marker); //this.getUiRenderer().update(this.getUiContext(), this.getUiMarkers(), marker, Kekule.Render.ObjectUpdateType.REMOVE); this.repaintUiMarker(); } }, /** * Clear all UI markers. * @private */ clearUiMarkers: function() { this.getUiMarkers().clearMarkers(); //this.getUiRenderer().redraw(this.getUiContext()); //this.redraw(); this.repaintUiMarker(); }, /** * Modify hot track marker to bind to newBoundInfos. * @private */ changeHotTrackMarkerBounds: function(newBoundInfos) { var infos = Kekule.ArrayUtils.toArray(newBoundInfos); //var updateType = Kekule.Render.ObjectUpdateType.MODIFY; var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs(); var drawStyles = { 'color': styleConfigs.getHotTrackerColor(), 'opacity': styleConfigs.getHotTrackerOpacity() }; var inflation = this.getCurrBoundInflation() || this.getEditorConfigs().getInteractionConfigs().getObjBoundTrackMinInflation(); var bounds = []; for (var i = 0, l = infos.length; i < l; ++i) { var boundInfo = infos[i]; var bound = inflation? Kekule.Render.MetaShapeUtils.inflateShape(boundInfo, inflation): boundInfo; //console.log('inflate', bound); if (bound) bounds.push(bound); } var tracker = this.getUiHotTrackMarker(); //console.log('change hot track', bound, drawStyles); tracker.setVisible(true); this.modifyShapeBasedMarker(tracker, bounds, drawStyles, true); return this; }, /** * Hide hot track marker. * @private */ hideHotTrackMarker: function() { var tracker = this.getUiHotTrackMarker(); if (tracker) { this.hideUiMarker(tracker, true); } return this; }, /** * Show hot track marker. * @private */ showHotTrackMarker: function() { var tracker = this.getUiHotTrackMarker(); if (tracker) { this.showUiMarker(tracker, true); } return this; }, ///////////////////////////////////////////////////////////////////////////// // methods about hot track marker /** * Try hot track object on coord. * @param {Hash} screenCoord Coord based on screen system. */ hotTrackOnCoord: function(screenCoord) { if (this.getEditorConfigs().getInteractionConfigs().getEnableHotTrack()) { /* var boundItem = this.getTopmostBoundInfoAtCoord(screenCoord); if (boundItem) // mouse move into object { var obj = boundItem.obj; if (obj) this.setHotTrackedObj(obj); //this.changeHotTrackMarkerBound(boundItem.boundInfo); } else // mouse move out from object { this.setHotTrackedObj(null); } */ //console.log('hot track here'); this.setHotTrackedObj(this.getTopmostBasicObjectAtCoord(screenCoord, this.getCurrBoundInflation())); } return this; }, /** * Hot try on a basic drawn object. * @param {Object} obj */ hotTrackOnObj: function(obj) { this.setHotTrackedObj(obj); return this; }, /** * Remove all hot track markers. * @param {Bool} doNotClearHotTrackedObjs If false, the hotTrackedObjs property will also be set to empty. */ hideHotTrack: function(doNotClearHotTrackedObjs) { this.hideHotTrackMarker(); if (!doNotClearHotTrackedObjs) this.clearHotTrackedObjs(); return this; }, /** * Set hot tracked objects to empty. */ clearHotTrackedObjs: function() { this.setHotTrackedObjs([]); }, /** * Add a obj to hot tracked objects. * @param {Object} obj */ addHotTrackedObj: function(obj) { var olds = this.getHotTrackedObjs() || []; Kekule.ArrayUtils.pushUnique(olds, obj); this.setHotTrackedObjs(olds); return this; }, /** @private */ recalcHotTrackMarker: function() { this.setHotTrackedObjs(this.getHotTrackedObjs()); }, // method about chem object hint /** * Update the hint of chem object. * This method may be called when hovering on some basic objects * @param {String} hint * @private */ updateHintForChemObject: function(hint) { var elem = this.getEditClientElem(); if (elem) { var sHint = hint || ''; if (sHint && this.updateHintForChemObject._cache == sHint) // same as last non-empty hint, must explicitly change hint a little, otherwise the hint may not be displayed in client area { sHint += '\f'; // add a hidden char } elem.title = sHint; if (sHint) this.updateHintForChemObject._cache = sHint; } }, /** * Returns the hint value from a chem object. * Descendants may override this method. * @param {Kekule.ChemObject} obj * @returns {String} */ getChemObjHint: function(obj) { return null; }, /** * Returns the hint value from a set of chem objects. * Descendants may override this method. * @param {Kekule.ChemObject} obj * @returns {String} */ getChemObjsHint: function(objs) { var hints = []; for (var i = 0, l = objs.length; i < l; ++i) { var hint = this.getChemObjHint(objs[i]); if (hint) { // hints.push(hint); AU.pushUnique(hints, hint); // avoid show duplicated hint texts } } // issue hints var issueHints = this._getChemObjsRelatedIssuesHints(objs); if (issueHints.length) { //hints = hints.concat(issueHints); AU.pushUnique(hints, issueHints); // avoid show duplicated hint texts } return hints.length? hints.join('\n'): null; }, /** @private */ _getChemObjsRelatedIssuesHints: function(objs) { var result = []; if (this.getEnableIssueMarkerHint() && this.getEnableIssueCheck()) { var issueItems = this.getObjectsRelatedIssueItems(objs, true) || []; for (var i = 0, l = issueItems.length; i < l; ++i) { var msg = issueItems[i].getMessage(); AU.pushUnique(result, msg); // avoid show duplicated hint texts } } return result; }, // methods about issue markers /** @private */ issueCheckResultsChanged: function() { this.recalcIssueCheckUiMarkers(); var activeIssueResult = this.getActiveIssueCheckResult(); if (activeIssueResult && this.getEnableAutoScrollToActiveIssue()) // need to auto scroll to active issue objects? { var targets = activeIssueResult.getTargets(); if (targets && targets.length) { var objs = this._getExposedSelfOrParentObjs(targets); if (objs && objs.length) { var interState = this.getObjectsBoxAndClientBoxRelation(objs); if (interState !== Kekule.IntersectionState.CONTAINED) this.scrollClientToObject(objs); } } } }, /** @private */ _needShowInactiveIssueMarkers: function() { var result = this.getEnableIssueCheck() && this.getShowAllIssueMarkers(); return result; }, /** @private */ recalcIssueCheckUiMarkers: function() { if (!this.getChemObjLoaded()) // if no content in editor, just bypass return; this.beginUpdateUiMarkers(); try { var checkResults = this.getIssueCheckResults() || []; if (!checkResults.length || !this.getEnableIssueCheck()) this.hideIssueCheckUiMarkers(); else { var showAll = this._needShowInactiveIssueMarkers(); var activeResult = this.getActiveIssueCheckResult(); // hide or show active marker this.getActiveIssueCheckUiMarker().setVisible(!!activeResult); var issueObjGroup = this._groupUpIssueObjects(checkResults, activeResult, true); // only returns exposed objs in editor //var boundGroup = {}; var inflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerInflation(); // TODO: the inflation of issue markers are now borrowed from selection markers var levels = Kekule.ErrorLevel.getAllLevels(); var groupKeys = levels.concat('active'); // Kekule.ObjUtils.getOwnedFieldNames(issueObjGroup); for (var i = 0, ii = groupKeys.length; i < ii; ++i) { var currBounds = []; var key = groupKeys[i]; var group = issueObjGroup[key]; var errorLevel = group? group.level: key; if (group) { var isActive = key === 'active'; if (isActive || showAll) // when showAll is not true, bypass all inactive issue markers { var objs = group.objs; for (var j = 0, jj = objs.length; j < jj; ++j) { var obj = objs[j]; var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj); for (var k = 0, kk = infos.length; k < kk; ++k) { var info = infos[k]; var bound = info.boundInfo; if (bound) { // inflate bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, inflation); currBounds.push(bound); } } } } } this.changeIssueCheckUiMarkerBound(errorLevel, currBounds, isActive); } } } finally { this.endUpdateUiMarkers(); } }, /** @private */ changeIssueCheckUiMarkerBound: function(issueLevel, bounds, isActive) { var marker = isActive? this.getActiveIssueCheckUiMarker(): this.getIssueCheckUiMarker(issueLevel); if (marker) { //console.log(issueLevel, marker, bounds.length); if (bounds && bounds.length) { var levelName = Kekule.ErrorLevel.levelToString(issueLevel); var configs = this.getEditorConfigs().getUiMarkerConfigs(); var styleConfigs = configs.getIssueCheckMarkerColors()[levelName]; var drawStyles = { 'strokeColor': isActive ? styleConfigs.activeStrokeColor : styleConfigs.strokeColor, 'strokeWidth': isActive ? configs.getIssueCheckActiveMarkerStrokeWidth() : configs.getIssueCheckMarkerStrokeWidth(), 'fillColor': isActive ? styleConfigs.activeFillColor : styleConfigs.fillColor, 'opacity': isActive ? configs.getIssueCheckActiveMarkerOpacity() : configs.getIssueCheckMarkerOpacity() }; //console.log(drawStyles); marker.setVisible(true); this.modifyShapeBasedMarker(marker, bounds, drawStyles, true); } else marker.setVisible(false); } return this; }, /** @private */ _getExposedSelfOrParentObjs: function(objs) { var result = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (!obj.isExposed || obj.isExposed()) result.push(obj); else if (obj.getExposedAncestor) { var ancestor = obj.getExposedAncestor(); if (ancestor) result.push(ancestor); } } return result; }, /** @private */ _groupUpIssueObjects: function(checkResults, activeResult, requireExposing) { var result = {}; for (var i = 0, l = checkResults.length; i < l; ++i) { var r = checkResults[i]; var objs = r.getTargets(); var level = r.getLevel(); if (activeResult && r === activeResult) { result['active'] = { 'level': level, 'objs': requireExposing? this._getExposedSelfOrParentObjs(objs): objs }; } else { if (!result[level]) result[level] = {'level': level, 'objs': []}; result[level].objs = result[level].objs.concat(requireExposing ? this._getExposedSelfOrParentObjs(objs) : objs); } } // different error levels have different priorities, a object in higher level need not to be marked in lower level var EL = Kekule.ErrorLevel; var priorities = [EL.LOG, EL.NOTE, EL.WARNING, EL.ERROR, 'active']; for (var i = 0, l = priorities.length; i < l; ++i) { var currPriotyObjs = result[i] && result[i].objs; if (currPriotyObjs) { for (var j = i + 1, k = priorities.length; j < k; ++j) { var highPriotyObjs = result[j] && result[j].objs; if (highPriotyObjs) { var filteredObjs = AU.exclude(currPriotyObjs, highPriotyObjs); result[i].objs = filteredObjs; } } } } return result; }, /** @private */ hideIssueCheckUiMarkers: function() { var markers = this.getAllIssueCheckUiMarkers() || []; for (var i = 0, l = markers.length; i < l; ++i) this.hideUiMarker(markers[i]); }, /** * Check if obj (or its ancestor) is (one of) the targets of issueResult. * @param {Kekule.ChemObject} obj * @param {Kekule.IssueCheck.CheckResult} issueResult * @param {Bool} checkAncestors * @returns {Bool} */ isObjectRelatedToIssue: function(obj, issueResult, checkAncestors) { var targets = issueResult.getTargets() || []; if (targets.indexOf(obj) >= 0) return true; else if (checkAncestors) { var parent = obj.getParent(); return parent? this.isObjectRelatedToIssue(parent, issueResult, checkAncestors): false; } }, /** * Returns the issue items related to obj. * @param {Kekule.ChemObject} obj * @param {Bool} checkAncestors * @returns {Array} */ getObjectIssueItems: function(obj, checkAncestors) { var checkResults = this.getIssueCheckResults() || []; if (!checkResults.length || !this.getEnableIssueCheck()) return []; else { var result = []; for (var i = 0, l = checkResults.length; i < l; ++i) { var item = checkResults[i]; if (this.isObjectRelatedToIssue(obj, item, checkAncestors)) result.push(item); } return result; } }, /** * Returns the issue items related to a series of objects. * @param {Array} objs * @param {Bool} checkAncestors * @returns {Array} */ getObjectsRelatedIssueItems: function(objs, checkAncestors) { var checkResults = this.getIssueCheckResults() || []; if (!checkResults.length || !this.getEnableIssueCheck()) return []; var result = []; // build the while object set that need to check issue items var totalObjs = [].concat(objs); if (checkAncestors) { for (var i = 0, l = objs.length; i < l; ++i) { AU.pushUnique(totalObjs, objs[i].getParentList()); } } for (var i = 0, l = totalObjs.length; i < l; ++i) { var issueItems = this.getObjectIssueItems(totalObjs[i], false); AU.pushUnique(result, issueItems); } return result; }, // methods about selecting marker /** * Modify hot track marker to bind to newBoundInfo. * @private */ changeSelectionAreaMarkerBound: function(newBoundInfo, drawStyles) { var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs(); if (!drawStyles) drawStyles = { 'strokeColor': styleConfigs.getSelectionMarkerStrokeColor(), 'strokeWidth': styleConfigs.getSelectionMarkerStrokeWidth(), 'fillColor': styleConfigs.getSelectionMarkerFillColor(), 'opacity': styleConfigs.getSelectionMarkerOpacity() }; //console.log(drawStyles); var marker = this.getUiSelectionAreaMarker(); if (marker) { marker.setVisible(true); this.modifyShapeBasedMarker(marker, newBoundInfo, drawStyles, true); } return this; }, /** @private */ hideSelectionAreaMarker: function() { var marker = this.getUiSelectionAreaMarker(); if (marker) { this.hideUiMarker(marker, true); } }, /** @private */ showSelectionAreaMarker: function() { var marker = this.getUiSelectionAreaMarker(); if (marker) { this.showUiMarker(marker, true); } }, /** * Recalculate and repaint selection marker. * @private */ recalcSelectionAreaMarker: function(doRepaint) { this.beginUpdateUiMarkers(); try { // debug var selection = this.getSelection(); var count = selection.length; if (count <= 0) this.hideSelectionAreaMarker(); else { var bounds = []; var containerBox = null; var inflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerInflation(); for (var i = 0; i < count; ++i) { var obj = selection[i]; var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj); if (infos && infos.length) { for (var j = 0, k = infos.length; j < k; ++j) { var info = infos[j]; var bound = info.boundInfo; if (bound) { // inflate bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, inflation); bounds.push(bound); var box = Kekule.Render.MetaShapeUtils.getContainerBox(bound); containerBox = containerBox? Kekule.BoxUtils.getContainerBox(containerBox, box): box; } } } } //var containerBox = this.getSelectionContainerBox(inflation); this.setUiSelectionAreaContainerBox(containerBox); // container box if (containerBox) { var containerShape = Kekule.Render.MetaShapeUtils.createShapeInfo( Kekule.Render.MetaShapeType.RECT, [{'x': containerBox.x1, 'y': containerBox.y1}, {'x': containerBox.x2, 'y': containerBox.y2}] ); bounds.push(containerShape); } else // containerBox disappear, may be a node or connector merge, hide selection area this.hideSelectionAreaMarker(); //console.log(bounds.length, bounds); if (bounds.length) this.changeSelectionAreaMarkerBound(bounds); } } finally { this.endUpdateUiMarkers(); } }, /** @private */ _highlightSelectionAreaMarker: function() { var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs(); var highlightStyles = { 'strokeColor': styleConfigs.getSelectionMarkerStrokeColor(), 'strokeWidth': styleConfigs.getSelectionMarkerStrokeWidth(), 'fillColor': styleConfigs.getSelectionMarkerFillColor(), 'opacity': styleConfigs.getSelectionMarkerEmphasisOpacity() }; this.changeSelectionAreaMarkerBound(null, highlightStyles); // change draw styles without the modification of bound }, /** @private */ _restoreSelectionAreaMarker: function() { var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs(); var highlightStyles = { 'strokeColor': styleConfigs.getSelectionMarkerStrokeColor(), 'strokeWidth': styleConfigs.getSelectionMarkerStrokeWidth(), 'fillColor': styleConfigs.getSelectionMarkerFillColor(), 'opacity': styleConfigs.getSelectionMarkerOpacity() }; this.changeSelectionAreaMarkerBound(null, highlightStyles); // change draw styles without the modification of bound }, /** * Pulse selection marker several times to get the attention of user. * @param {Int} duration Duration of the whole process, in ms. * @param {Int} pulseCount The times of highlighting marker. */ pulseSelectionAreaMarker: function(duration, pulseCount) { if (this.getUiSelectionAreaMarker()) { if (!duration) duration = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerDefPulseDuration() || 0; if (!pulseCount) pulseCount = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerDefPulseCount() || 1; if (!duration) return; var interval = duration / pulseCount; this.doPulseSelectionAreaMarker(interval, pulseCount); } return this; }, /** @private */ doPulseSelectionAreaMarker: function(interval, pulseCount) { this._highlightSelectionAreaMarker(); //if (pulseCount <= 1) setTimeout(this._restoreSelectionAreaMarker.bind(this), interval); if (pulseCount > 1) setTimeout(this.doPulseSelectionAreaMarker.bind(this, interval, pulseCount - 1), interval * 2); }, ///////////////////////// Methods about selecting region //////////////////////////////////// /** * Start a selecting operation from coord. * @param {Hash} coord * @param {Bool} toggleFlag If true, the selecting region will toggle selecting state inside it rather than select them directly. */ startSelecting: function(screenCoord, toggleFlag) { if (toggleFlag === undefined) toggleFlag = this.getIsToggleSelectOn(); if (!toggleFlag) this.deselectAll(); var M = Kekule.Editor.SelectMode; var mode = this.getSelectMode(); this._currSelectMode = mode; return (mode === M.POLYLINE || mode === M.POLYGON)? this.startSelectingCurveDrag(screenCoord, toggleFlag): this.startSelectingBoxDrag(screenCoord, toggleFlag); }, /** * Add a new anchor coord of selecting region. * This method is called when pointer device moving in selecting. * @param {Hash} screenCoord */ addSelectingAnchorCoord: function(screenCoord) { var M = Kekule.Editor.SelectMode; var mode = this._currSelectMode; return (mode === M.POLYLINE || mode === M.POLYGON)? this.dragSelectingCurveToCoord(screenCoord): this.dragSelectingBoxToCoord(screenCoord); }, /** * Selecting operation end. * @param {Hash} coord * @param {Bool} toggleFlag If true, the selecting region will toggle selecting state inside it rather than select them directly. */ endSelecting: function(screenCoord, toggleFlag) { if (toggleFlag === undefined) toggleFlag = this.getIsToggleSelectOn(); var M = Kekule.Editor.SelectMode; var mode = this._currSelectMode; var enablePartial = this.getEditorConfigs().getInteractionConfigs().getEnablePartialAreaSelecting(); var objs; if (mode === M.POLYLINE || mode === M.POLYGON) { var polygonCoords = this._selectingCurveCoords; // simplify the polygon first var threshold = this.getEditorConfigs().getInteractionConfigs().getSelectingCurveSimplificationDistanceThreshold(); var simpilfiedCoords = Kekule.GeometryUtils.simplifyCurveToLineSegments(polygonCoords, threshold); //console.log('simplify selection', polygonCoords.length, simpilfiedCoords.length); this.endSelectingCurveDrag(screenCoord, toggleFlag); if (mode === M.POLYLINE) { var lineWidth = this.getEditorConfigs().getInteractionConfigs().getSelectingBrushWidth(); objs = this.getObjectsIntersetExtendedPolyline(simpilfiedCoords, lineWidth); } else // if (mode === M.POLYGON) { objs = this.getObjectsInPolygon(simpilfiedCoords, enablePartial); this.endSelectingCurveDrag(screenCoord, toggleFlag); } } else // M.RECT or M.ANCESTOR { var startCoord = this._selectingBoxStartCoord; var box = Kekule.BoxUtils.createBox(startCoord, screenCoord); objs = this.getObjectsInScreenBox(box, enablePartial); this.endSelectingBoxDrag(screenCoord, toggleFlag); } /* if (objs && objs.length) { if (this._isInAncestorSelectMode()) // need to change to select standalone ancestors { objs = this._getAllStandaloneAncestorObjs(objs); // get standalone ancestors (e.g. molecule) //objs = this._getAllCoordDependantObjs(objs); // but select there coord dependant children (e.g. atoms and bonds) } if (toggleFlag) this.toggleSelectingState(objs); else this.select(objs); } */ objs = this._getActualSelectedObjsInSelecting(objs); if (toggleFlag) this.toggleSelectingState(objs); else this.select(objs); this.hideSelectingMarker(); }, /** * Cancel current selecting operation. */ cancelSelecting: function() { this.hideSelectingMarker(); }, /** @private */ _getActualSelectedObjsInSelecting: function(objs) { if (objs && objs.length) { if (this._isInAncestorSelectMode()) // need to change to select standalone ancestors { objs = this._getAllStandaloneAncestorObjs(objs); // get standalone ancestors (e.g. molecule) //objs = this._getAllCoordDependantObjs(objs); // but select there coord dependant children (e.g. atoms and bonds) } return objs; } else return []; }, /** @private */ _isInAncestorSelectMode: function() { return this.getSelectMode() === Kekule.Editor.SelectMode.ANCESTOR; }, /** @private */ _getAllStandaloneAncestorObjs: function(objs) { var result = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj && obj.getStandaloneAncestor) obj = obj.getStandaloneAncestor(); AU.pushUnique(result, obj); } return result; }, /* @private */ /* _getAllCoordDependantObjs: function(objs) { var result = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj && obj.getCoordDependentObjects) AU.pushUnique(result, obj.getCoordDependentObjects()); } return result; }, */ /** * Start to drag a selecting box from coord. * @param {Hash} coord * @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly. */ startSelectingBoxDrag: function(screenCoord, toggleFlag) { //this.setInteractionStartCoord(screenCoord); this._selectingBoxStartCoord = screenCoord; /* if (!toggleFlag) this.deselectAll(); */ //this.setEditorState(Kekule.Editor.EditorState.SELECTING); }, /** * Drag selecting box to a new coord. * @param {Hash} screenCoord */ dragSelectingBoxToCoord: function(screenCoord) { //var startCoord = this.getInteractionStartCoord(); var startCoord = this._selectingBoxStartCoord; var endCoord = screenCoord; this.changeSelectingMarkerBox(startCoord, endCoord); }, /** * Selecting box drag end. * @param {Hash} coord * @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly. */ endSelectingBoxDrag: function(screenCoord, toggleFlag) { //var startCoord = this.getInteractionStartCoord(); var startCoord = this._selectingBoxStartCoord; //this.setInteractionEndCoord(coord); this._selectingBoxEndCoord = screenCoord; /* var box = Kekule.BoxUtils.createBox(startCoord, screenCoord); var enablePartial = this.getEditorConfigs().getInteractionConfigs().getEnablePartialAreaSelecting(); if (toggleFlag) this.toggleSelectingStateOfObjectsInScreenBox(box, enablePartial); else this.selectObjectsInScreenBox(box, enablePartial); this.hideSelectingMarker(); */ }, /** * Start to drag a selecting curve from coord. * @param {Hash} coord * @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly. */ startSelectingCurveDrag: function(screenCoord, toggleFlag) { //this.setInteractionStartCoord(screenCoord); this._selectingCurveCoords = [screenCoord]; //this.setEditorState(Kekule.Editor.EditorState.SELECTING); }, /** * Drag selecting curve to a new coord. * @param {Hash} screenCoord */ dragSelectingCurveToCoord: function(screenCoord) { //var startCoord = this.getInteractionStartCoord(); this._selectingCurveCoords.push(screenCoord); this.changeSelectingMarkerCurve(this._selectingCurveCoords, this._currSelectMode === Kekule.Editor.SelectMode.POLYGON); }, /** * Selecting curve drag end. * @param {Hash} coord * @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly. */ endSelectingCurveDrag: function(screenCoord, toggleFlag) { this._selectingCurveCoords.push(screenCoord); /* var box = Kekule.BoxUtils.createBox(startCoord, screenCoord); var enablePartial = this.getEditorConfigs().getInteractionConfigs().getEnablePartialAreaSelecting(); if (toggleFlag) this.toggleSelectingStateOfObjectsInScreenBox(box, enablePartial); else this.selectObjectsInScreenBox(box, enablePartial); this.hideSelectingMarker(); */ }, /** * Try select a object on coord directly. * @param {Hash} coord * @param {Bool} toggleFlag If true, the box will toggle selecting state inside it rather than select them directly. */ selectOnCoord: function(coord, toggleFlag) { if (toggleFlag === undefined) toggleFlag = this.getIsToggleSelectOn(); //console.log('select on coord'); var obj = this.getTopmostBasicObjectAtCoord(coord, this.getCurrBoundInflation()); if (obj) { var objs = this._getActualSelectedObjsInSelecting([obj]); if (objs) { if (toggleFlag) this.toggleSelectingState(objs); else this.select(objs); } } }, // about selection area marker /** * Modify hot track marker to bind to newBoundInfo. * @private */ changeSelectingMarkerBound: function(newBoundInfo, drawStyles) { var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs(); if (!drawStyles) // use the default one drawStyles = { 'strokeColor': styleConfigs.getSelectingMarkerStrokeColor(), 'strokeWidth': styleConfigs.getSelectingMarkerStrokeWidth(), 'strokeDash': styleConfigs.getSelectingMarkerStrokeDash(), 'fillColor': styleConfigs.getSelectingMarkerFillColor(), 'opacity': styleConfigs.getSelectingMarkerOpacity() }; var marker = this.getUiSelectingMarker(); marker.setVisible(true); //console.log('change hot track', bound, drawStyles); this.modifyShapeBasedMarker(marker, newBoundInfo, drawStyles, true); return this; }, changeSelectingMarkerCurve: function(screenCoords, isPolygon) { var ctxCoords = []; for (var i = 0, l = screenCoords.length - 1; i < l; ++i) { ctxCoords.push(this.screenCoordToContext(screenCoords[i])); } var shapeInfo = Kekule.Render.MetaShapeUtils.createShapeInfo( isPolygon? Kekule.Render.MetaShapeType.POLYGON: Kekule.Render.MetaShapeType.POLYLINE, ctxCoords ); var drawStyle; if (!isPolygon) { var styleConfigs = this.getEditorConfigs().getUiMarkerConfigs(); drawStyle = { 'strokeColor': styleConfigs.getSelectingBrushMarkerStrokeColor(), 'strokeWidth': this.getEditorConfigs().getInteractionConfigs().getSelectingBrushWidth(), 'strokeDash': styleConfigs.getSelectingBrushMarkerStrokeDash(), //'fillColor': styleConfigs.getSelectingMarkerFillColor(), 'lineCap': styleConfigs.getSelectingBrushMarkerStrokeLineCap(), 'lineJoin': styleConfigs.getSelectingBrushMarkerStrokeLineJoin(), 'opacity': styleConfigs.getSelectingBrushMarkerOpacity() }; } return this.changeSelectingMarkerBound(shapeInfo, drawStyle); }, /** * Change the rect box of selection marker. * Coord is based on screen system. * @private */ changeSelectingMarkerBox: function(screenCoord1, screenCoord2) { //var coord1 = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord1); //var coord2 = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord2); var coord1 = this.screenCoordToContext(screenCoord1); var coord2 = this.screenCoordToContext(screenCoord2); var shapeInfo = Kekule.Render.MetaShapeUtils.createShapeInfo( Kekule.Render.MetaShapeType.RECT, [{'x': Math.min(coord1.x, coord2.x), 'y': Math.min(coord1.y, coord2.y)}, {'x': Math.max(coord1.x, coord2.x), 'y': Math.max(coord1.y, coord2.y)}] ); return this.changeSelectingMarkerBound(shapeInfo); }, /** @private */ hideSelectingMarker: function() { var marker = this.getUiSelectingMarker(); if (marker) { this.hideUiMarker(marker, true); } }, /** @private */ showSelectingMarker: function() { var marker = this.getUiSelectingMarker(); if (marker) { this.showUiMarker(marker, true); } }, // methods about selection marker /** * Returns the region of screenCoord relative to selection marker. * @private */ getCoordRegionInSelectionMarker: function(screenCoord, edgeInflation) { var R = Kekule.Editor.BoxRegion; var CU = Kekule.CoordUtils; var coord = this.screenCoordToContext(screenCoord); var marker = this.getUiSelectionAreaMarker(); if (marker && marker.getVisible()) { var box = this.getUiSelectionAreaContainerBox(); if (Kekule.ObjUtils.isUnset(edgeInflation)) edgeInflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerEdgeInflation(); var halfInf = (edgeInflation / 2) || 0; var coord1 = CU.substract({'x': box.x1, 'y': box.y1}, {'x': halfInf, 'y': halfInf}); var coord2 = CU.add({'x': box.x2, 'y': box.y2}, {'x': halfInf, 'y': halfInf}); if ((coord.x < coord1.x) || (coord.y < coord1.y) || (coord.x > coord2.x) || (coord.y > coord2.y)) return R.OUTSIDE; //coord2 = CU.substract(coord2, coord1); var delta1 = CU.substract(coord, coord1); var delta2 = CU.substract(coord2, coord); var dx1 = delta1.x; var dx2 = delta2.x; var dy1 = delta1.y; var dy2 = delta2.y; if (dy1 < dy2) // on top half { if (dx1 < dx2) // on left part { if (dy1 <= edgeInflation) return (dx1 <= edgeInflation)? R.CORNER_TL: R.EDGE_TOP; else if (dx1 <= edgeInflation) return R.EDGE_LEFT; else return R.INSIDE; } else // on right part { if (dy1 <= edgeInflation) return (dx2 <= edgeInflation)? R.CORNER_TR: R.EDGE_TOP; else if (dx2 <= edgeInflation) return R.EDGE_RIGHT; else return R.INSIDE; } } else // on bottom half { if (dx1 < dx2) // on left part { if (dy2 <= edgeInflation) return (dx1 <= edgeInflation)? R.CORNER_BL: R.EDGE_BOTTOM; else if (dx1 <= edgeInflation) return R.EDGE_LEFT; else return R.INSIDE; } else // on right part { if (dy2 <= edgeInflation) return (dx2 <= edgeInflation)? R.CORNER_BR: R.EDGE_BOTTOM; else if (dx2 <= edgeInflation) return R.EDGE_RIGHT; else return R.INSIDE; } } } return R.OUTSIDE; }, /** * Check if a point coord based on screen inside selection marker. * @private */ isCoordInSelectionMarkerBound: function(screenCoord) { /* //var coord = this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), screenCoord); var coord = this.screenCoordToContext(screenCoord); var marker = this.getUiSelectionAreaMarker(); if (marker && marker.getVisible()) { var shapeInfo = marker.getShapeInfo(); return shapeInfo? Kekule.Render.MetaShapeUtils.isCoordInside(coord, shapeInfo): false; } else return false; */ return (this.getCoordRegionInSelectionMarker(screenCoord) !== Kekule.Editor.BoxRegion.OUTSIDE); }, ////////////////////////////////////////////////////////////////////////////// /////////////////////// methods about selection //////////////////////////// /** * Returns override render options that need to be applied to each selected objects. * Descendants should override this method. * @returns {Hash} * @private */ getObjSelectedRenderOptions: function() { // debug /* if (!this._selectedRenderOptions) this._selectedRenderOptions = {'color': '#000055', 'strokeWidth': 2, 'atomRadius': 5}; */ return this._selectedRenderOptions; }, /** * Returns method to add render option override item of chemObj. * In 2D render mode, this method should returns chemObj.addOverrideRenderOptionItem, * in 3D render mode, this method should returns chemObj.addOverrideRender3DOptionItem. * @private */ _getObjRenderOptionItemAppendMethod: function(chemObj) { return (this.getRenderType() === Kekule.Render.RendererType.R3D)? chemObj.addOverrideRender3DOptionItem: chemObj.addOverrideRenderOptionItem; }, /** * Returns method to remove render option override item of chemObj. * In 2D render mode, this method should returns chemObj.removeOverrideRenderOptionItem, * in 3D render mode, this method should returns chemObj.removeOverrideRender3DOptionItem. * @private */ _getObjRenderOptionItemRemoveMethod: function(chemObj) { return (this.getRenderType() === Kekule.Render.RendererType.R3D )? chemObj.removeOverrideRender3DOptionItem: chemObj.removeOverrideRenderOptionItem; }, /** @private */ _addSelectRenderOptions: function(chemObj) { var selOps = this.getObjSelectedRenderOptions(); if (selOps) { //console.log('_addSelectRenderOptions', chemObj, selOps); var method = this._getObjRenderOptionItemAppendMethod(chemObj); //if (!method) //console.log(chemObj.getClassName()); return method.apply(chemObj, [selOps]); } else return null; }, /** @private */ _removeSelectRenderOptions: function(chemObj) { var selOps = this.getObjSelectedRenderOptions(); if (selOps) { //console.log('_removeSelectRenderOptions', chemObj); var method = this._getObjRenderOptionItemRemoveMethod(chemObj); return method.apply(chemObj, [this.getObjSelectedRenderOptions()]); } else return null; }, /** Notify that a continuous selection update is underway. UI need not to be changed. */ beginUpdateSelection: function() { this.beginUpdateObject(); --this._objSelectFlag; }, /** Notify that a continuous selection update is done. UI need to be changed. */ endUpdateSelection: function() { ++this._objSelectFlag; if (this._objSelectFlag >= 0) { this.selectionChanged(); } this.endUpdateObject(); }, /** Check if the editor is under continuous selection update. */ isUpdatingSelection: function() { return (this._objSelectFlag < 0); }, /** * Notify selection is changed or object in selection has changed. * @private */ selectionChanged: function() { /* var selection = this.getSelection(); if (selection && selection.length) // at least one selected object { var obj, boundItem, bound, box; var containBox; // calc out bound box to contain all selected objects for (var i = 0, l = selection.length; i < l; ++i) { obj = selection[i]; boundItem = this.findBoundMapItem(obj); if (boundItem) { bound = boundItem.boundInfo; if (bound) { box = Kekule.Render.MetaShapeUtils.getContainerBox(bound); if (box) { if (!containBox) containBox = box; else containBox = Kekule.BoxUtils.getContainerBox(containBox, box); } } } } if (containBox) { var inflation = this.getEditorConfigs().getInteractionConfigs().getSelectionMarkerInflation() || 0; if (inflation) containBox = Kekule.BoxUtils.inflateBox(containBox, inflation); this.changeSelectionMarkerBox(containBox); } else // no selected this.removeSelectionMarker(); } else // no selected { this.removeSelectionMarker(); } */ if (!this.isUpdatingSelection()) { this.notifyPropSet('selection', this.getSelection()); this.invokeEvent('selectionChange'); return this.doSelectionChanged(); } }, /** * Do actual work of method selectionChanged. * Descendants may override this method. */ doSelectionChanged: function() { this.recalcSelectionAreaMarker(); }, /** * Check if an object is in selection. * @param {Kekule.ChemObject} obj * @returns {Bool} */ isInSelection: function(obj) { if (!obj) return false; return this.getSelection().indexOf(obj) >= 0; }, /** * Add an object to selection. * Descendants can override this method. * @param {Kekule.ChemObject} obj */ addObjToSelection: function(obj) { if (!obj) return this; var selection = this.getSelection(); Kekule.ArrayUtils.pushUnique(selection, obj.getNearestSelectableObject()); this._addSelectRenderOptions(obj); this.selectionChanged(); return this; }, /** * Remove an object (and all its child objects) from selection. * Descendants can override this method. * @param {Kekule.ChemObject} obj */ removeObjFromSelection: function(obj, doNotNotifySelectionChange) { if (!obj) return this; var selection = this.getSelection(); var relObj = obj.getNearestSelectableObject && obj.getNearestSelectableObject(); if (relObj === obj) relObj === null; Kekule.ArrayUtils.remove(selection, obj); this._removeSelectRenderOptions(obj); if (relObj) { Kekule.ArrayUtils.remove(selection, relObj); this._removeSelectRenderOptions(relObj); } // remove possible child objects for (var i = selection.length - 1; i >= 0; --i) { var remainObj = selection[i]; if (remainObj.isChildOf && (remainObj.isChildOf(obj) || (relObj && remainObj.isChildOf(relObj)))) this.removeObjFromSelection(remainObj, true); } if (!doNotNotifySelectionChange) this.selectionChanged(); return this; }, /** * Select all first-level objects in editor. */ selectAll: function() { var selection = []; var obj = this.getChemObj(); if (obj) { var children = obj.getChildren() || []; if (children.length) selection = children; else selection = [obj]; } return this.select(selection); }, /** * Deselect all objects in selection */ deselectAll: function() { var selection = this.getSelection(); return this.removeFromSelection(selection); }, /** * Make a obj or set of objs be selected. * @param {Variant} objs A object or an array of objects. */ select: function(objs) { this.beginUpdateSelection(); try { this.deselectAll(); this.addToSelection(objs); } finally { //console.log(this.getPainter().getRenderer().getClassName(), this.getPainter().getRenderer().getRenderCache(this.getDrawContext())); this.endUpdateSelection(); } return this; }, /** * Add object or an array of objects to selection. * @param {Variant} param A object or an array of objects. */ addToSelection: function(param) { if (!param) return; var objs = DataType.isArrayValue(param)? param: [param]; this.beginUpdateSelection(); try { for (var i = 0, l = objs.length; i < l; ++i) { this.addObjToSelection(objs[i]); } } finally { this.endUpdateSelection(); } return this; }, /** * Remove object or an array of objects from selection. * @param {Variant} param A object or an array of objects. */ removeFromSelection: function(param) { if (!param || !param.length) return; var objs = DataType.isArrayValue(param)? param: [param]; this.beginUpdateSelection(); try { for (var i = objs.length - 1; i >= 0; --i) { this.removeObjFromSelection(objs[i]); } } finally { this.endUpdateSelection(); } return this; }, /** * Toggle selection state of object or an array of objects. * @param {Variant} param A object or an array of objects. */ toggleSelectingState: function(param) { if (!param) return; var objs = DataType.isArrayValue(param)? param: [param]; this.beginUpdateSelection(); try { for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var relObj = obj.getNearestSelectableObject && obj.getNearestSelectableObject(); if (this.isInSelection(obj)) this.removeObjFromSelection(obj); else if (relObj && this.isInSelection(relObj)) this.removeObjFromSelection(relObj); else this.addObjToSelection(obj); } } finally { this.endUpdateSelection(); } return this; }, /** * Check if there is objects selected currently. * @returns {Bool} */ hasSelection: function() { return !!this.getSelection().length; }, /** * Delete and free all selected objects. */ deleteSelectedObjs: function() { // TODO: unfinished }, /** @private */ requestAutoCheckIssuesIfNecessary: function() { if (this.getEnableAutoIssueCheck()) this._tryCheckIssueOnIdle(); }, /** * Check issues when not updating/manipulating objects in editor. * @private */ _tryCheckIssueOnIdle: function() { //console.log('try check', this.isUpdatingObject(), this.isManipulatingObject()); if (!this.isUpdatingObject() && !this.isManipulatingObject()) { return this.checkIssues(); } else return null; }, /** * Create a default issue check executor instance. * Descendants may override this method. * @returns {Kekule.IssueCheck.Executor} * @private */ createIssueCheckExecutor: function() { return new Kekule.IssueCheck.ExecutorForEditor(this); }, /** * Check potential issues for objects in editor. * @param {Kekule.ChemObject} rootObj Root object to check. If this param is ommited, all objects in editor will be checked. * @returns {Array} Array of error check report result. */ checkIssues: function(rootObj) { var result = null; var root = rootObj || this.getChemObj(); if (root && this.getEnableIssueCheck()) { var checkExecutor = this.getIssueCheckExecutor(true); result = checkExecutor.execute(root); } return result; }, /** * Get all objects interset a polyline defined by a set of screen coords. * Here Object partial in the polyline width range will also be put in result. * @param {Array} polylineScreenCoords * @param {Number} lineWidth * @returns {Array} All interseting objects. */ getObjectsIntersetExtendedPolyline: function(polylineScreenCoords, lineWidth) { var ctxCoords = []; for (var i = 0, l = polylineScreenCoords.length; i < l; ++i) { ctxCoords.push(this.screenCoordToContext(polylineScreenCoords[i])); } var objs = []; var boundInfos = this.getBoundInfoRecorder().getAllRecordedInfoOfContext(this.getObjContext()); var compareFunc = Kekule.Render.MetaShapeUtils.isIntersectingPolyline; for (var i = 0, l = boundInfos.length; i < l; ++i) { var boundInfo = boundInfos[i]; var shapeInfo = boundInfo.boundInfo; /* if (!shapeInfo) console.log(boundInfo); */ if (shapeInfo) if (compareFunc(shapeInfo, ctxCoords, lineWidth)) objs.push(boundInfo.obj); } //console.log('selected', objs); return objs; }, /** * Get all objects inside a polygon defined by a set of screen coords. * @param {Array} polygonScreenCoords * @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected. * @returns {Array} All inside objects. */ getObjectsInPolygon: function(polygonScreenCoords, allowPartialAreaSelecting) { var ctxCoords = []; for (var i = 0, l = polygonScreenCoords.length; i < l; ++i) { ctxCoords.push(this.screenCoordToContext(polygonScreenCoords[i])); } var objs = []; var boundInfos = this.getBoundInfoRecorder().getAllRecordedInfoOfContext(this.getObjContext()); var compareFunc = allowPartialAreaSelecting? Kekule.Render.MetaShapeUtils.isIntersectingPolygon: Kekule.Render.MetaShapeUtils.isInsidePolygon; for (var i = 0, l = boundInfos.length; i < l; ++i) { var boundInfo = boundInfos[i]; var shapeInfo = boundInfo.boundInfo; /* if (!shapeInfo) console.log(boundInfo); */ if (shapeInfo) if (compareFunc(shapeInfo, ctxCoords)) objs.push(boundInfo.obj); } //console.log('selected', objs); return objs; }, /** * Get all objects inside a screen box. * @param {Hash} screenBox * @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected. * @returns {Array} All inside objects. */ getObjectsInScreenBox: function(screenBox, allowPartialAreaSelecting) { var box = this.screenBoxToContext(screenBox); var objs = []; var boundInfos = this.getBoundInfoRecorder().getAllRecordedInfoOfContext(this.getObjContext()); var compareFunc = allowPartialAreaSelecting? Kekule.Render.MetaShapeUtils.isIntersectingBox: Kekule.Render.MetaShapeUtils.isInsideBox; for (var i = 0, l = boundInfos.length; i < l; ++i) { var boundInfo = boundInfos[i]; var shapeInfo = boundInfo.boundInfo; /* if (!shapeInfo) console.log(boundInfo); */ if (shapeInfo) if (compareFunc(shapeInfo, box)) objs.push(boundInfo.obj); } //console.log('selected', objs); return objs; }, /** * Select all objects inside a screen box. * @param {Hash} box * @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected. * @returns {Array} All inside objects. */ selectObjectsInScreenBox: function(screenBox, allowPartialAreaSelecting) { var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting); if (objs && objs.length) this.select(objs); return objs; }, /** * Add objects inside a screen box to selection. * @param {Hash} box * @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be selected. * @returns {Array} All inside objects. */ addObjectsInScreenBoxToSelection: function(screenBox, allowPartialAreaSelecting) { var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting); if (objs && objs.length) this.addToSelection(objs); return objs; }, /** * Remove objects inside a screen box from selection. * @param {Hash} box * @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be deselected. * @returns {Array} All inside objects. */ removeObjectsInScreenBoxFromSelection: function(screenBox, allowPartialAreaSelecting) { var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting); if (objs && objs.length) this.removeFromSelection(objs); return objs; }, /** * Toggle selection state of objects inside a screen box. * @param {Hash} box * @param {Bool} allowPartialAreaSelecting If this value is true, object partial in the box will also be toggled. * @returns {Array} All inside objects. */ toggleSelectingStateOfObjectsInScreenBox: function(screenBox, allowPartialAreaSelecting) { var objs = this.getObjectsInScreenBox(screenBox, allowPartialAreaSelecting); if (objs && objs.length) this.toggleSelectingState(objs); return objs; }, /** * Returns a minimal box (in screen coord system) containing all objects' bounds in editor. * @param {Array} objects * @param {Float} objBoundInflation Inflation of each object's bound. * @returns {Hash} */ getObjectsContainerBox: function(objects, objBoundInflation) { var objs = Kekule.ArrayUtils.toArray(objects); var inf = objBoundInflation || 0; var bounds = []; var containerBox = null; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var infos = this.getBoundInfoRecorder().getBelongedInfos(this.getObjContext(), obj); if (infos && infos.length) { for (var j = 0, k = infos.length; j < k; ++j) { var info = infos[j]; var bound = info.boundInfo; if (bound) { // inflate if (inf) bound = Kekule.Render.MetaShapeUtils.inflateShape(bound, inf); var box = Kekule.Render.MetaShapeUtils.getContainerBox(bound); containerBox = containerBox? Kekule.BoxUtils.getContainerBox(containerBox, box): box; } } } } return containerBox; }, /** * Returns the intersection state of object container box and editor client box. * @param {Array} objs * @returns {Int} Value from {@link Kekule.IntersectionState} */ getObjectsBoxAndClientBoxRelation: function(objs) { var containerBox = this.getObjectsContainerBox(objs); if (containerBox) { var editorBox = this.getVisibleClientScreenBox(); return Kekule.BoxUtils.getIntersectionState(containerBox, editorBox); } }, /** * Returns container box (in screen coord system) that contains all objects in selection. * @param {Number} objBoundInflation * @returns {Hash} */ getSelectionContainerBox: function(objBoundInflation) { return this.getObjectsContainerBox(this.getSelection(), objBoundInflation); }, /** * Returns whether current selected objects can be seen from screen (not all of them * are in hidden scroll area). */ isSelectionVisible: function() { var selectionBox = this.getSelectionContainerBox(); if (selectionBox) { /* var editorDim = this.getClientDimension(); var editorOffset = this.getClientScrollPosition(); var editorBox = { 'x1': editorOffset.x, 'y1': editorOffset.y, 'x2': editorOffset.x + editorDim.width, 'y2': editorOffset.y + editorDim.height }; */ var editorBox = this.getVisibleClientScreenBox(); //console.log(selectionBox, editorBox, Kekule.BoxUtils.getIntersection(selectionBox, editorBox)); return Kekule.BoxUtils.hasIntersection(selectionBox, editorBox); } else return false; }, /////////// methods about object manipulations ///////////////////////////// /** * Returns width and height info of obj. * @param {Object} obj * @returns {Hash} */ getObjSize: function(obj) { return this.doGetObjSize(obj); }, /** * Do actual job of getObjSize. Descendants may override this method. * @param {Object} obj * @returns {Hash} */ doGetObjSize: function(obj) { var coordMode = this.getCoordMode(); //var allowCoordBorrow = this.getAllowCoordBorrow(); return obj.getSizeOfMode? obj.getSizeOfMode(coordMode): null; }, /** * Set dimension of obj. * @param {Object} obj * @param {Hash} size */ setObjSize: function(obj, size) { this.doSetObjSize(obj, size); this.objectChanged(obj); }, /** * Do actual work of setObjSize. * @param {Object} obj * @param {Hash} size */ doSetObjSize: function(obj, dimension) { if (obj.setSizeOfMode) obj.setSizeOfMode(dimension, this.getCoordMode()); }, /** * Returns own coord of obj. * @param {Object} obj * @param {Int} coordPos Value from {@link Kekule.Render.CoordPos}, relative position of coord in object. * @returns {Hash} */ getObjCoord: function(obj, coordPos) { return this.doGetObjCoord(obj, coordPos); }, /** * Do actual job of getObjCoord. Descendants may override this method. * @private */ doGetObjCoord: function(obj, coordPos) { if (!obj) return null; var coordMode = this.getCoordMode(); var allowCoordBorrow = this.getAllowCoordBorrow(); var result = obj.getAbsBaseCoord? obj.getAbsBaseCoord(coordMode, allowCoordBorrow): obj.getAbsCoordOfMode? obj.getAbsCoordOfMode(coordMode, allowCoordBorrow): obj.getCoordOfMode? obj.getCoordOfMode(coordMode, allowCoordBorrow): null; if (coordMode === Kekule.CoordMode.COORD2D && Kekule.ObjUtils.notUnset(coordPos)) // appoint coord pos, need further calculation { var baseCoordPos = Kekule.Render.CoordPos.DEFAULT; if (coordPos !== baseCoordPos) { var allowCoordBorrow = this.getAllowCoordBorrow(); var box = obj.getExposedContainerBox? obj.getExposedContainerBox(coordMode, allowCoordBorrow): obj.getContainerBox? obj.getContainerBox(coordMode, allowCoordBorrow): null; //console.log(obj.getClassName(), coordPos, objBasePos, box); if (box) { if (coordPos === Kekule.Render.CoordPos.CORNER_TL) { var delta = {x: (box.x2 - box.x1) / 2, y: (box.y2 - box.y1) / 2}; result.x = result.x - delta.x; result.y = result.y + delta.y; } } } } return result; /* return obj.getAbsBaseCoord2D? obj.getAbsBaseCoord2D(allowCoordBorrow): obj.getAbsCoord2D? obj.getAbsCoord2D(allowCoordBorrow): obj.getCoord2D? obj.getCoord2D(allowCoordBorrow): null; */ }, /** * Set own coord of obj. * @param {Object} obj * @param {Hash} coord * @param {Int} coordPos Value from {@link Kekule.Render.CoordPos}, relative position of coord in object. */ setObjCoord: function(obj, coord, coordPos) { this.doSetObjCoord(obj, coord, coordPos); this.objectChanged(obj); }, /** * Do actual job of setObjCoord. Descendants can override this method. * @private */ doSetObjCoord: function(obj, coord, coordPos) { var newCoord = Object.create(coord); var coordMode = this.getCoordMode(); //console.log(obj.setAbsBaseCoord, obj.setAbsCoordOfMode, obj.setAbsCoordOfMode); if (coordMode === Kekule.CoordMode.COORD2D && Kekule.ObjUtils.notUnset(coordPos)) // appoint coord pos, need further calculation { //var baseCoordPos = obj.getCoordPos? obj.getCoordPos(coordMode): Kekule.Render.CoordPos.DEFAULT; var baseCoordPos = Kekule.Render.CoordPos.DEFAULT; if (coordPos !== baseCoordPos) { var allowCoordBorrow = this.getAllowCoordBorrow(); var box = obj.getExposedContainerBox? obj.getExposedContainerBox(coordMode, allowCoordBorrow): obj.getContainerBox? obj.getContainerBox(coordMode, allowCoordBorrow): null; //console.log(obj.getClassName(), coordPos, objBasePos, box); if (box) { var delta = {x: (box.x2 - box.x1) / 2, y: (box.y2 - box.y1) / 2}; if (coordPos === Kekule.Render.CoordPos.CORNER_TL) // base coord on center and set coord as top left { newCoord.x = coord.x + delta.x; newCoord.y = coord.y - delta.y; } } } } if (obj.setAbsBaseCoord) { obj.setAbsBaseCoord(newCoord, coordMode); } else if (obj.setAbsCoordOfMode) { obj.setAbsCoordOfMode(newCoord, coordMode); } else if (obj.setAbsCoordOfMode) { obj.setCoordOfMode(newCoord, coordMode); } }, /** * Get object's coord on context. * @param {Object} obj * @returns {Hash} */ getObjectContextCoord: function(obj, coordPos) { var coord = this.getObjCoord(obj, coordPos); return this.objCoordToContext(coord); }, /** * Change object's coord on context. * @param {Object} obj * @param {Hash} contextCoord */ setObjectContextCoord: function(obj, contextCoord, coordPos) { var coord = this.contextCoordToObj(contextCoord); if (coord) this.setObjCoord(obj, coord, coordPos); }, /** * Get object's coord on screen. * @param {Object} obj * @returns {Hash} */ getObjectScreenCoord: function(obj, coordPos) { var coord = this.getObjCoord(obj, coordPos); return this.objCoordToScreen(coord); }, /** * Change object's coord on screen. * @param {Object} obj * @param {Hash} contextCoord */ setObjectScreenCoord: function(obj, screenCoord, coordPos) { var coord = this.screenCoordToObj(screenCoord); if (coord) this.setObjCoord(obj, coord, coordPos); }, /** * Get coord of obj. * @param {Object} obj * @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here. * @returns {Hash} */ getCoord: function(obj, coordSys, coordPos) { /* if (coordSys === Kekule.Render.CoordSystem.CONTEXT) return this.getObjectContextCoord(obj); else return this.getObjCoord(obj); */ var objCoord = this.getObjCoord(obj, coordPos); return this.translateCoord(objCoord, Kekule.Editor.CoordSys.OBJ, coordSys); }, /** * Set coord of obj. * @param {Object} obj * @param {Hash} value * @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here. */ setCoord: function(obj, value, coordSys, coordPos) { /* if (coordSys === Kekule.Render.CoordSystem.CONTEXT) this.setObjectContextCoord(obj, value); else this.setObjCoord(obj, value); */ var objCoord = this.translateCoord(value, coordSys, Kekule.Editor.CoordSys.OBJ); this.setObjCoord(obj, objCoord, coordPos); }, /** * Get size of obj. * @param {Object} obj * @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here. * @returns {Hash} */ getSize: function(obj, coordSys) { var objSize = this.getObjSize(obj); return this.translateCoord(objSize, Kekule.Editor.CoordSys.OBJ, coordSys); }, /** * Set size of obj. * @param {Object} obj * @param {Hash} value * @param {Int} coordSys Value from {@link Kekule.Render.CoordSystem}. Only CONTEXT and CHEM are available here. */ setSize: function(obj, value, coordSys) { var objSize = this.translateCoord(value, coordSys, Kekule.Editor.CoordSys.OBJ); this.setObjSize(obj, objSize); }, // Coord translate methods /* * Translate coord to value of another coord system. * @param {Hash} coord * @param {Int} fromSys * @param {Int} toSys */ /* translateCoord: function(coord, fromSys, toSys) { if (!coord) return null; var S = Kekule.Editor.CoordSys; if (fromSys === S.SCREEN) { if (toSys === S.SCREEN) return coord; else if (toSys === S.CONTEXT) return this.getObjDrawBridge()? this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), coord): coord; else // S.OBJ { var contextCoord = this.getObjDrawBridge()? this.getObjDrawBridge().transformScreenCoordToContext(this.getObjContext(), coord): coord; return this.getObjContext()? this.getRootRenderer().transformCoordToObj(this.getObjContext(), this.getChemObj(), contextCoord): coord; } } else if (fromSys === S.CONTEXT) { if (toSys === S.SCREEN) return this.getObjDrawBridge()? this.getObjDrawBridge().transformContextCoordToScreen(this.getObjContext(), coord): coord; else if (toSys === S.CONTEXT) return coord; else // S.OBJ return this.getObjContext()? this.getRootRenderer().transformCoordToObj(this.getObjContext(), this.getChemObj(), coord): coord; } else // fromSys === S.OBJ { if (toSys === S.SCREEN) { var contextCoord = this.getRootRenderer().transformCoordToContext(this.getObjContext(), this.getChemObj(), coord); return this.getObjDrawBridge()? this.getObjDrawBridge().transformContextCoordToScreen(this.getObjContext(), contextCoord): coord; } else if (toSys === S.CONTEXT) return this.getObjContext()? this.getRootRenderer().transformCoordToContext(this.getObjContext(), this.getChemObj(), coord): coord; else // S.OBJ return coord; } }, */ /* * Translate a distance value to a distance in another coord system. * @param {Hash} coord * @param {Int} fromSys * @param {Int} toSys */ /* translateDistance: function(distance, fromSys, toSys) { var coord0 = {'x': 0, 'y': 0, 'z': 0}; var coord1 = {'x': distance, 'y': 0, 'z': 0}; var transCoord0 = this.translateCoord(coord0, fromSys, toSys); var transCoord1 = this.translateCoord(coord1, fromSys, toSys); return Kekule.CoordUtils.getDistance(transCoord0, transCoord1); }, */ /** * Transform sizes and coords of objects based on coord sys of current editor. * @param {Array} objects * @param {Hash} transformParams * @private */ transformCoordAndSizeOfObjects: function(objects, transformParams) { var coordMode = this.getCoordMode(); var allowCoordBorrow = this.getAllowCoordBorrow(); var matrix = (coordMode === Kekule.CoordMode.COORD3D)? Kekule.CoordUtils.calcTransform3DMatrix(transformParams): Kekule.CoordUtils.calcTransform2DMatrix(transformParams); var childTransformParams = Object.extend({}, transformParams); childTransformParams = Object.extend(childTransformParams, { 'translateX': 0, 'translateY': 0, 'translateZ': 0, 'center': {'x': 0, 'y': 0, 'z': 0} }); var childMatrix = (coordMode === Kekule.CoordMode.COORD3D)? Kekule.CoordUtils.calcTransform3DMatrix(childTransformParams): Kekule.CoordUtils.calcTransform2DMatrix(childTransformParams); for (var i = 0, l = objects.length; i < l; ++i) { var obj = objects[i]; obj.transformAbsCoordByMatrix(matrix, childMatrix, coordMode, true, allowCoordBorrow); obj.scaleSize(transformParams.scale, coordMode, true, allowCoordBorrow); } }, /* * Turn obj coord to context one. * @param {Hash} objCoord * @returns {Hash} */ /* objCoordToContext: function(objCoord) { var S = Kekule.Editor.CoordSys; return this.translateCoord(objCoord, S.OBJ, S.CONTEXT); }, */ /* * Turn context coord to obj one. * @param {Hash} contextCoord * @returns {Hash} */ /* contextCoordToObj: function(contextCoord) { var S = Kekule.Editor.CoordSys; return this.translateCoord(contextCoord, S.CONTEXT, S.OBJ); }, */ /* * Turn obj coord to screen one. * @param {Hash} objCoord * @returns {Hash} */ /* objCoordToScreen: function(objCoord) { var S = Kekule.Editor.CoordSys; return this.translateCoord(objCoord, S.OBJ, S.SCREEN); }, */ /* * Turn screen coord to obj one. * @param {Hash} contextCoord * @returns {Hash} */ /* screenCoordToObj: function(screenCoord) { var S = Kekule.Editor.CoordSys; return this.translateCoord(screenCoord, S.SCREEN, S.OBJ); }, */ /* * Turn screen based coord to context one. * @param {Hash} screenCoord * @returns {Hash} */ /* screenCoordToContext: function(screenCoord) { var S = Kekule.Editor.CoordSys; return this.translateCoord(screenCoord, S.SCREEN, S.CONTEXT); }, */ /* * Turn context based coord to screen one. * @param {Hash} screenCoord * @returns {Hash} */ /* contextCoordToScreen: function(screenCoord) { var S = Kekule.Editor.CoordSys; return this.translateCoord(screenCoord, S.CONTEXT, S.SCREEN); }, */ /* * Turn box coords based on screen system to context one. * @param {Hash} screenCoord * @returns {Hash} */ /* screenBoxToContext: function(screenBox) { var coord1 = this.screenCoordToContext({'x': screenBox.x1, 'y': screenBox.y1}); var coord2 = this.screenCoordToContext({'x': screenBox.x2, 'y': screenBox.y2}); return {'x1': coord1.x, 'y1': coord1.y, 'x2': coord2.x, 'y2': coord2.y}; }, */ /////////////////////////////////////////////////////// /** * Create a default node at coord and append it to parent. * @param {Hash} coord * @param {Int} coordType Value from {@link Kekule.Editor.CoordType} * @param {Kekule.StructureFragment} parent * @returns {Kekule.ChemStructureNode} * @private */ createDefaultNode: function(coord, coordType, parent) { var isoId = this.getEditorConfigs().getStructureConfigs().getDefIsotopeId(); var atom = new Kekule.Atom(); atom.setIsotopeId(isoId); if (parent) parent.appendNode(atom); this.setCoord(atom, coord, coordType); return atom; }, ///////////////////////////////////////////////////////////////////////////// // methods about undo/redo and operation histories /** * Called after a operation is executed or reversed. Notify object has changed. * @param {Object} operation */ operationDone: function(operation) { this.doOperationDone(operation); }, /** * Do actual job of {@link Kekule.Editor.AbstractEditor#operationDone}. Descendants should override this method. * @private */ doOperationDone: function(operation) { // do nothing here }, /** * Pop all operations and empty history list. */ clearOperHistory: function() { var h = this.getOperHistory(); if (h) h.clear(); }, /** * Manually append an operation to the tail of operation history. * @param {Kekule.Operation} operation * @param {Bool} autoExec Whether execute the operation after pushing it. */ pushOperation: function(operation, autoExec) { // console.log('push operation'); if (operation) { var h = this.getOperHistory(); if (h) { h.push(operation); } this.getOperationsInCurrManipulation().push(operation); if (autoExec) { this.beginUpdateObject(); try { operation.execute(); } finally { this.endUpdateObject(); } } } }, /** * Manually pop an operation from the tail of operation history. * @param {Bool} autoReverse Whether undo the operation after popping it. * @returns {Kekule.Operation} Operation popped. */ popOperation: function(autoReverse) { var r; var h = this.getOperHistory(); if (h) { r = h.pop(); if (autoReverse) { this.beginUpdateObject(); try { r.reverse(); } finally { this.endUpdateObject(); } } // if r in operationsInCurrManipulation, removes it var currOpers = this.getOperationsInCurrManipulation(); var index = currOpers.indexOf(r); if (index >= 0) currOpers.splice(index, 1); return r; } else return null; }, /** * Execute an operation in editor. * @param {Kekule.Operation} operation A single operation, or an array of operations. */ execOperation: function(operation) { //this.beginUpdateObject(); var opers = AU.toArray(operation); this.beginManipulateAndUpdateObject(); try { for (var i = 0, l = opers.length; i < l; ++i) { var o = opers[i]; o.execute(); if (this.getEnableOperHistory()) this.pushOperation(o, false); // push but not execute } //operation.execute(); } finally { //this.endUpdateObject(); this.endManipulateAndUpdateObject(); } /* if (this.getEnableOperHistory()) this.pushOperation(operation, false); // push but not execute */ return this; }, /** * Execute a series of operations in editor. * @param {Array} operations */ execOperations: function(opers) { if (opers.length === 1) return this.execOperation(opers[0]); else { var oper = new Kekule.MacroOperation(opers); return this.execOperation(oper); } }, /** * Replace an operation in operation history. * @param {Kekule.Operation} oldOperation * @param {Kekule.Operation} newOperation * @returns {Kekule.Operation} The replaced old operation object. */ replaceOperationInHistory: function(oldOperation, newOperation) { var h = this.getOperHistory(); return h && h.replaceOperation(oldOperation, newOperation); }, /** * Undo last operation. */ undo: function() { var o; var h = this.getOperHistory(); if (h) { this.beginUpdateObject(); try { o = h.undo(); } finally { this.endUpdateObject(); if (o) this.operationDone(o); } } return o; }, /** * Redo last operation. */ redo: function() { var o; var h = this.getOperHistory(); if (h) { this.beginUpdateObject(); try { o = h.redo(); } finally { this.endUpdateObject(); if (o) this.operationDone(o) } } return o; }, /** * Undo all operations. */ undoAll: function() { var o; var h = this.getOperHistory(); if (h) { this.beginUpdateObject(); try { o = h.undoAll(); } finally { this.endUpdateObject(); } } return o; }, /** * Check if an undo action can be taken. * @returns {Bool} */ canUndo: function() { var h = this.getOperHistory(); return h? h.canUndo(): false; }, /** * Check if an undo action can be taken. * @returns {Bool} */ canRedo: function() { var h = this.getOperHistory(); return h? h.canRedo(): false; }, /** * Modify properties of objects in editor. * @param {Variant} objOrObjs A object or an array of objects. * @param {Hash} modifiedPropInfos A hash of property: value pairs. * @param {Bool} putInOperHistory If set to true, the modification will be put into history and can be undone. */ modifyObjects: function(objOrObjs, modifiedPropInfos, putInOperHistory) { var objs = Kekule.ArrayUtils.toArray(objOrObjs); try { var macro = new Kekule.MacroOperation(); for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var oper = new Kekule.ChemObjOperation.Modify(obj, modifiedPropInfos, this); macro.add(oper); } macro.execute(); } finally { if (putInOperHistory && this.getEnableOperHistory() && macro.getChildCount()) this.pushOperation(macro); } return this; }, /** * Modify render options of objects in editor. * @param {Variant} objOrObjs A object or an array of objects. * @param {Hash} modifiedValues A hash of name: value pairs. * @param {Bool} is3DOption Change renderOptions or render3DOptions. * @param {Bool} putInOperHistory If set to true, the modification will be put into history and can be undone. */ modifyObjectsRenderOptions: function(objOrObjs, modifiedValues, is3DOption, putInOperHistory) { var objs = Kekule.ArrayUtils.toArray(objOrObjs); var renderPropName = is3DOption? 'render3DOptions': 'renderOptions'; var getterName = is3DOption? 'getRender3DOptions': 'getRenderOptions'; try { var macro = new Kekule.MacroOperation(); for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj[getterName]) { var old = obj[getterName](); var newOps = Object.extend({}, old); newOps = Object.extend(newOps, modifiedValues); var hash = {}; hash[renderPropName] = newOps; var oper = new Kekule.ChemObjOperation.Modify(obj, hash, this); //oper.execute(); macro.add(oper); } } this.beginManipulateAndUpdateObject(); macro.execute(); } finally { if (putInOperHistory && this.getEnableOperHistory() && macro.getChildCount()) this.pushOperation(macro); this.endManipulateAndUpdateObject(); } return this; }, /** * Returns the dimension of current visible client area of editor. */ getClientDimension: function() { var elem = this.getElement(); return { 'width': elem.clientWidth, 'height': elem.clientHeight }; }, /** * Returns current scroll position of edit client element. * @returns {Hash} {x, y} */ getClientScrollPosition: function() { var elem = this.getEditClientElem().parentNode; return elem? { 'x': elem.scrollLeft, 'y': elem.scrollTop }: null; }, /** * Returns the top left corner coord of client in coordSys. * @param {Int} coordSys * @returns {Hash} */ getClientScrollCoord: function(coordSys) { var screenCoord = this.getClientScrollPosition(); if (OU.isUnset(coordSys) || coordSys === Kekule.Editor.CoordSys.SCREEN) return screenCoord; else return this.translateCoord(screenCoord, Kekule.Editor.CoordSys.SCREEN, coordSys); }, /** * Returns the screen rect/box of editor client element. * @returns {Hash} {x1, y1, x2, y2, left, top, width, height} */ getClientVisibleRect: function() { var result = this.getClientDimension(); var p = this.getClientScrollPosition(); result.x1 = result.left = p.x; result.y1 = result.top = p.y; result.x2 = result.x1 + result.width; result.y2 = result.y1 + result.height; return result; }, /** * Scroll edit client to a position. * @param {Int} yPosition, in px. * @param {Int} xPosition, in px. */ scrollClientTo: function(yPosition, xPosition) { /* var elem = this.getEditClientElem().parentNode; if (Kekule.ObjUtils.notUnset(yPosition)) elem.scrollTop = yPosition; if (Kekule.ObjUtils.notUnset(xPosition)) elem.scrollLeft = xPosition; return this; */ return this.scrollClientToCoord({'y': yPosition, 'x': xPosition}); }, /** * Scroll edit client to top. */ scrollClientToTop: function() { return this.scrollClientTo(0, null); }, /** * Scroll edit client to bottom. */ scrollClientToBottom: function() { var elem = this.getEditClientElem(); var dim = Kekule.HtmlElementUtils.getElemClientDimension(elem); return this.scrollClientTo(dim.height, null); }, /** * Scroll edit client to coord (based on coordSys). * @param {Hash} coord * @param {Int} coordSys If not set, screen coord system will be used. * @param {Hash} options A hash object that contains the options of scrolling. * Currently it may has one field: scrollToCenter. If scrollToCenter is true, * the coord will be at the center of edit area rather than top-left. */ scrollClientToCoord: function(coord, coordSys, options) { var scrollX = OU.notUnset(coord.x); var scrollY = OU.notUnset(coord.y); var scrollToCenter = options && options.scrollToCenter; var screenCoord; if (OU.isUnset(coordSys)) screenCoord = coord; else screenCoord = this.translateCoord(coord, coordSys, Kekule.Editor.CoordSys.SCREEN); if (scrollToCenter) { var visibleClientBox = this.getVisibleClientScreenBox(); var delta = {'x': visibleClientBox.width / 2, 'y': visibleClientBox.height / 2}; screenCoord = Kekule.CoordUtils.substract(screenCoord, delta); } var elem = this.getEditClientElem().parentNode; if (scrollY) elem.scrollTop = screenCoord.y; if (scrollX) elem.scrollLeft = screenCoord.x; return this; }, /** * Scroll edit client to target object or objects in editor. * @param {Variant} targetObjOrObjs Target object or objects array. * @param {Hash} options Scroll options, can including two fields: scrollToCenter, coverMostObjs. * The default value of both of those options are true. */ scrollClientToObject: function(targetObjOrObjs, options) { var BU = Kekule.BoxUtils; if (!targetObjOrObjs) return this; var rootObj = this.getChemObj(); if (!rootObj) return this; var objs = AU.toArray(targetObjOrObjs); /* var containerBoxes = []; var totalContainerBox = null; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj.getExposedContainerBox && obj.isChildOf && obj.isChildOf(rootObj)) { var box = obj.getExposedContainerBox(this.getCoordMode()); if (box) { containerBoxes.push(box); if (!totalContainerBox) totalContainerBox = box; else totalContainerBox = BU.getContainerBox(totalContainerBox, box); } } } */ var boxInfo = this._getTargetObjsExposedContainerBoxInfo(objs, rootObj); var totalContainerBox = boxInfo.totalBox; var containerBoxes = boxInfo.boxes; if (totalContainerBox) { var ops = Object.extend({scrollToCenter: true, coverMostObjs: true}, options || {}); /* var actualBox; // if scroll to centerCoord and none of the obj can be seen in current state, we need another approach var visibleBox = this.getVisibleClientBoxOfSys(Kekule.Editor.CoordSys.CHEM); if (((totalContainerBox.x2 - totalContainerBox.x1 > visibleBox.x2 - visibleBox.x1) || (totalContainerBox.y2 - totalContainerBox.y1 > visibleBox.y2 - visibleBox.y1)) && ops.coverMostObjs) { actualBox = this._getMostIntersectedContainerBox(visibleBox.x2 - visibleBox.x1, visibleBox.y2 - visibleBox.y1, containerBoxes, totalContainerBox); } else actualBox = totalContainerBox; var scrollCoord = ops.scrollToCenter? BU.getCenterCoord(actualBox): {x: actualBox.x1, y: actualBox.y2}; return this.scrollClientToCoord(scrollCoord, Kekule.Editor.CoordSys.CHEM, ops); */ return this._scrollClientToContainerBox(totalContainerBox, containerBoxes, ops); } else return this; }, /** @private */ _scrollClientToContainerBox: function(totalContainerBox, allContainerBoxes, options) { var BU = Kekule.BoxUtils; var actualBox; // if scroll to centerCoord and none of the obj can be seen in current state, we need another approach var visibleBox = this.getVisibleClientBoxOfSys(Kekule.Editor.CoordSys.CHEM); if (((totalContainerBox.x2 - totalContainerBox.x1 > visibleBox.x2 - visibleBox.x1) || (totalContainerBox.y2 - totalContainerBox.y1 > visibleBox.y2 - visibleBox.y1)) && options.coverMostObjs) { actualBox = this._getMostIntersectedContainerBox(visibleBox.x2 - visibleBox.x1, visibleBox.y2 - visibleBox.y1, allContainerBoxes, totalContainerBox); } else actualBox = totalContainerBox; var scrollCoord = options.scrollToCenter? BU.getCenterCoord(actualBox): {x: actualBox.x1, y: actualBox.y2}; return this.scrollClientToCoord(scrollCoord, Kekule.Editor.CoordSys.CHEM, options); }, /** * Returns the exposed container box of each object and the total container box. * @param {Array} objs * @returns {Hash} * @private */ _getTargetObjsExposedContainerBoxInfo: function(objs, rootObj) { var BU = Kekule.BoxUtils; if (!rootObj) rootObj = this.getChemObj(); if (rootObj) { var totalContainerBox = null; var containerBoxes = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj.getExposedContainerBox && obj.isChildOf && obj.isChildOf(rootObj)) { var box = obj.getExposedContainerBox(this.getCoordMode()); if (box) { containerBoxes.push(box); if (!totalContainerBox) totalContainerBox = box; else totalContainerBox = BU.getContainerBox(totalContainerBox, box); } } } } return {'totalBox': totalContainerBox, 'boxes': containerBoxes}; }, /** @private */ _getMostIntersectedContainerBox: function(width, height, boxes, totalContainerBox) { var BU = Kekule.BoxUtils; var generateTestBox = function(startingCoord, directions) { var endingCoord = CU.add(startingCoord, {'x': width * directions.x, 'y': height * directions.y}); if (endingCoord.x < totalContainerBox.x1) endingCoord.x = totalContainerBox.x1; else if (endingCoord.x > totalContainerBox.x2) endingCoord.x = totalContainerBox.x2; if (endingCoord.y < totalContainerBox.y1) endingCoord.y = totalContainerBox.y1; else if (endingCoord.y > totalContainerBox.y2) endingCoord.y = totalContainerBox.y2; var actualStartingCoord = CU.add(endingCoord, {'x': -width * directions.x, 'y': -height * directions.y}); var result = BU.createBox(actualStartingCoord, endingCoord); return result; }; var getIntersectedBoxCount = function(testBox, boxes) { var result = 0; for (var i = 0, l = boxes.length; i < l; ++i) { var box = boxes[i]; if (BU.hasIntersection(box, testBox)) ++result; } return result; }; var maxIntersectCount = 0; var currContainerBox; for (var i = 0, l = boxes.length; i < l; ++i) { var corners = BU.getCornerCoords(boxes[i]); var testBoxes = [ generateTestBox(corners[0], {x: 1, y: 1}), generateTestBox(corners[1], {x: 1, y: -1}), generateTestBox(corners[2], {x: -1, y: 1}), generateTestBox(corners[3], {x: -1, y: -1}), ]; for (var j = 0, k = testBoxes.length; j < k; ++j) { var count = getIntersectedBoxCount(testBoxes[j], boxes); if (count > maxIntersectCount) { maxIntersectCount = count; currContainerBox = testBoxes[j]; } } } return currContainerBox; }, /////// Event handle ////////////////////// /** @ignore */ doBeforeDispatchUiEvent: function(/*$super, */e) { // get pointer type information here var evType = e.getType(); if (['pointerdown', 'pointermove', 'pointerup'].indexOf(evType) >= 0) { this.setCurrPointerType(e.pointerType); if (evType === 'pointermove' && this.isRenderable()) { var coord = this._getEventMouseCoord(e, this.getCoreElement()); // coord based on editor client element var hoveredObjs = this.getBasicObjectsAtCoord(coord, this.getCurrBoundInflation()) || []; var oldHoveredObjs = this.getHoveredBasicObjs(); this.setPropStoreFieldValue('hoveredBasicObjs', hoveredObjs); // if there are differences between oldHoveredObjs and hoveredObjs if (!oldHoveredObjs || hoveredObjs.length !== oldHoveredObjs.length || AU.intersect(oldHoveredObjs, hoveredObjs).length !== hoveredObjs.length) { this.notifyHoverOnObjs(hoveredObjs); } } } return this.tryApplySuper('doBeforeDispatchUiEvent', [e]) /* $super(e) */; }, /** * Called when the pointer hover on/off objects. * @param {Array} hoveredObjs An empty array means move out off objects. * @private */ notifyHoverOnObjs: function(hoveredObjs) { // when hovering on objects, update the chem object hint of editor var hint = this.getChemObjsHint(hoveredObjs); this.updateHintForChemObject(hint); this.invokeEvent('hoverOnObjs', {'objs': hoveredObjs}); }, /** * React to a HTML event to find if it is a registered hotkey, then react to it when necessary. * @param {HTMLEvent} e * @returns {Bool} Returns true if a hot key is found and handled. * @private */ reactHotKeys: function(e) { var editor = this; // react to hotkeys if (this.getEditorConfigs().getInteractionConfigs().getEnableHotKey()) { var hotKeys = this.getEditorConfigs().getHotKeyConfigs().getHotKeys(); var srcParams = Kekule.Widget.KeyboardUtils.getKeyParamsFromEvent(e); var done = false; var pendingOperations = []; for (var i = hotKeys.length - 1; i >= 0; --i) { var keyParams = Kekule.Widget.KeyboardUtils.shortcutLabelToKeyParams(hotKeys[i].key, null, false); keyParams.repeat = hotKeys[i].repeat; if (Kekule.Widget.KeyboardUtils.matchKeyParams(srcParams, keyParams, false)) // not strict match { var actionId = hotKeys[i].action; if (actionId) { var action = editor.getChildAction(actionId, true); if (action) { if (action instanceof Kekule.Editor.ActionOperationCreate.Base) // operation creation actions, handles differently { var opers = action.createOperations(editor); done = !!(opers && opers.length) || done; if (done) pendingOperations = pendingOperations.concat(opers); } else done = action.execute(editor, e) || done; } } } } if (pendingOperations.length) editor.execOperations(pendingOperations); if (done) { e.stopPropagation(); e.preventDefault(); return true; // already do the modification, returns a flag } } }, /** @ignore */ react_keydown: function(e) { var handled = this.tryApplySuper('react_keydown', [e]); if (!handled) return this.reactHotKeys(e); } }); /** * A special class to give a setting facade for BaseEditor. * Do not use this class alone. * @class * @augments Kekule.ChemWidget.ChemObjDisplayer.Settings * @ignore */ Kekule.Editor.BaseEditor.Settings = Class.create(Kekule.ChemWidget.ChemObjDisplayer.Settings, /** @lends Kekule.Editor.BaseEditor.Settings# */ { /** @private */ CLASS_NAME: 'Kekule.Editor.BaseEditor.Settings', /** @private */ initProperties: function() { this.defineProp('enableCreateNewDoc', {'dataType': DataType.BOOL, 'serializable': false, 'getter': function() { return this.getEditor().getEnableCreateNewDoc(); }, 'setter': function(value) { this.getEditor().setEnableCreateNewDoc(value); } }); this.defineProp('initOnNewDoc', {'dataType': DataType.BOOL, 'serializable': false, 'getter': function() { return this.getEditor().getInitOnNewDoc(); }, 'setter': function(value) { this.getEditor().setInitOnNewDoc(value); } }); this.defineProp('enableOperHistory', {'dataType': DataType.BOOL, 'serializable': false, 'getter': function() { return this.getEditor().getEnableOperHistory(); }, 'setter': function(value) { this.getEditor().setEnableOperHistory(value); } }); this.defineProp('enableIssueCheck', {'dataType': DataType.BOOL, 'serializable': false, 'getter': function() { return this.getEditor().getEnableIssueCheck(); }, 'setter': function(value) { this.getEditor().setEnableIssueCheck(value); } }); }, /** @private */ getEditor: function() { return this.getDisplayer(); } }); /** * A class to register all available IA controllers for editor. * @class */ Kekule.Editor.IaControllerManager = { /** @private */ _controllerMap: new Kekule.MapEx(true), /** * Register a controller, the controller can be used in targetEditorClass or its descendants. * @param {Class} controllerClass * @param {Class} targetEditorClass */ register: function(controllerClass, targetEditorClass) { ICM._controllerMap.set(controllerClass, targetEditorClass); }, /** * Unregister a controller. * @param {Class} controllerClass */ unregister: function(controllerClass) { ICM._controllerMap.remove(controllerClass); }, /** * Returns all registered controller classes. * @returns {Array} */ getAllControllerClasses: function() { return ICM._controllerMap.getKeys(); }, /** * Returns controller classes can be used for editorClass. * @param {Class} editorClass * @returns {Array} */ getAvailableControllerClasses: function(editorClass) { var result = []; var controllerClasses = ICM.getAllControllerClasses(); for (var i = 0, l = controllerClasses.length; i < l; ++i) { var cc = controllerClasses[i]; var ec = ICM._controllerMap.get(cc); if (!ec || ClassEx.isOrIsDescendantOf(editorClass, ec)) result.push(cc); } return result; } }; var ICM = Kekule.Editor.IaControllerManager; /** * Base controller class for BaseEditor. * This is a base class and should not be used directly. * @class * @augments Kekule.Widget.InteractionController * * @param {Kekule.Editor.BaseEditor} editor Editor of current object being installed to. */ Kekule.Editor.BaseEditorBaseIaController = Class.create(Kekule.Widget.InteractionController, /** @lends Kekule.Editor.BaseEditorBaseIaController# */ { /** @private */ CLASS_NAME: 'Kekule.Editor.BaseEditorIaController', /** @constructs */ initialize: function(/*$super, */editor) { this.tryApplySuper('initialize', [editor]) /* $super(editor) */; }, /** @private */ _defineEditorConfigBasedProperty: function(propName, configPath, options) { var defOps = { 'dataType': DataType.VARIANT, 'serializable': false, /* 'setter': function(value) { var configs = this.getEditorConfigs(); configs.setCascadePropValue(configPath, value); } */ 'setter': null }; if (options && options.overwrite) { defOps.getter = function () { var v = this.getPropStoreFieldValue(propName); var configs = this.getEditorConfigs(); return v && configs.getCascadePropValue(configPath); }; defOps.setter = function(value) { this.setPropStoreFieldValue(propName, value); } } else { defOps.getter = function () { var configs = this.getEditorConfigs(); return configs.getCascadePropValue(configPath); }; } var ops = Object.extend(defOps, options || {}); this.defineProp(propName, ops); }, /** * Returns the preferred id for this controller. */ getDefId: function() { return Kekule.ClassUtils.getLastClassName(this.getClassName()); }, /** * Return associated editor. * @returns {Kekule.ChemWidget.BaseEditor} */ getEditor: function() { return this.getWidget(); }, /** * Set associated editor. * @param {Kekule.ChemWidget.BaseEditor} editor */ setEditor: function(editor) { return this.setWidget(editor); }, /** * Get config object of editor. * @returns {Object} */ getEditorConfigs: function() { var editor = this.getEditor(); return editor? editor.getEditorConfigs(): null; } }); /** * Base Controller class for editor. * @class * @augments Kekule.Editor.BaseEditorBaseIaController * * @param {Kekule.Editor.BaseEditor} editor Editor of current object being installed to. * * @property {Bool} manuallyHotTrack If set to false, hot track will be auto shown in mousemove event listener. */ Kekule.Editor.BaseEditorIaController = Class.create(Kekule.Editor.BaseEditorBaseIaController, /** @lends Kekule.Editor.BaseEditorIaController# */ { /** @private */ CLASS_NAME: 'Kekule.Editor.BaseEditorIaController', /** @constructs */ initialize: function(/*$super, */editor) { this.tryApplySuper('initialize', [editor]) /* $super(editor) */; }, initProperties: function() { this.defineProp('manuallyHotTrack', {'dataType': DataType.BOOL, 'serializable': false}); // in mouse or touch interaction, we may have different bound inflation this.defineProp('currBoundInflation', {'dataType': DataType.NUMBER, 'serializable': false, 'getter': function() { return this.getEditor().getCurrBoundInflation(); }, 'setter': null // function(value) { return this.getEditor().setCurrBoundInflation(value); } }); this.defineProp('activePointerType', {'dataType': DataType.BOOL, 'serializable': false, 'getter': function() { var editor = this.getEditor(); return (editor && editor.getCurrPointerType()) || this.getPropStoreFieldValue('activePointerType'); }, 'setter': function(value) { var editor = this.getEditor(); if (editor) editor.setCurrPointerType(value); else this.setStoreFieldValue('activePointerType', value); } }); // private }, /** * Call the beginManipulateObjects method of editor. * @private */ notifyEditorBeginManipulateObjects: function() { var editor = this.getEditor(); editor.beginManipulateObject(); }, /** * Call the endManipulateObjects method of editor. * @private */ notifyEditorEndManipulateObjects: function() { var editor = this.getEditor(); editor.endManipulateObject(); }, /** @private */ getInteractionBoundInflation: function(pointerType) { return this.getEditor().getInteractionBoundInflation(pointerType); }, /** @ignore */ handleUiEvent: function(/*$super, */e) { var handle = false; var targetElem = (e.getTarget && e.getTarget()) || e.target; // hammer event does not have getTarget method var uiElem = this.getEditor().getUiEventReceiverElem(); if (uiElem) { // only handles event on event receiver element // otherwise scrollbar on editor may cause problem if ((targetElem === uiElem) || Kekule.DomUtils.isDescendantOf(targetElem, uiElem)) handle = true; } else handle = true; if (handle) this.tryApplySuper('handleUiEvent', [e]) /* $super(e) */; }, /** * Returns if this IaController can interact with obj. * If true, when mouse moving over obj, a hot track marker will be drawn. * Descendants should override this method. * @param {Object} obj * @return {Bool} * @private */ canInteractWithObj: function(obj) { return !!obj; }, /** * Returns all interactable object classes for this IA controller in editor. * If can interact will all objects, simply returns null. * Descendants may override this method. * @private */ getInteractableTargetClasses: function() { return null; }, /* @private */ getAllInteractableObjsAtScreenCoord: function(coord) { return this.getEditor().getBasicObjectsAtCoord(coord, this.getCurrBoundInflation(), null, this.getInteractableTargetClasses()); }, /** @private */ getTopmostInteractableObjAtScreenCoord: function(coord) { var objs = this.getAllInteractableObjsAtScreenCoord(coord); if (objs) { for (var i = 0, l = objs.length; i < l; ++i) { if (this.canInteractWithObj(objs[i])) return objs[i]; } } return null; }, /** @private */ getTopmostInteractableObjAtCurrPointerPos: function() { var objs = this.getEditor().getHoveredBasicObjs(); if (objs) { for (var i = 0, l = objs.length; i < l; ++i) { if (this.canInteractWithObj(objs[i])) return objs[i]; } } return null; }, /** * Show a hot track marker on obj in editor. * @param {Kekule.ChemObject} obj */ hotTrackOnObj: function(obj) { this.getEditor().hotTrackOnObj(obj); }, // zoom functions /** @private */ zoomEditor: function(zoomLevel, zoomCenterCoord) { if (zoomLevel > 0) this.getEditor().zoomIn(zoomLevel, zoomCenterCoord); else if (zoomLevel < 0) this.getEditor().zoomOut(-zoomLevel, zoomCenterCoord); }, /** @private */ /* updateCurrBoundInflation: function(evt) { */ /* var editor = this.getEditor(); var pointerType = evt && evt.pointerType; var iaConfigs = this.getEditorConfigs().getInteractionConfigs(); var defRatio = iaConfigs.getObjBoundTrackInflationRatio(); var currRatio, ratioValue; if (pointerType === 'mouse') currRatio = iaConfigs.getObjBoundTrackInflationRatioMouse(); else if (pointerType === 'pen') currRatio = iaConfigs.getObjBoundTrackInflationRatioPen(); else if (pointerType === 'touch') currRatio = iaConfigs.getObjBoundTrackInflationRatioTouch(); currRatio = currRatio || defRatio; if (currRatio) { var bondScreenLength = editor.getDefBondScreenLength(); ratioValue = bondScreenLength * currRatio; } var defMinValue = iaConfigs.getObjBoundTrackMinInflation(); var currMinValue; if (pointerType === 'mouse') currMinValue = iaConfigs.getObjBoundTrackMinInflationMouse(); else if (pointerType === 'pen') currMinValue = iaConfigs.getObjBoundTrackMinInflationPen(); else if (pointerType === 'touch') currMinValue = iaConfigs.getObjBoundTrackMinInflationTouch(); currMinValue = currMinValue || defMinValue; var actualValue = Math.max(ratioValue || 0, currMinValue); */ /* //this.setCurrBoundInflation(actualValue); var value = this.getEditor().getInteractionBoundInflation(evt && evt.pointerType); this.setCurrBoundInflation(value); //console.log('update bound inflation', pointerType, this.getCurrBoundInflation()); }, */ /** @private */ _filterBasicObjectsInEditor: function(objs) { var editor = this.getEditor(); var rootObj = editor.getChemObj(); var result = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj.isChildOf(rootObj)) result.push(obj); } return result; }, /** * Notify the manipulation is done and objs are inserted into or modified in editor. * This method should be called by descendants at the end of their manipulation. * Objs will be automatically selected if autoSelectNewlyInsertedObjects option is true. * @param {Array} objs * @private */ doneInsertOrModifyBasicObjects: function(objs) { if (this.needAutoSelectNewlyInsertedObjects()) { var filteredObjs = this._filterBasicObjectsInEditor(objs); this.getEditor().select(filteredObjs); } }, /** @private */ needAutoSelectNewlyInsertedObjects: function() { var pointerType = this.getActivePointerType(); var ic = this.getEditorConfigs().getInteractionConfigs(); return (ic.getAutoSelectNewlyInsertedObjectsOnTouch() && pointerType === 'touch') || ic.getAutoSelectNewlyInsertedObjects(); }, /** @private */ react_pointerdown: function(e) { //this.updateCurrBoundInflation(e); //this.getEditor().setCurrPointerType(e.pointerType); this.setActivePointerType(e.pointerType); e.preventDefault(); return true; }, /** @private */ react_pointermove: function(e) { //if (!this.getCurrBoundInflation()) //this.updateCurrBoundInflation(e); //this.getEditor().setCurrPointerType(e.pointerType); //console.log(e.getTarget().id); /* var coord = this._getEventMouseCoord(e); var obj = this.getTopmostInteractableObjAtScreenCoord(coord); */ var obj = this.getTopmostInteractableObjAtCurrPointerPos(); // read the hovered obj directly from the editor's cached property if (!this.getManuallyHotTrack()) { /* if (obj) console.log('point to', obj.getClassName(), obj.getId()); */ if (obj /* && this.canInteractWithObj(obj)*/) // canInteractWithObj check now already done in getTopmostInteractableObjAtScreenCoord { this.hotTrackOnObj(obj); } else { this.hotTrackOnObj(null); } //e.preventDefault(); } e.preventDefault(); return true; }, /** @private */ react_mousewheel: function(e) { if (e.getCtrlKey()) { var currScreenCoord = this._getEventMouseCoord(e); //this.getEditor().setZoomCenter(currScreenCoord); try { var delta = e.wheelDeltaY || e.wheelDelta; if (delta) delta /= 120; //console.log('zoom', this.getEditor().getZoomCenter()) this.zoomEditor(delta, currScreenCoord); } finally { //this.getEditor().setZoomCenter(null); } e.preventDefault(); return true; } }, /** @private */ _getEventMouseCoord: function(/*$super, */e, clientElem) { var elem = clientElem || this.getWidget().getCoreElement(); // defaultly base on client element, not widget element return this.tryApplySuper('_getEventMouseCoord', [e, elem]) /* $super(e, elem) */; } }); /** * Controller for drag and scroll (by mouse, touch...) client element in editor. * @class * @augments Kekule.Widget.BaseEditorIaController * * @param {Kekule.Editor.BaseEditor} widget Editor of current object being installed to. */ Kekule.Editor.ClientDragScrollIaController = Class.create(Kekule.Editor.BaseEditorIaController, /** @lends Kekule.Editor.ClientDragScrollIaController# */ { /** @private */ CLASS_NAME: 'Kekule.Editor.ClientDragScrollIaController', /** @constructs */ initialize: function(/*$super, */widget) { this.tryApplySuper('initialize', [widget]) /* $super(widget) */; this._isExecuting = false; }, /** @ignore */ canInteractWithObj: function(obj) { return false; // do not interact directly with objects in editor }, /** @ignore */ doTestMouseCursor: function(coord, e) { //console.log(this.isExecuting(), coord); return this.isExecuting()? ['grabbing', '-webkit-grabbing', '-moz-grabbing', 'move']: ['grab', '-webkit-grab', '-moz-grab', 'pointer']; //return this.isExecuting()? '-webkit-grabbing': '-webkit-grab'; }, /** @private */ isExecuting: function() { return this._isExecuting; }, /** @private */ startScroll: function(screenCoord) { this._startCoord = screenCoord; this._originalScrollPos = this.getEditor().getClientScrollPosition(); this._isExecuting = true; }, /** @private */ endScroll: function() { this._isExecuting = false; this._startCoord = null; this._originalScrollPos = null; }, /** @private */ scrollTo: function(screenCoord) { if (this.isExecuting()) { var startCoord = this._startCoord; var delta = Kekule.CoordUtils.substract(startCoord, screenCoord); var newScrollPos = Kekule.CoordUtils.add(this._originalScrollPos, delta); this.getEditor().scrollClientTo(newScrollPos.y, newScrollPos.x); // note the params of this method is y, x } }, /** @private */ react_pointerdown: function(e) { this.setActivePointerType(e.pointerType); if (e.getButton() === Kekule.X.Event.MouseButton.LEFT) // begin scroll { if (!this.isExecuting()) { var coord = {x: e.getScreenX(), y: e.getScreenY()}; this.startScroll(coord); e.preventDefault(); } } else if (e.getButton() === Kekule.X.Event.MouseButton.RIGHT) { if (this.isExecuting()) { this.endScroll(); e.preventDefault(); } } }, /** @private */ react_pointerup: function(e) { if (e.getButton() === Kekule.X.Event.MouseButton.LEFT) { if (this.isExecuting()) { this.endScroll(); e.preventDefault(); } } }, /** @private */ react_pointermove: function(/*$super, */e) { this.tryApplySuper('react_pointermove', [e]) /* $super(e) */; if (this.isExecuting()) { var coord = {x: e.getScreenX(), y: e.getScreenY()}; this.scrollTo(coord); e.preventDefault(); } return true; } }); /** @ignore */ Kekule.Editor.IaControllerManager.register(Kekule.Editor.ClientDragScrollIaController, Kekule.Editor.BaseEditor); /** * Controller for deleting objects in editor. * @class * @augments Kekule.Widget.BaseEditorIaController * * @param {Kekule.Editor.BaseEditor} widget Editor of current object being installed to. */ Kekule.Editor.BasicEraserIaController = Class.create(Kekule.Editor.BaseEditorIaController, /** @lends Kekule.Editor.BasicEraserIaController# */ { /** @private */ CLASS_NAME: 'Kekule.Editor.BasicEraserIaController', /** @constructs */ initialize: function(/*$super, */widget) { this.tryApplySuper('initialize', [widget]) /* $super(widget) */; this._isExecuting = false; }, /** @ignore */ canInteractWithObj: function(obj) { return !!obj; // every thing can be deleted }, //methods about remove /** @private */ removeObjs: function(objs) { if (objs && objs.length) { var editor = this.getEditor(); editor.beginUpdateObject(); try { var actualObjs = this.doGetActualRemovedObjs(objs); this.doRemoveObjs(actualObjs); } finally { editor.endUpdateObject(); } } }, /** @private */ doRemoveObjs: function(objs) { // do actual remove job }, doGetActualRemovedObjs: function(objs) { return objs; }, /** * Remove selected objects in editor. */ removeSelection: function() { var editor = this.getEditor(); this.removeObjs(editor.getSelection()); // the selection is currently empty editor.deselectAll(); }, /** * Remove object on screen coord. * @param {Hash} coord */ removeOnScreenCoord: function(coord) { var obj = this.getEditor().getTopmostBasicObjectAtCoord(coord); if (obj) { this.removeObjs([obj]); return true; } else return false; }, /** @private */ startRemove: function() { this._isExecuting = true; }, /** @private */ endRemove: function() { this._isExecuting = false; }, /** @private */ isRemoving: function() { return this._isExecuting; }, /** @ignore */ reactUiEvent: function(/*$super, */e) { var result = this.tryApplySuper('reactUiEvent', [e]) /* $super(e) */; var evType = e.getType(); // prevent default touch action (may change UI) in mobile browsers if (['touchstart', 'touchend', 'touchcancel', 'touchmove'].indexOf(evType) >= 0) e.preventDefault(); return result; }, /** @private */ react_pointerdown: function(e) { this.setActivePointerType(e.pointerType); if (e.getButton() === Kekule.X.Event.MOUSE_BTN_LEFT) { this.startRemove(); var coord = this._getEventMouseCoord(e); this.removeOnScreenCoord(coord); e.preventDefault(); } else if (e.getButton() === Kekule.X.Event.MOUSE_BTN_RIGHT) { this.endRemove(); e.preventDefault(); } }, /** @private */ react_pointerup: function(e) { if (e.getButton() === Kekule.X.Event.MOUSE_BTN_LEFT) { this.endRemove(); e.preventDefault(); } }, /** @private */ react_pointermove: function(/*$super, */e) { this.tryApplySuper('react_pointermove', [e]) /* $super(e) */; if (this.isRemoving()) { var coord = this._getEventMouseCoord(e); this.removeOnScreenCoord(coord); e.preventDefault(); } return true; } }); /** @ignore */ Kekule.Editor.IaControllerManager.register(Kekule.Editor.BasicEraserIaController, Kekule.Editor.BaseEditor); /** * Controller for selecting, moving or rotating objects in editor. * @class * @augments Kekule.Widget.BaseEditorIaController * * @param {Kekule.Editor.BaseEditor} widget Editor of current object being installed to. * * @property {Int} selectMode Set the selectMode property of editor. * @property {Bool} enableSelect Whether select function is enabled. * @property {Bool} enableMove Whether move function is enabled. * //@property {Bool} enableRemove Whether remove function is enabled. * @property {Bool} enableResize Whether resize of selection is allowed. * @property {Bool} enableRotate Whether rotate of selection is allowed. * @property {Bool} enableGestureManipulation Whether rotate and resize by touch gestures are allowed. */ Kekule.Editor.BasicManipulationIaController = Class.create(Kekule.Editor.BaseEditorIaController, /** @lends Kekule.Editor.BasicManipulationIaController# */ { /** @private */ CLASS_NAME: 'Kekule.Editor.BasicManipulationIaController', /** @constructs */ initialize: function(/*$super, */widget) { this.tryApplySuper('initialize', [widget]) /* $super(widget) */; this.setState(Kekule.Editor.BasicManipulationIaController.State.NORMAL); /* this.setEnableSelect(false); this.setEnableGestureManipulation(false); this.setEnableMove(true); this.setEnableResize(true); this.setEnableAspectRatioLockedResize(true); this.setEnableRotate(true); */ this._suppressConstrainedResize = false; this._manipulationStepBuffer = {}; this._suspendedOperations = null; this.execManipulationStepBind = this.execManipulationStep.bind(this); }, /** @private */ initProperties: function() { this.defineProp('selectMode', {'dataType': DataType.INT, 'serializable': false}); this.defineProp('enableSelect', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('enableMove', {'dataType': DataType.BOOL, 'serializable': false}); //this.defineProp('enableRemove', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('enableResize', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('enableRotate', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('enableGestureManipulation', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('state', {'dataType': DataType.INT, 'serializable': false}); // the screen coord that start this manipulation, since startCoord may be changed during rotation, use this // to get the inital coord of mouse down this.defineProp('baseCoord', {'dataType': DataType.HASH, 'serializable': false}); this.defineProp('startCoord', {'dataType': DataType.HASH, 'serializable': false/*, 'setter': function(value) { console.log('set startCoord', value); console.log(arguments.callee.caller.caller.caller.toString()); this.setPropStoreFieldValue('startCoord', value); }*/ }); this.defineProp('endCoord', {'dataType': DataType.HASH, 'serializable': false}); this.defineProp('startBox', {'dataType': DataType.HASH, 'serializable': false}); this.defineProp('endBox', {'dataType': DataType.HASH, 'serializable': false}); this.defineProp('lastRotateAngle', {'dataType': DataType.FLOAT, 'serializable': false}); // private // private, such as {x: 1, y: 0}, plays as the initial base direction of rotation this.defineProp('rotateRefCoord', {'dataType': DataType.HASH, 'serializable': false}); this.defineProp('rotateCenter', {'dataType': DataType.HASH, 'serializable': false, 'getter': function() { var result = this.getPropStoreFieldValue('rotateCenter'); if (!result) { /* var box = this.getStartBox(); result = box? {'x': (box.x1 + box.x2) / 2, 'y': (box.y1 + box.y2) / 2}: null; */ var centerCoord = this._getManipulateObjsCenterCoord(); result = this.getEditor().objCoordToScreen(centerCoord); this.setPropStoreFieldValue('rotateCenter', result); //console.log(result, result2); } return result; } }); this.defineProp('resizeStartingRegion', {'dataType': DataType.INT, 'serializable': false}); // private this.defineProp('enableAspectRatioLockedResize', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('rotateStartingRegion', {'dataType': DataType.INT, 'serializable': false}); // private this.defineProp('manipulateOriginObjs', {'dataType': DataType.ARRAY, 'serializable': false}); // private, the direct object user act on this.defineProp('manipulateObjs', {'dataType': DataType.ARRAY, 'serializable': false, // actual manipulated objects 'setter': function(value) { this.setPropStoreFieldValue('manipulateObjs', value); //console.log('set manipulate', value); if (!value) this.getEditor().endOperatingObjs(); else this.getEditor().prepareOperatingObjs(value); } }); this.defineProp('manipulateObjInfoMap', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null, 'getter': function() { var result = this.getPropStoreFieldValue('manipulateObjInfoMap'); if (!result) { result = new Kekule.MapEx(true); this.setPropStoreFieldValue('manipulateObjInfoMap', result); } return result; } }); this.defineProp('manipulateObjCurrInfoMap', {'dataType': DataType.OBJECT, 'serializable': false, 'setter': null, 'getter': function() { var result = this.getPropStoreFieldValue('manipulateObjCurrInfoMap'); if (!result) { result = new Kekule.MapEx(true); this.setPropStoreFieldValue('manipulateObjCurrInfoMap', result); } return result; } }); this.defineProp('manipulationType', {'dataType': DataType.INT, 'serializable': false}); // private this.defineProp('isManipulatingSelection', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('isOffsetManipulating', {'dataType': DataType.BOOL, 'serializable': false}); this.defineProp('manipulationPointerType', {'dataType': DataType.BOOL, 'serializable': false, 'getter': function() { return this.getActivePointerType(); }, 'setter': function(value) { this.setActivePointerType(value); } }); // private, alias of property activePointerType this.defineProp('activePointerId', {'dataType': DataType.INT, 'serializable': false}); // private, the pointer id currently activated in editpr //this.defineProp('manipulateOperation', {'dataType': 'Kekule.MacroOperation', 'serializable': false}); // store operation of moving //this.defineProp('activeOperation', {'dataType': 'Kekule.MacroOperation', 'serializable': false}); // store operation that should be add to history this.defineProp('moveOperations', {'dataType': DataType.ARRAY, 'serializable': false}); // store operations of moving //this.defineProp('mergeOperations', {'dataType': DataType.ARRAY, 'serializable': false}); // store operations of merging this.defineProp('moveWrapperOperation', {'dataType': DataType.OBJECT, 'serializable': false}); // private this.defineProp('objOperationMap', {'dataType': 'Kekule.MapEx', 'serializable': false, 'getter': function() { var result = this.getPropStoreFieldValue('objOperationMap'); if (!result) { result = new Kekule.MapEx(true); this.setPropStoreFieldValue('objOperationMap', result); } return result; } }); // store operation on each object }, /** @ignore */ initPropValues: function() { this.tryApplySuper('initPropValues'); this.setEnableSelect(false); // turn off select for most of IA controllers derived from this class this.setEnableGestureManipulation(false); // turn off gesture for most of IA controllers derived from this class /* this.setEnableGestureManipulation(false); this.setEnableMove(true); this.setEnableResize(true); this.setEnableAspectRatioLockedResize(true); this.setEnableRotate(true); */ var options = Kekule.globalOptions.get('chemWidget.editor') || {}; var oneOf = Kekule.oneOf; this.setEnableMove(oneOf(options.enableMove, true)); this.setEnableResize(oneOf(options.enableResize, true)); this.setEnableAspectRatioLockedResize(oneOf(options.enableAspectRatioLockedResize, true)); this.setEnableRotate(oneOf(options.enableRotate, true)); }, /** @private */ doFinalize: function(/*$super*/) { var map = this.getPropStoreFieldValue('manipulateObjInfoMap'); if (map) map.clear(); map = this.getPropStoreFieldValue('objOperationMap'); if (map) map.clear(); this.tryApplySuper('doFinalize') /* $super() */; }, /* @ignore */ /* activated: function($super, widget) { $super(widget); //console.log('activated', this.getSelectMode()); // set select mode when be activated if (this.getEnableSelect()) this.getEditor().setSelectMode(this.getSelectMode()); }, */ /** @ignore */ hotTrackOnObj: function(/*$super, */obj) { // override parent method, is selectMode is ANCESTOR, hot track the whole ancestor object if (this.getEnableSelect() && this.getSelectMode() === Kekule.Editor.SelectMode.ANCESTOR) { var concreteObj = this.getStandaloneAncestor(obj); (obj && obj.getStandaloneAncestor) ? obj.getStandaloneAncestor() : obj; return this.tryApplySuper('hotTrackOnObj', [concreteObj]) /* $super(concreteObj) */; } else return this.tryApplySuper('hotTrackOnObj', [obj]) /* $super(obj) */; }, /** @private */ getStandaloneAncestor: function(obj) { return (obj && obj.getStandaloneAncestor) ? obj.getStandaloneAncestor() : obj; }, /** @private */ isInAncestorSelectMode: function() { return this.getEnableSelect() && (this.getSelectMode() === Kekule.Editor.SelectMode.ANCESTOR); }, /** @private */ isAspectRatioLockedResize: function() { return this.getEnableAspectRatioLockedResize() && (!this._suppressConstrainedResize); }, /** * Check if screenCoord is on near-outside of selection bound and returns which corner is the neraest. * @param {Hash} screenCoord * @returns {Variant} If on rotation region, a nearest corner flag (from @link Kekule.Editor.BoxRegion} will be returned, * else false will be returned. */ getCoordOnSelectionRotationRegion: function(screenCoord) { var R = Kekule.Editor.BoxRegion; var editor = this.getEditor(); var region = editor.getCoordRegionInSelectionMarker(screenCoord); if (region !== R.OUTSIDE) return false; var r = editor.getEditorConfigs().getInteractionConfigs().getRotationRegionInflation(); var box = editor.getUiSelectionAreaContainerBox(); if (box && editor.hasSelection()) { var corners = [R.CORNER_TL, R.CORNER_TR, R.CORNER_BR, R.CORNER_BL]; var points = [ {'x': box.x1, 'y': box.y1}, {'x': box.x2, 'y': box.y1}, {'x': box.x2, 'y': box.y2}, {'x': box.x1, 'y': box.y2} ]; var result = false; var minDis = r; for (var i = 0, l = corners.length; i < l; ++i) { var corner = corners[i]; var point = points[i]; var dis = Kekule.CoordUtils.getDistance(point, screenCoord); if (dis <= minDis) { result = corner; minDis = dis; } } return result; } else return false; }, /** * Create a coord change operation to add to operation history of editor. * The operation is a macro one with sub operations on each obj. * @private */ createManipulateOperation: function() { return this.doCreateManipulateMoveAndResizeOperation(); }, /** @private */ doCreateManipulateMoveAndResizeOperation: function() { //var oper = new Kekule.MacroOperation(); var opers = []; this.setMoveOperations(opers); var objs = this.getManipulateObjs(); var map = this.getManipulateObjInfoMap(); var operMap = this.getObjOperationMap(); operMap.clear(); var objsMoveInfo = []; var totalOperation = new Kekule.ChemObjOperation.MoveAndResizeObjs([], objsMoveInfo, this.getEditor().getCoordMode(), true, this.getEditor()); totalOperation.setDisableIndirectCoord(true); //console.log('init operations'); for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var item = map.get(obj); //var sub = new Kekule.EditorOperation.OpSetObjCoord(this.getEditor(), obj, null, item.objCoord, Kekule.Editor.CoordSys.OBJ); //var sub = new Kekule.ChemObjOperation.MoveTo(obj, null, this.getEditor().getCoordMode()); var sub = new Kekule.ChemObjOperation.MoveAndResize(obj, null, null, this.getEditor().getCoordMode(), true, this.getEditor()); // use abs coord sub.setAllowCoordBorrow(this.getEditor().getAllowCoordBorrow()); sub.setOldCoord(item.objCoord); sub.setOldDimension(item.size); //oper.add(sub); //operMap.set(obj, sub); opers.push(sub); /* objsMoveInfo.push({ 'obj': obj, 'oldCoord': item.objCoord, 'oldDimension': item.size }); */ totalOperation.getChildOperations().push(sub); this.setMoveWrapperOperation(totalOperation); } //this.setManipulateOperation(oper); //this.setActiveOperation(oper); //return oper; //return opers; return [totalOperation]; }, /* @private */ /* _ensureObjOperationToMove: function(obj) { var map = this.getObjOperationMap(); var oper = map.get(obj); if (oper && !(oper instanceof Kekule.ChemObjOperation.MoveAndResize)) { //console.log('_ensureObjOperationToMove reverse'); //oper.reverse(); oper.finalize(); oper = new Kekule.ChemObjOperation.MoveAndResize(obj, null, null, this.getEditor().getCoordMode(), true); // use abs coord map.set(obj, oper); } return oper; }, */ /** * Update new coord info of sub operations. * @private */ updateChildMoveOperation: function(objIndex, obj, newObjCoord) { //console.log('update move', newObjCoord); //var oper = this.getManipulateOperation().getChildAt(objIndex); //var oper = this._ensureObjOperationToMove(obj); var oper = this.getMoveOperations()[objIndex]; //oper.setCoord(newObjCoord); oper.setNewCoord(newObjCoord); }, /** @private */ updateChildResizeOperation: function(objIndex, obj, newDimension) { //var oper = this.getManipulateOperation().getChildAt(objIndex); //var oper = this._ensureObjOperationToMove(obj); var oper = this.getMoveOperations()[objIndex]; oper.setNewDimension(newDimension); }, /** @private */ getAllObjOperations: function(isTheFinalOperationToEditor) { //var opers = this.getObjOperationMap().getValues(); var op = this.getMoveOperations(); var opers = op? Kekule.ArrayUtils.clone(op): []; if (opers.length) { var wrapper = this.getMoveWrapperOperation(); wrapper.setChildOperations(opers); //return opers; return [wrapper]; } else return []; }, /** @private */ getActiveOperation: function(isTheFinalOperationToEditor) { //console.log('get active operation', isTheFinalOperationToEditor); var opers = this.getAllObjOperations(isTheFinalOperationToEditor); opers = Kekule.ArrayUtils.toUnique(opers); if (opers.length <= 0) return null; else if (opers.length === 1) return opers[0]; else { var macro = new Kekule.MacroOperation(opers); return macro; } }, /** @private */ reverseActiveOperation: function() { var oper = this.getActiveOperation(); return oper.reverse(); }, /* @private */ /* clearActiveOperation: function() { //this.getObjOperationMap().clear(); }, */ /** @private */ addOperationToEditor: function() { var editor = this.getEditor(); if (editor && editor.getEnableOperHistory()) { //console.log('add oper to editor', this.getClassName(), this.getActiveOperation()); //editor.pushOperation(this.getActiveOperation()); /* var opers = this.getAllObjOperations(); var macro = new Kekule.MacroOperation(opers); editor.pushOperation(macro); */ var op = this.getActiveOperation(true); if (op) editor.pushOperation(op); } }, // methods about object move / resize /** @private */ getCurrAvailableManipulationTypes: function() { var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; var box = this.getEditor().getSelectionContainerBox(); if (!box) { return []; } else { var result = []; if (this.getEnableMove()) result.push(T.MOVE); // if box is a single point, can not resize or rotate if (!Kekule.NumUtils.isFloatEqual(box.x1, box.x2, 1e-10) || !Kekule.NumUtils.isFloatEqual(box.y1, box.y2, 1e-10)) { if (this.getEnableResize()) result.push(T.RESIZE); if (this.getEnableRotate()) result.push(T.ROTATE); if (this.getEnableResize() || this.getEnableRotate()) result.push(T.TRANSFORM); } return result; } }, /** @private */ getActualManipulatingObjects: function(objs) { var result = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var actualObjs = obj.getCoordDependentObjects? obj.getCoordDependentObjects(): [obj]; Kekule.ArrayUtils.pushUnique(result, actualObjs); } return result; }, /* * Prepare to resize resizingObjs. * Note that resizingObjs may differ from actual resized objects (for instance, resize a bond actually move its connected atoms). * @param {Hash} startContextCoord Mouse position when starting to move objects. This coord is based on context. * @param {Array} resizingObjs Objects about to be resized. * @private */ /* prepareResizing: function(startScreenCoord, startBox, movingObjs) { var actualObjs = this.getActualResizingObject(movingObjs); this.setManipulateObjs(actualObjs); var map = this.getManipulateObjInfoMap(); map.clear(); var editor = this.getEditor(); // store original objs coords info into map for (var i = 0, l = actualObjs.length; i < l; ++i) { var obj = actualObjs[i]; var info = this.createManipulateObjInfo(obj, startScreenCoord); map.set(obj, info); } this.setStartBox(startBox); }, */ /** @private */ doPrepareManipulatingObjects: function(manipulatingObjs, startScreenCoord) { var actualObjs = this.getActualManipulatingObjects(manipulatingObjs); //console.log(manipulatingObjs, actualObjs); this.setManipulateOriginObjs(manipulatingObjs); this.setManipulateObjs(actualObjs); var map = this.getManipulateObjInfoMap(); map.clear(); //this.getManipulateObjCurrInfoMap().clear(); var editor = this.getEditor(); // store original objs coords info into map for (var i = 0, l = actualObjs.length; i < l; ++i) { var obj = actualObjs[i]; var info = this.createManipulateObjInfo(obj, i, startScreenCoord); map.set(obj, info); /* // disable indirect coord during coord move if (info.enableIndirectCoord) obj.setEnableIndirectCoord(false); */ } }, /** @private */ doPrepareManipulatingStartingCoords: function(startScreenCoord, startBox, rotateCenter, rotateRefCoord) { this.setStartBox(startBox); this.setRotateCenter(rotateCenter); this.setRotateRefCoord(rotateRefCoord); this.setLastRotateAngle(null); }, /** * Prepare to move movingObjs. * Note that movingObjs may differ from actual moved objects (for instance, move a bond actually move its connected atoms). * @param {Hash} startContextCoord Mouse position when starting to move objects. This coord is based on context. * @param {Array} manipulatingObjs Objects about to be moved or resized. * @param {Hash} startBox * @param {Hash} rotateCenter * @private */ prepareManipulating: function(manipulationType, manipulatingObjs, startScreenCoord, startBox, rotateCenter, rotateRefCoord) { this.setManipulationType(manipulationType); this.doPrepareManipulatingObjects(manipulatingObjs, startScreenCoord); this.doPrepareManipulatingStartingCoords(startScreenCoord, startBox, rotateCenter, rotateRefCoord); this.createManipulateOperation(); this._cachedTransformCompareThresholds = null; // clear cache this._runManipulationStepId = Kekule.window.requestAnimationFrame(this.execManipulationStepBind); //this.setManuallyHotTrack(true); // manully set hot track point when manipulating }, /** * Cancel the moving process and set objects to its original position. * @private */ cancelManipulate: function() { var editor = this.getEditor(); var objs = this.getManipulateObjs(); //editor.beginUpdateObject(); //this.getActiveOperation().reverse(); this.reverseActiveOperation(); this.notifyCoordChangeOfObjects(this.getManipulateObjs()); //editor.endUpdateObject(); //this.setActiveOperation(null); //this.clearActiveOperation(); //this.setManuallyHotTrack(false); this.manipulateEnd(); }, /** * Returns center coord of manipulate objs. * @private */ _getManipulateObjsCenterCoord: function() { var objs = this.getManipulateObjs(); if (!objs || !objs.length) return null; var coordMode = this.getEditor().getCoordMode(); var allowCoordBorrow = this.getEditor().getAllowCoordBorrow(); var sum = {'x': 0, 'y': 0, 'z': 0}; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var objCoord = obj.getAbsBaseCoord? obj.getAbsBaseCoord(coordMode, allowCoordBorrow): obj.getAbsCoord? obj.getAbsCoord(coordMode, allowCoordBorrow): obj.getCoordOfMode? obj.getCoordOfMode(coordMode, allowCoordBorrow): null; if (objCoord) sum = Kekule.CoordUtils.add(sum, objCoord); } return Kekule.CoordUtils.divide(sum, objs.length); }, /** * Called when a phrase of rotate/resize/move function ends. */ _maniplateObjsFrameEnd: function(objs) { // do nothing here }, /** @private */ _addManipultingObjNewInfo: function(obj, newInfo) { var newInfoMap = this.getManipulateObjCurrInfoMap(); var info = newInfoMap.get(obj) || {}; info = Object.extend(info, newInfo); newInfoMap.set(obj, info); }, /** @private */ applyManipulatingObjsInfo: function(endScreenCoord) { //this._moveResizeOperExecPending = false; var objs = this.getManipulateObjs(); var newInfoMap = this.getManipulateObjCurrInfoMap(); var indirectCoordObjs = this._getIndirectCoordObjs(objs); this._setEnableIndirectCoordOfObjs(indirectCoordObjs, false); // important, disable indirect coord first, avoid calculating during moving and position error try { for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; var newInfo = newInfoMap.get(obj); this.applySingleManipulatingObjInfo(i, obj, newInfo, endScreenCoord); } /* if (this._moveResizeOperExecPending) this.getMoveWrapperOperation().execute(); */ } finally { this._setEnableIndirectCoordOfObjs(indirectCoordObjs, true); } }, /** @private */ _getIndirectCoordObjs: function(objs) { var result = []; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; if (obj.getEnableIndirectCoord && obj.getEnableIndirectCoord()) result.push(obj); } return result; }, /** @private */ _setEnableIndirectCoordOfObjs: function(objs, enabled) { if (!objs) return; for (var i = 0, l = objs.length; i < l; ++i) { objs[i].setEnableIndirectCoord(enabled); } }, /** @private */ applySingleManipulatingObjInfo: function(objIndex, obj, newInfo, endScreenCoord) { if (newInfo) { if (newInfo.screenCoord) this.doMoveManipulatedObj(objIndex, obj, newInfo.screenCoord, endScreenCoord); if (newInfo.size) this.doResizeManipulatedObj(objIndex, obj, newInfo.size); } }, /** @private */ _calcRotateAngle: function(endScreenCoord) { var C = Kekule.CoordUtils; var angle; var angleCalculated = false; var rotateCenter = this.getRotateCenter(); var startCoord = this.getRotateRefCoord() || this.getStartCoord(); // ensure startCoord large than threshold var threshold = this.getEditorConfigs().getInteractionConfigs().getRotationLocationPointDistanceThreshold(); if (threshold) { var startDistance = C.getDistance(startCoord, rotateCenter); if (startDistance < threshold) { angle = 0; // do not rotate angleCalculated = true; // and use endScreen coord as new start coord this.setStartCoord(endScreenCoord); return false; } var endDistance = C.getDistance(endScreenCoord, rotateCenter); if (endDistance < threshold) { angle = 0; // do not rotate angleCalculated = true; return false; } } if (!angleCalculated) { var vector = C.substract(endScreenCoord, rotateCenter); var endAngle = Math.atan2(vector.y, vector.x); vector = C.substract(startCoord, rotateCenter); var startAngle = Math.atan2(vector.y, vector.x); angle = endAngle - startAngle; } return {'angle': angle, 'startAngle': startAngle, 'endAngle': endAngle}; }, /** @private */ _calcActualRotateAngle: function(objs, newDeltaAngle, oldAbsAngle, newAbsAngle) { return newDeltaAngle; }, /** @private */ _calcManipulateObjsRotationParams: function(manipulatingObjs, endScreenCoord) { if (!this.getEnableRotate()) return false; var rotateCenter = this.getRotateCenter(); var angleInfo = this._calcRotateAngle(endScreenCoord); if (!angleInfo) // need not to rotate return false; // get actual rotation angle var angle = this._calcActualRotateAngle(manipulatingObjs, angleInfo.angle, angleInfo.startAngle, angleInfo.endAngle); var lastAngle = this.getLastRotateAngle(); if (Kekule.ObjUtils.notUnset(lastAngle) && Kekule.NumUtils.isFloatEqual(angle, lastAngle, 0.0175)) // ignore angle change under 1 degree { return false; // no angle change, do not rotate } //console.log('rotateAngle', angle, lastAngle); this.setLastRotateAngle(angle); return {'center': rotateCenter, 'rotateAngle': angle}; }, /* @private */ /* doRotateManipulatedObjs: function(endScreenCoord, transformParams) { var byPassRotate = !this._calcManipulateObjsTransformInfo(this.getManipulateObjs(), transformParams); if (byPassRotate) // need not to rotate { //console.log('bypass rotate'); return; } //console.log('rotate'); var objNewInfo = this.getManipulateObjCurrInfoMap(); var editor = this.getEditor(); editor.beginUpdateObject(); try { var objs = this.getManipulateObjs(); this.applyManipulatingObjsInfo(endScreenCoord); this._maniplateObjsFrameEnd(objs); this.notifyCoordChangeOfObjects(objs); } finally { editor.endUpdateObject(); this.manipulateStepDone(); } }, */ /* * Rotate manupulatedObjs according to endScreenCoord. * @private */ /* rotateManipulatedObjs: function(endScreenCoord) { var R = Kekule.Editor.BoxRegion; var C = Kekule.CoordUtils; //var editor = this.getEditor(); var changedObjs = []; //console.log('rotate', this.getRotateCenter(), endScreenCoord); var rotateParams = this._calcManipulateObjsRotationParams(this.getManipulateObjs(), endScreenCoord); if (!rotateParams) return; this.doRotateManipulatedObjs(endScreenCoord, rotateParams); }, */ /** @private */ _calcActualResizeScales: function(objs, newScales) { return newScales; }, /** @private */ _calcManipulateObjsResizeParams: function(manipulatingObjs, startingRegion, endScreenCoord) { if (!this.getEnableResize()) return false; var R = Kekule.Editor.BoxRegion; var C = Kekule.CoordUtils; var box = this.getStartBox(); var coordDelta = C.substract(endScreenCoord, this.getStartCoord()); var scaleCenter; var doConstraint, doConstraintOnX, doConstraintOnY; if (startingRegion === R.EDGE_TOP) { coordDelta.x = 0; scaleCenter = {'x': (box.x1 + box.x2) / 2, 'y': box.y2}; } else if (startingRegion === R.EDGE_BOTTOM) { coordDelta.x = 0; scaleCenter = {'x': (box.x1 + box.x2) / 2, 'y': box.y1}; } else if (startingRegion === R.EDGE_LEFT) { coordDelta.y = 0; scaleCenter = {'x': box.x2, 'y': (box.y1 + box.y2) / 2}; } else if (startingRegion === R.EDGE_RIGHT) { coordDelta.y = 0; scaleCenter = {'x': box.x1, 'y': (box.y1 + box.y2) / 2}; } else // resize from corner { if (this.isAspectRatioLockedResize()) { doConstraint = true; /* var widthHeightRatio = (box.x2 - box.x1) / (box.y2 - box.y1); var currRatio = coordDelta.x / coordDelta.y; if (Math.abs(currRatio) > widthHeightRatio) //coordDelta.x = coordDelta.y * widthHeightRatio * (Math.sign(currRatio) || 1); doConstraintOnY = true; else //coordDelta.y = coordDelta.x / widthHeightRatio * (Math.sign(currRatio) || 1); doConstraintOnX = true; */ } scaleCenter = (startingRegion === R.CORNER_TL)? {'x': box.x2, 'y': box.y2}: (startingRegion === R.CORNER_TR)? {'x': box.x1, 'y': box.y2}: (startingRegion === R.CORNER_BL)? {'x': box.x2, 'y': box.y1}: {'x': box.x1, 'y': box.y1}; } var reversedX = (startingRegion === R.CORNER_TL) || (startingRegion === R.CORNER_BL) || (startingRegion === R.EDGE_LEFT); var reversedY = (startingRegion === R.CORNER_TL) || (startingRegion === R.CORNER_TR) || (startingRegion === R.EDGE_TOP); // calc transform matrix var scaleX, scaleY; if (Kekule.NumUtils.isFloatEqual(box.x1, box.x2, 1e-10)) // box has no x size, can not scale on x scaleX = 1; else scaleX = 1 + coordDelta.x / (box.x2 - box.x1) * (reversedX? -1: 1); if (Kekule.NumUtils.isFloatEqual(box.y1, box.y2, 1e-10)) // box has no y size, can not scale on y scaleY = 1; else scaleY = 1 + coordDelta.y / (box.y2 - box.y1) * (reversedY? -1: 1); if (doConstraint) { var absX = Math.abs(scaleX), absY = Math.abs(scaleY); if (absX >= absY) scaleY = (Math.sign(scaleY) || 1) * absX; // avoid sign = 0 else scaleX = (Math.sign(scaleX) || 1) * absY; } //console.log('before actual scale', coordDelta, {'scaleX': scaleX, 'scaleY': scaleY}); var actualScales = this._calcActualResizeScales(manipulatingObjs, {'scaleX': scaleX, 'scaleY': scaleY}); var transformParams = {'center': scaleCenter, 'scaleX': actualScales.scaleX, 'scaleY': actualScales.scaleY}; //console.log(this.isAspectRatioLockedResize(), scaleX, scaleY); //console.log('startBox', box); //console.log('transformParams', transformParams); return transformParams; }, /* @private */ /* _calcManipulateObjsResizeInfo: function(manipulatingObjs, startingRegion, endScreenCoord) { var R = Kekule.Editor.BoxRegion; var C = Kekule.CoordUtils; var transformOps = this._calcManipulateObjsResizeParams(manipulatingObjs, startingRegion, endScreenCoord); //console.log(scaleX, scaleY); this._calcManipulateObjsTransformInfo(manipulatingObjs, transformOps); return true; }, */ /** @private */ _calcManipulateObjsTransformInfo: function(manipulatingObjs, transformParams) { var C = Kekule.CoordUtils; // since we transform screen coord, it will always be in 2D mode // and now the editor only supports 2D var is3D = false; // this.getEditor().getCoordMode() === Kekule.CoordMode.COORD3D; var transformMatrix = is3D? C.calcTransform3DMatrix(transformParams): C.calcTransform2DMatrix(transformParams); var scaleX = transformParams.scaleX || transformParams.scale; var scaleY = transformParams.scaleY || transformParams.scale; var isMovingOneStickNode = this._isManipulatingSingleStickedObj(manipulatingObjs); for (var i = 0, l = manipulatingObjs.length; i < l; ++i) { var obj = manipulatingObjs[i]; var info = this.getManipulateObjInfoMap().get(obj); var newInfo = {}; if (!info.hasNoCoord) // this object has coord property and can be rotated { var oldCoord = info.screenCoord; if (!info.stickTarget || isMovingOneStickNode) { var newCoord = C.transform2DByMatrix(oldCoord, transformMatrix); newInfo.screenCoord = newCoord; } else newInfo.screenCoord = oldCoord; //this._addManipultingObjNewInfo(obj, {'screenCoord': newCoord}); } // TODO: may need change dimension also if (info.size && (scaleX || scaleY)) { var newSize = {'x': info.size.x * Math.abs(scaleX || 1), 'y': info.size.y * Math.abs(scaleY || 1)}; newInfo.size = newSize; } this._addManipultingObjNewInfo(obj, newInfo); } return true; }, /** * Whether an object is sticking to another one. * @private */ _isStickedObj: function(obj) { return obj && obj.getCoordStickTarget && obj.getCoordStickTarget(); }, /** @private */ _isManipulatingSingleStickedObj: function(manipulatingObjs) { var result = false; if (manipulatingObjs.length === 1) { var oneObj = manipulatingObjs[0]; var info = this.getManipulateObjInfoMap().get(oneObj); result = !!info.stickTarget; } return result; }, /* * Resize manupulatedObjs according to endScreenCoord. * @private */ /* doResizeManipulatedObjs: function(endScreenCoord) { var editor = this.getEditor(); var objs = this.getManipulateObjs(); //var changedObjs = []; this._calcManipulateObjsResizeInfo(objs, this.getResizeStartingRegion(), endScreenCoord); editor.beginUpdateObject(); var newInfoMap = this.getManipulateObjCurrInfoMap(); try { this.applyManipulatingObjsInfo(endScreenCoord); this._maniplateObjsFrameEnd(objs); this.notifyCoordChangeOfObjects(objs); } finally { editor.endUpdateObject(); this.manipulateStepDone(); } }, */ /** * Transform manupulatedObjs according to manipulateType(rotate/resize) endScreenCoord. * @private */ doTransformManipulatedObjs: function(manipulateType, endScreenCoord, explicitTransformParams) { var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; var editor = this.getEditor(); var objs = this.getManipulateObjs(); //var changedObjs = []; var transformParams = explicitTransformParams; if (!transformParams) { if (manipulateType === T.RESIZE) transformParams = this._calcManipulateObjsResizeParams(objs, this.getResizeStartingRegion(), endScreenCoord); else if (manipulateType === T.ROTATE) transformParams = this._calcManipulateObjsRotationParams(objs, endScreenCoord); } if (this._lastTransformParams && this._isSameTransformParams(this._lastTransformParams, transformParams, null, editor.getCoordMode())) // not a significant change, do not transform { //console.log('bypass transform'); return; } //console.log('do transform', transformParams); var doConcreteTransform = transformParams && this._calcManipulateObjsTransformInfo(objs, transformParams); if (!doConcreteTransform) return; this._lastTransformParams = transformParams; editor.beginUpdateObject(); var newInfoMap = this.getManipulateObjCurrInfoMap(); try { this.applyManipulatingObjsInfo(endScreenCoord); this._maniplateObjsFrameEnd(objs); this.notifyCoordChangeOfObjects(objs); } finally { editor.endUpdateObject(); this.manipulateStepDone(); } }, /** @private */ _isSameTransformParams: function(p1, p2, thresholds, coordMode) { if (!thresholds) { thresholds = this._cachedTransformCompareThresholds; } if (!thresholds) { thresholds = this._getTransformCompareThresholds(); // 0.1 this._cachedTransformCompareThresholds = thresholds; // cache the threshold to reduce calculation } /* if (coordMode === Kekule.CoordMode.COORD2D) return CU.isSameTransform2DOptions(p1, p2, {'translate': threshold, 'scale': threshold, 'rotate': threshold}); else return CU.isSameTransform3DOptions(p1, p2, {'translate': threshold, 'scale': threshold, 'rotate': threshold}); */ if (coordMode === Kekule.CoordMode.COORD2D) return CU.isSameTransform2DOptions(p1, p2, {'translate': thresholds.translate, 'scale': thresholds.scale, 'rotate': thresholds.rotate}); else return CU.isSameTransform3DOptions(p1, p2, {'translate': thresholds.translate, 'scale': thresholds.scale, 'rotate': thresholds.rotate}); }, /** @private */ _getTransformCompareThresholds: function(coordMode) { return { translate: 0.1, scale: 0.1, rotate: 0.1 } }, /* @private */ _calcActualMovedScreenCoord: function(obj, info, newScreenCoord) { return newScreenCoord; }, /** @private */ _calcManipulateObjsMoveInfo: function(manipulatingObjs, endScreenCoord) { var C = Kekule.CoordUtils; var newInfoMap = this.getManipulateObjCurrInfoMap(); var editor = this.getEditor(); var isMovingOneStickNode = this._isManipulatingSingleStickedObj(manipulatingObjs); var isDirectManipulateSingleObj = this.isDirectManipulating() && (manipulatingObjs.length === 1); var manipulatingObjHasSize = isDirectManipulateSingleObj? (manipulatingObjs[0] && manipulatingObjs[0].getSizeOfMode && manipulatingObjs[0].getSizeOfMode(editor.getCoordMode(), editor.getAllowCoordBorrow())): true; var followPointerCoord = isDirectManipulateSingleObj && !manipulatingObjHasSize // when the object has size, it can not follow the pointer coord && this.getEditorConfigs().getInteractionConfigs().getFollowPointerCoordOnDirectManipulatingSingleObj(); if (followPointerCoord) { var startCoord = this.getStartCoord(); var moveDistance = C.getDistance(endScreenCoord, startCoord); if (moveDistance <= this.getEditorConfigs().getInteractionConfigs().getFollowPointerCoordOnDirectManipulatingSingleObjDistanceThreshold()) { followPointerCoord = false; } } for (var i = 0, l = manipulatingObjs.length; i < l; ++i) { var obj = manipulatingObjs[i]; var info = this.getManipulateObjInfoMap().get(obj); if (info.hasNoCoord) // this object has no coord property and can not be moved continue; if (info.stickTarget && !isMovingOneStickNode) continue; var newScreenCoord; if (followPointerCoord) newScreenCoord = endScreenCoord; else newScreenCoord = C.add(endScreenCoord, info.screenCoordOffset); newScreenCoord = this._calcActualMovedScreenCoord(obj, info, newScreenCoord); this._addManipultingObjNewInfo(obj, {'screenCoord': newScreenCoord}); } }, /** * Move objects in manipulateObjs array to new position. New coord is determinated by endContextCoord * and each object's offset. * @private */ moveManipulatedObjs: function(endScreenCoord) { var C = Kekule.CoordUtils; var editor = this.getEditor(); var objs = this.getManipulateObjs(); var changedObjs = []; this._calcManipulateObjsMoveInfo(objs, endScreenCoord); editor.beginUpdateObject(); var newInfoMap = this.getManipulateObjCurrInfoMap(); try { this.applyManipulatingObjsInfo(endScreenCoord); this._maniplateObjsFrameEnd(objs); // notify this.notifyCoordChangeOfObjects(objs); } finally { editor.endUpdateObject(); this.manipulateStepDone(); } }, /** * Move a single object to newScreenCoord. MoverScreenCoord is the actual coord of mouse. * Note that not only move operation will call this method, rotate and resize may also affect * objects' coord so this method will also be called. * @private */ doMoveManipulatedObj: function(objIndex, obj, newScreenCoord, moverScreenCoord) { var editor = this.getEditor(); this.updateChildMoveOperation(objIndex, obj, editor.screenCoordToObj(newScreenCoord)); editor.setObjectScreenCoord(obj, newScreenCoord); //this._moveResizeOperExecPending = true; }, /** * Resize a single object to newDimension. * @private */ doResizeManipulatedObj: function(objIndex, obj, newSize) { this.updateChildResizeOperation(objIndex, obj, newSize); if (obj.setSizeOfMode) obj.setSizeOfMode(newSize, this.getEditor().getCoordMode()); //this._moveResizeOperExecPending = true; }, /* * Moving complete, do the wrap up job. * @private */ /* endMoving: function() { this.stopManipulate(); }, */ /** * Returns whether the controller is in direct manipulating state. */ isDirectManipulating: function() { return (this.getState() === Kekule.Editor.BasicManipulationIaController.State.MANIPULATING) && (!this.getIsManipulatingSelection()); }, /** * Click on a object or objects and manipulate it directly. * @private */ startDirectManipulate: function(manipulateType, objOrObjs, startCoord, startBox, rotateCenter, rotateRefCoord) { this.manipulateBegin(); return this.doStartDirectManipulate(manipulateType, objOrObjs, startCoord, startBox, rotateCenter, rotateRefCoord); }, /** @private */ doStartDirectManipulate: function(manipulateType, objOrObjs, startCoord, startBox, rotateCenter, rotateRefCoord) { var objs = Kekule.ArrayUtils.toArray(objOrObjs); this.setState(Kekule.Editor.BasicManipulationIaController.State.MANIPULATING); this.setBaseCoord(startCoord); this.setStartCoord(startCoord); this.setRotateRefCoord(rotateRefCoord); this.setIsManipulatingSelection(false); //console.log('call prepareManipulating', startCoord, manipulateType, objOrObjs); this.prepareManipulating(manipulateType || Kekule.Editor.BasicManipulationIaController.ManipulationType.MOVE, objs, startCoord, startBox, rotateCenter, rotateRefCoord); }, /** * Called when a manipulation is applied and the changes has been reflected in editor (editor redrawn done). * Descendants may override this method. * @private */ manipulateStepDone: function() { // do nothing here }, /** @private */ doManipulateObjectsEnd: function(manipulatingObjs) { var map = this.getManipulateObjInfoMap(); for (var i = manipulatingObjs.length - 1; i >= 0; --i) { this.doManipulateObjectEnd(manipulatingObjs[i], map.get(manipulatingObjs[i])); } }, /** @private */ doManipulateObjectEnd: function(manipulateObj, objInfo) { /* if (objInfo.enableIndirectCoord && manipulateObj.setEnableIndirectCoord) manipulateObj.setEnableIndirectCoord(true); */ }, /** * Called when a manipulation is beginning (usually with point down event). * Descendants may override this method. * @private */ manipulateBegin: function() { this.notifyEditorBeginManipulateObjects(); }, /** * Called when a manipulation is ended (stopped or cancelled). * Descendants may override this method. * @private */ manipulateEnd: function() { if (this._runManipulationStepId) { Kekule.window.cancelAnimationFrame(this._runManipulationStepId); this._runManipulationStepId = null; } this.doManipulateObjectsEnd(this.getManipulateObjs()); this._lastTransformParams = null; this.setIsOffsetManipulating(false); this.setManipulateObjs(null); this.getManipulateObjInfoMap().clear(); this.getObjOperationMap().clear(); this.notifyEditorEndManipulateObjects(); }, /** * Called before method stopManipulate. * Descendants may do some round-off work here. * @private */ manipulateBeforeStopping: function() { // do nothing here }, /** * Stop manipulate of objects. * @private */ stopManipulate: function() { this.manipulateEnd(); }, /** @private */ refreshManipulateObjs: function() { this.setManipulateObjs(this.getManipulateObjs()); }, /** @private */ createManipulateObjInfo: function(obj, objIndex, startScreenCoord) { var editor = this.getEditor(); var info = { //'obj': obj, 'objCoord': editor.getObjCoord(obj), // abs base coord //'objSelfCoord': obj.getCoordOfMode? obj.getCoordOfMode(editor.getCoordMode()): null, 'screenCoord': editor.getObjectScreenCoord(obj), 'size': editor.getObjSize(obj), 'enableIndirectCoord': !!(obj.getEnableIndirectCoord && obj.getEnableIndirectCoord()) }; info.hasNoCoord = !info.objCoord; if (!info.hasNoCoord && startScreenCoord) info.screenCoordOffset = Kekule.CoordUtils.substract(info.screenCoord, startScreenCoord); if (obj.getCoordStickTarget) // wether is a sticking object { info.stickTarget = obj.getCoordStickTarget(); } return info; }, /** @private */ notifyCoordChangeOfObjects: function(objs) { var changedDetails = []; var editor = this.getEditor(); var coordPropName = this.getEditor().getCoordMode() === Kekule.CoordMode.COORD3D? 'coord3D': 'coord2D'; for (var i = 0, l = objs.length; i < l; ++i) { var obj = objs[i]; Kekule.ArrayUtils.pushUnique(changedDetails, {'obj': obj, 'propNames': [coordPropName]}); var relatedObjs = obj.getCoordDeterminateObjects? obj.getCoordDeterminateObjects(): [obj]; for (var j = 0, k = relatedObjs.length; j < k; ++j) Kekule.ArrayUtils.pushUnique(changedDetails, {'obj': relatedObjs[j], 'propNames': [coordPropName]}); } // notify editor.objectsChanged(changedDetails); }, /** @private */ canInteractWithObj: function(obj) { return (this.getState() === Kekule.Editor.BasicManipulationIaController.State.NORMAL) && obj; }, /** @ignore */ doTestMouseCursor: function(coord, e) { if (!this.getEditor().isRenderable()) // if chem object not painted, do not need to test return ''; var result = ''; // since client element is not the same to widget element, coord need to be recalculated var c = this._getEventMouseCoord(e, this.getEditor().getEditClientElem()); if (this.getState() === Kekule.Editor.BasicManipulationIaController.State.NORMAL) { var R = Kekule.Editor.BoxRegion; var region = this.getEditor().getCoordRegionInSelectionMarker(c); if (this.getEnableSelect()) // show move/rotate/resize marker in select ia controller only { var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; var availManipulationTypes = this.getCurrAvailableManipulationTypes(); //if (this.getEnableMove()) if (availManipulationTypes.indexOf(T.MOVE) >= 0) { result = (region === R.INSIDE)? 'move': ''; } //if (!result && this.getEnableResize()) if (!result && (availManipulationTypes.indexOf(T.RESIZE) >= 0)) { var result = (region === R.CORNER_TL)? 'nwse-resize': (region === R.CORNER_TR)? 'nesw-resize': (region === R.CORNER_BL)? 'nesw-resize': (region === R.CORNER_BR)? 'nwse-resize': (region === R.EDGE_TOP) || (region === R.EDGE_BOTTOM)? 'ns-resize': (region === R.EDGE_LEFT) || (region === R.EDGE_RIGHT)? 'ew-resize': ''; } if (!result) { //if (this.getEnableRotate()) if (availManipulationTypes.indexOf(T.ROTATE) >= 0) { var region = this.getCoordOnSelectionRotationRegion(c); if (!!region) { var SN = Kekule.Widget.StyleResourceNames; result = (region === R.CORNER_TL)? SN.CURSOR_ROTATE_NW: (region === R.CORNER_TR)? SN.CURSOR_ROTATE_NE: (region === R.CORNER_BL)? SN.CURSOR_ROTATE_SW: (region === R.CORNER_BR)? SN.CURSOR_ROTATE_SE: SN.CURSOR_ROTATE; //console.log('rotate cursor', result); } } } } } return result; }, /** * Set operations in suspended state. * @param {Func} immediateOper * @param {Func} delayedOper * @param {Int} delay In ms. * @private */ setSuspendedOperations: function(immediateOper, delayedOper, delay) { if (this._suspendedOperations) this.haltSuspendedOperations(); // halt old var self = this; this._suspendedOperations = { 'immediate': immediateOper, 'delayed': delayedOper, 'delayExecId': setTimeout(this.execSuspendedDelayOperation.bind(this), delay) }; return this._suspendedOperations; }, /** * Execute the immediate operation in suspended operations, cancelling the delayed one. * @private */ execSuspendedImmediateOperation: function() { if (this._suspendedOperations) { //console.log('exec immediate'); clearTimeout(this._suspendedOperations.delayExecId); var oper = this._suspendedOperations.immediate; this._suspendedOperations = null; // clear old return oper.apply(this); } }, /** * Execute the delayed operation in suspended operations, cancelling the immediate one. * @private */ execSuspendedDelayOperation: function() { if (this._suspendedOperations) { //console.log('exec delayed'); clearTimeout(this._suspendedOperations.delayExecId); var oper = this._suspendedOperations.delayed; this._suspendedOperations = null; // clear old return oper.apply(this); } }, /** * Halt all suspend operations. * @private */ haltSuspendedOperations: function() { if (this._suspendedOperations) { clearTimeout(this._suspendedOperations.delayExecId); this._suspendedOperations = null; // clear old } }, /** @private */ _startNewSelecting: function(startCoord, shifted) { if (this.getEnableSelect()) { this.getEditor().startSelecting(startCoord, shifted || this.getEditor().getIsToggleSelectOn()); this.setState(Kekule.Editor.BasicManipulationIaController.State.SELECTING); } }, /** @private */ _startOffSelectionManipulation: function(currCoord) { //console.log('off selection!'); this.setIsOffsetManipulating(true); this.startManipulation(currCoord, null, Kekule.Editor.BasicManipulationIaController.ManipulationType.MOVE); this.getEditor().pulseSelectionAreaMarker(); // pulse selection, reach the user's attention }, /** * Begin a manipulation. * Descendants may override this method. * @param {Hash} currCoord Current coord of pointer (mouse or touch) * @param {Object} e Pointer (mouse or touch) event parameter. */ startManipulation: function(currCoord, e, explicitManipulationType) { var S = Kekule.Editor.BasicManipulationIaController.State; var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; var availManipulationTypes = this.getCurrAvailableManipulationTypes(); var evokedByTouch = e && e.pointerType === 'touch'; // edge resize/rotate will be disabled in touch if (e) { this.setManipulationPointerType(e && e.pointerType); } this.manipulateBegin(); this.setBaseCoord(currCoord); this.setStartCoord(currCoord); this._lastTransformParams = null; var coordRegion = currCoord && this.getEditor().getCoordRegionInSelectionMarker(currCoord); var R = Kekule.Editor.BoxRegion; var rotateRegion = currCoord && this.getCoordOnSelectionRotationRegion(currCoord); // test manipulate type /* var isTransform = (this.getEnableResize() || this.getEnableRotate()) && (explicitManipulationType === T.TRANSFORM); // gesture transform */ var isTransform = (availManipulationTypes.indexOf(T.TRANSFORM) >= 0) && (explicitManipulationType === T.TRANSFORM); // gesture transform //console.log('check isTransform', isTransform, explicitManipulationType, availManipulationTypes); if (!isTransform) { var isResize = !evokedByTouch && (availManipulationTypes.indexOf(T.RESIZE) >= 0) //&& this.getEnableResize() && ((explicitManipulationType === T.RESIZE) || ((coordRegion !== R.INSIDE) && (coordRegion !== R.OUTSIDE))); var isMove = !isResize && (availManipulationTypes.indexOf(T.MOVE) >= 0) // this.getEnableMove() && ((explicitManipulationType === T.MOVE) || (coordRegion !== R.OUTSIDE)); var isRotate = !evokedByTouch && !isResize && !isMove && (availManipulationTypes.indexOf(T.ROTATE) >= 0)//this.getEnableRotate() && ((explicitManipulationType === T.ROTATE) || !!rotateRegion); } else // transform { //console.log('set transform types', availManipulationTypes); this._availTransformTypes = availManipulationTypes; // stores the available transform types } if (!isTransform && !isResize && !isRotate) // when pointer not at resize or rotate position, check if it is directly on an object to evoke direct manipulation { // check if mouse just on an object, if so, direct manipulation mode var hoveredObj = this.getEditor().getTopmostBasicObjectAtCoord(currCoord, this.getCurrBoundInflation()); if (hoveredObj && !evokedByTouch) // mouse down directly on a object { //hoveredObj = hoveredObj.getNearestSelectableObject(); if (this.isInAncestorSelectMode()) hoveredObj = this.getStandaloneAncestor(hoveredObj); hoveredObj = hoveredObj.getNearestMovableObject(); if (this.getEnableMove()) { this.doStartDirectManipulate(null, hoveredObj, currCoord); // call doStartDirectManipulate rather than startDirectManipulate, avoid calling doStartDirectManipulate twice return; } } } // check if already has selection and mouse in selection rect first //if (this.getEditor().isCoordInSelectionMarkerBound(coord)) if (isTransform) { this.setState(S.MANIPULATING); this.setIsManipulatingSelection(true); this.setResizeStartingRegion(coordRegion); this.setRotateStartingRegion(rotateRegion); this.prepareManipulating(T.TRANSFORM, this.getEditor().getSelection(), currCoord, this.getEditor().getSelectionContainerBox()); } else if (isResize) { this.setState(S.MANIPULATING); this.setIsManipulatingSelection(true); this.setResizeStartingRegion(/*this.getEditor().getCoordRegionInSelectionMarker(coord)*/coordRegion); //console.log('box', this.getEditor().getUiSelectionAreaContainerBox()); this.prepareManipulating(T.RESIZE, this.getEditor().getSelection(), currCoord, this.getEditor().getSelectionContainerBox()); //console.log('Resize'); } else if (isMove) { //if (this.getEnableMove()) { this.setState(S.MANIPULATING); this.setIsManipulatingSelection(true); this.prepareManipulating(T.MOVE, this.getEditor().getSelection(), currCoord); } } else if (isRotate) { this.setState(S.MANIPULATING); this.setIsManipulatingSelection(true); this.setRotateStartingRegion(rotateRegion); this.prepareManipulating(T.ROTATE, this.getEditor().getSelection(), currCoord, this.getEditor().getSelectionContainerBox()); } else { /* var obj = this.getEditor().getTopmostBasicObjectAtCoord(currCoord, this.getCurrBoundInflation()); if (obj) // mouse down directly on a object { obj = obj.getNearestSelectableObject(); if (this.isInAncestorSelectMode()) obj = this.getStandaloneAncestor(obj); // only mouse down and moved will cause manupulating if (this.getEnableMove()) this.startDirectManipulate(null, obj, currCoord); } */ if (hoveredObj) // point on an object, direct move { if (this.getEnableMove()) this.startDirectManipulate(null, hoveredObj, currCoord); } else // pointer down on empty region, deselect old selection and prepare for new selecting { if (this.getEnableMove() && this.getEnableSelect() && this.getEditorConfigs().getInteractionConfigs().getEnableOffSelectionManipulation() && this.getEditor().hasSelection() && this.getEditor().isSelectionVisible()) { //console.log('enter suspend'); this.setState(S.SUSPENDING); // need wait for a while to determinate the actual operation var delay = this.getEditorConfigs().getInteractionConfigs().getOffSelectionManipulationActivatingTimeThreshold(); var shifted = e && e.getShiftKey(); this.setSuspendedOperations( this._startNewSelecting.bind(this, currCoord, shifted), this._startOffSelectionManipulation.bind(this, currCoord), delay ); //this._startOffSelectionManipulation(currCoord); } else if (this.getEnableSelect()) { var shifted = e && e.getShiftKey(); /* //this.getEditor().startSelectingBoxDrag(currCoord, shifted); //this.getEditor().setSelectMode(this.getSelectMode()); this.getEditor().startSelecting(currCoord, shifted); this.setState(S.SELECTING); */ this._startNewSelecting(currCoord, shifted); } } } }, /** * Do manipulation based on mouse/touch move step. * //@param {Hash} currCoord Current coord of pointer (mouse or touch) * //@param {Object} e Pointer (mouse or touch) event parameter. */ execManipulationStep: function(/*currCoord, e*/timeStamp) { if (this.getState() !== Kekule.Editor.BasicManipulationIaController.State.MANIPULATING) return false; var currCoord = this._manipulationStepBuffer.coord; var e = this._manipulationStepBuffer.event; var explicitTransformParams = this._manipulationStepBuffer.explicitTransformParams; //console.log('step', this.getState(), this._manipulationStepBuffer.explicitTransformParams); if (explicitTransformParams) // has transform params explicitly in gesture transform { this.doExecManipulationStepWithExplicitTransformParams(explicitTransformParams, this._manipulationStepBuffer); } else if (currCoord && e) { //console.log('do actual manipulate'); this.doExecManipulationStep(currCoord, e, this._manipulationStepBuffer); // empty buffer, indicating that the event has been handled } this._manipulationStepBuffer.coord = null; this._manipulationStepBuffer.event = null; this._manipulationStepBuffer.explicitTransformParams = null; /* if (this._lastTimeStamp) console.log('elpase', timeStamp - this._lastTimeStamp); this._lastTimeStamp = timeStamp; */ this._runManipulationStepId = Kekule.window.requestAnimationFrame(this.execManipulationStepBind); }, /** * Do actual manipulation based on mouse/touch move step. * Descendants may override this method. * @param {Hash} currCoord Current coord of pointer (mouse or touch) * @param {Object} e Pointer (mouse or touch) event parameter. */ doExecManipulationStep: function(currCoord, e, manipulationStepBuffer) { var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; var manipulateType = this.getManipulationType(); var editor = this.getEditor(); editor.beginUpdateObject(); try { this._isBusy = true; if (manipulateType === T.MOVE) { this.moveManipulatedObjs(currCoord); } else if (manipulateType === T.RESIZE) { //this.doResizeManipulatedObjs(currCoord); this.doTransformManipulatedObjs(manipulateType, currCoord); } else if (manipulateType === T.ROTATE) { //this.rotateManipulatedObjs(currCoord); this.doTransformManipulatedObjs(manipulateType, currCoord); } } finally { editor.endUpdateObject(); this._isBusy = false; } }, /** * Do actual manipulation based on mouse/touch move step. * Descendants may override this method. * @param {Hash} currCoord Current coord of pointer (mouse or touch) * @param {Object} e Pointer (mouse or touch) event parameter. */ doExecManipulationStepWithExplicitTransformParams: function(transformParams, manipulationStepBuffer) { var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; var manipulateType = this.getManipulationType(); if (manipulateType === T.TRANSFORM) { var editor = this.getEditor(); editor.beginUpdateObject(); try { this._isBusy = true; this.doTransformManipulatedObjs(manipulateType, null, transformParams); } finally { editor.endUpdateObject(); this._isBusy = false; } } }, /** * Refill the manipulationStepBuffer. * Descendants may override this method. * @param {Object} e Pointer (mouse or touch) event parameter. * @private */ updateManipulationStepBuffer: function(buffer, value) { Object.extend(buffer, value); /* buffer.coord = coord; buffer.event = e; */ }, // event handle methods /** @ignore */ react_pointermove: function(/*$super, */e) { this.tryApplySuper('react_pointermove', [e]) /* $super(e) */; if (this._isBusy) { return true; } if (Kekule.ObjUtils.notUnset(this.getActivePointerId()) && e.pointerId !== this.getActivePointerId()) { //console.log('hhh', e.pointerId, this.getActivePointerId()); return true; } var S = Kekule.Editor.BasicManipulationIaController.State; var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; var state = this.getState(); var coord = this._getEventMouseCoord(e); var distanceFromLast; if (state === S.NORMAL || state === S.SUSPENDING) { if (this._lastMouseMoveCoord) { var dis = Kekule.CoordUtils.getDistance(coord, this._lastMouseMoveCoord); distanceFromLast = dis; if (dis < 4) // less than 4 px, too tiny to react { return true; } } } this._lastMouseMoveCoord = coord; /* if (state !== S.NORMAL) this.getEditor().hideHotTrack(); if (state === S.NORMAL) { // in normal state, if mouse moved to boundary of a object, it may be highlighted this.getEditor().hotTrackOnCoord(coord); } else */ if (state === S.SUSPENDING) { var disThreshold = this.getEditorConfigs().getInteractionConfigs().getUnmovePointerDistanceThreshold() || 0; if (Kekule.ObjUtils.notUnset(distanceFromLast) && (distanceFromLast > disThreshold)) this.execSuspendedImmediateOperation(); } if (state === S.SELECTING) { if (this.getEnableSelect()) { //this.getEditor().dragSelectingBoxToCoord(coord); this.getEditor().addSelectingAnchorCoord(coord); } e.preventDefault(); } else if (state === S.MANIPULATING) // move or resize objects { //console.log('mouse move', coord); this.updateManipulationStepBuffer(this._manipulationStepBuffer, {'coord': coord, 'event': e}); //this.execManipulationStep(coord, e); e.preventDefault(); } return true; }, /** @private */ react_pointerdown: function(/*$super, */e) { this.tryApplySuper('react_pointerdown', [e]) /* $super(e) */; //console.log('pointerdown', e); this.setActivePointerId(e.pointerId); var S = Kekule.Editor.BasicManipulationIaController.State; //var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; if (e.getButton() === Kekule.X.Event.MouseButton.LEFT) { this._lastMouseMoveCoord = null; var coord = this._getEventMouseCoord(e); if ((this.getState() === S.NORMAL)/* && (this.getEditor().getMouseLBtnDown()) */) { //var evokedByTouch = e && e.pointerType === 'touch'; var self = this; var beginNormalManipulation = function(){ if (self.getState() === S.NORMAL || self.getState() === S.SUSPENDING) { self.startManipulation(coord, e); e.preventDefault(); } }; this.setState(S.SUSPENDING); // wait for a while for the possible gesture operations this.setSuspendedOperations(beginNormalManipulation, beginNormalManipulation, 50); } } else if (e.getButton() === Kekule.X.Event.MouseButton.RIGHT) { //if (this.getEnableMove()) { if (this.getState() === S.MANIPULATING) // when click right button on manipulating, just cancel it. { this.cancelManipulate(); this.setState(S.NORMAL); e.stopPropagation(); e.preventDefault(); } else if (this.getState() === S.SUSPENDING) this.haltSuspendedOperations(); } } return true; }, /** @private */ react_pointerup: function(e) { if (e.getButton() === Kekule.X.Event.MouseButton.LEFT) { var coord = this._getEventMouseCoord(e); this.setEndCoord(coord); var startCoord = this.getStartCoord(); var endCoord = coord; var shifted = e.getShiftKey(); var S = Kekule.Editor.BasicManipulationIaController.State; if (this.getState() === S.SUSPENDING) // done suspended first, then finish the operation this.execSuspendedImmediateOperation(); var state = this.getState(); if (state === S.SELECTING) // mouse up, end selecting { //this.getEditor().endSelectingBoxDrag(coord, shifted); this.getEditor().endSelecting(coord, shifted || this.getEditor().getIsToggleSelectOn()); this.setState(S.NORMAL); e.preventDefault(); var editor = this.getEditor(); editor.endManipulateObject(); } else if (state === S.MANIPULATING) { //var dis = Kekule.CoordUtils.getDistance(startCoord, endCoord); //if (dis <= this.getEditorConfigs().getInteractionConfigs().getUnmovePointerDistanceThreshold()) if (startCoord && endCoord && Kekule.CoordUtils.isEqual(startCoord, endCoord)) // mouse down and up in same point, not manupulate, just select a object { if (this.getEnableSelect()) this.getEditor().selectOnCoord(startCoord, shifted || this.getEditor().getIsToggleSelectOn()); } else // move objects to new pos { this.manipulateBeforeStopping(); /* if (this.getEnableMove()) { //this.moveManipulatedObjs(coord); //this.endMoving(); // add operation to editor's historys this.addOperationToEditor(); } */ this.addOperationToEditor(); } this.stopManipulate(); this.setState(S.NORMAL); e.preventDefault(); } } return true; }, /** @private */ react_mousewheel: function(/*$super, */e) { if (e.getCtrlKey()) { var state = this.getState(); if (state === Kekule.Editor.BasicManipulationIaController.State.NORMAL) { // disallow mouse zoom during manipulation return this.tryApplySuper('react_mousewheel', [e]) /* $super(e) */; } e.preventDefault(); } }, /* @private */ /* react_keyup: function(e) { var keyCode = e.getKeyCode(); switch (keyCode) { case 46: // delete { if (this.getEnableRemove()) this.removeSelection(); } } } */ //////////////////// Hammer Gesture event handlers /////////////////////////// /** @private */ _isGestureManipulationEnabled: function() { return this.getEditorConfigs().getInteractionConfigs().getEnableGestureManipulation(); }, /** @private */ _isGestureZoomOnEditorEnabled: function() { return this.getEditorConfigs().getInteractionConfigs().getEnableGestureZoomOnEditor(); }, /** @private */ _isInGestureManipulation: function() { return !!this._initialGestureTransformParams; }, /** @private */ _isGestureZoomOnEditor: function() { return !!this._initialGestureZoomLevel; }, /** * Starts a gesture transform. * @param {Object} event * @private */ beginGestureTransform: function(event) { if (this.getEditor().hasSelection()) { this._initialGestureZoomLevel = null; if (this._isGestureManipulationEnabled()) { this.haltSuspendedOperations(); // halt possible touch hold manipulations // stores initial gesture transform params this._initialGestureTransformParams = { 'angle': (event.rotation * Math.PI / 180) || 0 }; //console.log('begin gesture manipulation', this.getState(), this.getManipulationType()); // start a brand new one if (this.getState() !== Kekule.Editor.BasicManipulationIaController.State.MANIPULATING) { this.startManipulation(null, null, Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM); } else { if (this.getManipulationType() !== Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM) { // the gesture event may be evoked after pointerdown event, // and in pointerdown, a calling to startManipulation without transform may be already called. // So here we force a new manipulation with transform on. //this.setManipulationType(Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM); this.startManipulation(null, null, Kekule.Editor.BasicManipulationIaController.ManipulationType.TRANSFORM); } } } else this._initialGestureTransformParams = null; } else if (this._isGestureZoomOnEditorEnabled()) // zoom on editor { this.getEditor().cancelSelecting(); // force store the selecting this.setState(Kekule.Editor.BasicManipulationIaController.State.NORMAL); this._initialGestureZoomLevel = this.getEditor().getZoom(); } }, /** * Ends a gesture transform. * @private */ endGestureTransform: function() { if (this.getState() === Kekule.Editor.BasicManipulationIaController.State.MANIPULATING) // stop prev manipulation first { if (this._isInGestureManipulation()) { this.manipulateBeforeStopping(); this.addOperationToEditor(); this.stopManipulate(); this.setState(Kekule.Editor.BasicManipulationIaController.State.NORMAL); this._initialGestureTransformParams = null; } } if (this._isGestureZoomOnEditor()) { this._initialGestureZoomLevel = null; } }, /** * Do a new transform step according to received event. * @param {Object} e Gesture event received. * @private */ doGestureTransformStep: function(e) { var T = Kekule.Editor.BasicManipulationIaController.ManipulationType; if ((this.getState() === Kekule.Editor.BasicManipulationIaController.State.MANIPULATING) && (this.getManipulationType() === T.TRANSFORM) && (this._isInGestureManipulation())) { var availTransformTypes = this._availTransformTypes || []; // get transform params from event directly var center = this.getRotateCenter(); // use the center of current editor selection var resizeScales, rotateAngle; if (availTransformTypes.indexOf(T.RESIZE) >= 0) { var scale = e.scale; resizeScales = this._calcActualResizeScales(this.getManipulateObjs(), {'scaleX': scale, 'scaleY': scale}); } else resizeScales = {'scaleX': 1, 'scaleY': 1}; if (availTransformTypes.indexOf(T.ROTATE) >= 0) { var absAngle = e.rotation * Math.PI / 180; var rotateAngle = absAngle - this._initialGestureTransformParams.angle; // get actual rotation angle rotateAngle = this._calcActualRotateAngle(this.getManipulateObjs(), rotateAngle, this._initialGestureTransformParams.angle, absAngle); } else { rotateAngle = 0; } //console.log('here', resizeScales.scaleX, resizeScales.scaleY, rotateAngle, availTransformTypes); this.updateManipulationStepBuffer(this._manipulationStepBuffer, { 'explicitTransformParams': { 'center': center, 'scaleX': resizeScales.scaleX, 'scaleY': resizeScales.scaleY, 'rotateAngle': rotateAngle //'rotateDegree': e.rotation, //'event': e } }); e.preventDefault(); } else if (this._isGestureZoomOnEditor()) { var editor = this.getEditor(); var scale = e.scale; var initZoom = this._initialGestureZoomLevel; editor.zoomTo(initZoom * scale, null, e.center); } }, /** @ignore */ react_rotatestart: function(e) { if (this.getEnableGestureManipulation()) this.beginGestureTransform(e); }, /** @ignore */ react_rotate: function(e) { if (this.getEnableGestureManipulation()) this.doGestureTransformStep(e); }, /** @ignore */ react_rotateend: function(e) { if (this.getEnableGestureManipulation()) this.endGestureTransform(); }, /** @ignore */ react_rotatecancel: function(e) { if (this.getEnableGestureManipulation()) this.endGestureTransform(); }, /** @ignore */ react_pinchstart: function(e) { if (this.getEnableGestureManipulation()) this.beginGestureTransform(e); }, /** @ignore */ react_pinchmove: function(e) { if (this.getEnableGestureManipulation()) this.doGestureTransformStep(e); }, /** @ignore */ react_pinchend: function(e) { if (this.getEnableGestureManipulation()) this.endGestureTransform(); }, /** @ignore */ react_pinchcancel: function(e) { if (this.getEnableGestureManipulation()) this.endGestureTransform(); } }); /** * Enumeration of state of a {@link Kekule.Editor.BasicManipulationIaController}. * @class */ Kekule.Editor.BasicManipulationIaController.State = { /** Normal state. */ NORMAL: 0, /** Is selecting objects. */ SELECTING: 1, /** Is manipulating objects (e.g. changing object position). */ MANIPULATING: 2, /** * The pointer is down, but need to wait to determinate if there will be a gesture event. */ WAITING: 10, /** * Just put down pointer, if move the pointer immediately, selecting state will be open. * But if hold down still for a while, it may turn to manipulating state to move current selected objects. */ SUSPENDING: 11 }; /** * Enumeration of manipulation types of a {@link Kekule.Editor.BasicManipulationIaController}. * @class */ Kekule.Editor.BasicManipulationIaController.ManipulationType = { MOVE: 0, ROTATE: 1, RESIZE: 2, TRANSFORM: 4 // scale and rotate simultaneously by touch }; /** @ignore */ Kekule.Editor.IaControllerManager.register(Kekule.Editor.BasicManipulationIaController, Kekule.Editor.BaseEditor); })();
partridgejiang/Kekule.js
src/widgets/chem/editor/kekule.chemEditor.baseEditors.js
JavaScript
mit
258,521
export interface DragDelta { x: number y: number } let targets: HTMLElement[] = [] export function getDragDeltas ( onDragDelta: (d: DragDelta) => void, onMouseDown?: (e?: MouseEvent) => void ) { let oldX = 0 let oldY = 0 let target: HTMLElement function onmousedown (e: MouseEvent) { target = e.currentTarget as HTMLElement targets.push(target) oldX = e.clientX oldY = e.clientY document.addEventListener('mousemove', onMouseMove) document.addEventListener('mouseup', onMouseUp) onMouseDown && onMouseDown(e) } function onMouseUp () { document.removeEventListener('mousemove', onMouseMove) document.removeEventListener('mouseup', onMouseUp) targets = targets.filter(t => t !== target) } function onMouseMove (e: MouseEvent) { for (const t of targets) { if (t !== target && target.contains(t)) return } onDragDelta({ x: oldX - e.clientX, y: oldY - e.clientY }) oldX = e.clientX oldY = e.clientY } return { onmousedown } }
trivial-space/flow-tools
lib/utils/component-helpers.ts
TypeScript
mit
984
package com.kensenter.p2poolwidget; import android.content.Context; import android.content.SharedPreferences; public class GetPrefs { public static final String PREFS_NAME = "p2poolwidgetprefs"; public String GetWidget(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("servername", null); } public String GetServer(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("servername", ""); } public String getPayKey(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("paykey", ""); } public Integer getPort(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getInt("portnum", 3332); } public Integer getHashLevel(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getInt("hashlevel", 2); } public Integer getAlertRate(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getInt("alertnum", 0); } public Integer getDOARate(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getInt("doanum", 50); } public String getEfficiency(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("efficiency", ""); } public String getUptime(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("uptime", ""); } public String getShares(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("shares", ""); } public String getTimeToShare(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("toshare", ""); } public String getRoundTime(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("roundtime", ""); } public String getTimeToBlock(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("toblock", ""); } public String getBlockValue(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("blockvalue", ""); } public String getPoolRate(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getString("pool_rate", ""); } public boolean getRemoveLine(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getBoolean("removeline", false); } public boolean getAlertOn(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getBoolean("alerton", true); } public boolean getDOAOn(Context ctxt, int WidgetId){ SharedPreferences settings = ctxt.getSharedPreferences(PREFS_NAME+WidgetId, 0); return settings.getBoolean("doaon", true); } }
ksenter/P2PoolWidget
src/com/kensenter/p2poolwidget/GetPrefs.java
Java
mit
3,843
<?php namespace OC\PlatformBundle\Entity; use Doctrine\ORM\Mapping as ORM; use OC\PlatformBundle\Entity\Advert; /** Une annonce peut contenir plusieurs candidatures, alors qu'une candidature n'appartient qu'à une seule annonce */ /** * @ORM\Table(name="application") * @ORM\Entity(repositoryClass="OC\PlatformBundle\Repository\ApplicationRepository") */ class Application { /** * @ORM\ManyToOne(targetEntity="OC\PlatformBundle\Entity\Advert", inversedBy="applications") * @ORM\JoinColumn(nullable=false) */ private $advert; /** * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(name="author", type="string", length=255) */ private $author; /** * @ORM\Column(name="content", type="text") */ private $content; /** * @ORM\Column(name="date", type="datetime") */ private $date; public function __construct() { $this->date = new \Datetime(); } public function getId() { return $this->id; } public function setAuthor($author) { $this->author = $author; return $this; } public function getAuthor() { return $this->author; } public function setContent($content) { $this->content = $content; return $this; } public function getContent() { return $this->content; } public function setDate(\DateTimeInterface $date) { $this->date = $date; return $this; } public function getDate() { return $this->date; } public function setAdvert(Advert $advert) { $this->advert = $advert; return $this; } public function getAdvert() { return $this->advert; } }
walter-da-costa/sf2project
src/OC/PlatformBundle/Entity/Application.php
PHP
mit
1,858
package com.gulj.common.util; import java.io.UnsupportedEncodingException; public enum FeijianCode { SAVE_SUCCESS("0001","保存成功"), SAVE_ERROR("0002","保存失败"), UPDATE_SUCCESS("0003","修改成功"), UPDATE_ERROR("0004","修改失败"), DELETE_SUCCESS("0005","删除成功"), DELETE_ERROR("0006","删除失败"), USERORPWD_ERROR("0007","用户名或者密码不正确"), USEROR_ERROR("0008","账号不存在"), USER_FIBINDDEN_ERROR("0009","账号被禁止"), CODE_ERROR("0010","验证码不正确"), USER_EXIST_ERROR("0011","帐号已存在"), USEROR_LOGIN_SUCCESS("0012","登录成功"), USEROR_NONE_TOP_MENU("0013","无顶级菜单,请联系系统管理员进行权限分配"), USEROR_NONE_CHILD_MENU("0014","无子级菜单,请联系系统管理员进行权限分配"), SYS_EXCEPTION("1100","系统异常"),; /** 错误码 */ private final String code; /** 错误吗对应描述信息 */ private final String info; FeijianCode(String code, String info) { this.code = code; this.info = info; } public String getCode() { return code; } public String getInfo() { return info; } @SuppressWarnings("finally") @Override public String toString() { String result = "{\"code\":"+"\""+this.code+"\""+",\"message\":"+"\""+this.info+"\""+"}"; try { result = new String(result.getBytes("utf-8"), "utf-8"); } catch (UnsupportedEncodingException e) { result = e.getMessage(); e.printStackTrace(); } finally{ return result; } } }
gulijian/joingu
gulj-common-util/src/main/java/com/gulj/common/util/FeijianCode.java
Java
mit
1,732
<?php namespace App; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Database\Eloquent\Model as Eloquent; class User extends Authenticatable { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'username', 'email', 'password','firstname','lastname' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; }
Pelkar/Timeo
laravel/app/User.php
PHP
mit
522
#region MIT // /*The MIT License (MIT) // // Copyright 2016 lizs lizs4ever@163.com // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // * */ #endregion using System; using System.Collections.Generic; namespace Pi.Framework { public interface IProperty { #region Êý¾Ý²Ù×÷ void Inject(IEnumerable<IBlock> blocks); List<T> GetList<T>(short pid); bool Inject(IBlock block); bool Inc<T>(short pid, T delta); bool Inc(short pid, object delta); bool Inc<T>(short pid, T delta, out T overflow); bool Inc(short pid, object delta, out object overflow); bool IncTo<T>(short pid, T target); bool IncTo(short pid, object target); bool Set<T>(short pid, T value); bool Set(short pid, object value); int IndexOf<T>(short pid, T item); int IndexOf<T>(short pid, Predicate<T> condition); T GetByIndex<T>(short pid, int idx); bool Add<T>(short pid, T value); bool Add(short pid, object value); bool AddRange<T>(short pid, List<T> items); bool Remove<T>(short pid, T item); bool Remove(short pid, object item); bool RemoveAll<T>(short pid, Predicate<T> predicate); bool RemoveAll<T>(short pid, Predicate<T> predicate, out int count); bool RemoveAll(short pid); bool RemoveAll(short pid, out int count); bool Insert<T>(short pid, int idx, T item); bool Insert(short pid, int idx, object item); bool Replace<T>(short pid, int idx, T item); bool Swap<T>(short pid, int idxA, int idxB); #endregion } }
lizs/Pi
Pi.Framework/ecs/entity/IProperty.cs
C#
mit
2,676
from django.contrib import admin try: from django.contrib.auth import get_permission_codename except ImportError: # pragma: no cover # Django < 1.6 def get_permission_codename(action, opts): return '%s_%s' % (action, opts.object_name.lower()) class ObjectPermissionsModelAdminMixin(object): def has_change_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): opts = self.opts codename = get_permission_codename('delete', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) class ObjectPermissionsInlineModelAdminMixin(ObjectPermissionsModelAdminMixin): def has_change_permission(self, request, obj=None): # pragma: no cover opts = self.opts if opts.auto_created: for field in opts.fields: if field.rel and field.rel.to != self.parent_model: opts = field.rel.to._meta break codename = get_permission_codename('change', opts) return request.user.has_perm('%s.%s' % (opts.app_label, codename), obj) def has_delete_permission(self, request, obj=None): # pragma: no cover if self.opts.auto_created: return self.has_change_permission(request, obj) return super(ObjectPermissionsInlineModelAdminMixin, self).has_delete_permission(request, obj) class ObjectPermissionsModelAdmin(ObjectPermissionsModelAdminMixin, admin.ModelAdmin): pass class ObjectPermissionsStackedInline(ObjectPermissionsInlineModelAdminMixin, admin.StackedInline): pass class ObjectPermissionsTabularInline(ObjectPermissionsInlineModelAdminMixin, admin.TabularInline): pass
smcoll/django-rules
rules/contrib/admin.py
Python
mit
1,879
/* MIT License Copyright (c) 2022 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ export * from './Slider'
looker-open-source/components
packages/components/src/Form/Inputs/Slider/index.ts
TypeScript
mit
1,135
using Google.Protobuf; using PoGo.ApiClient.Authentication; using PoGo.ApiClient.Enums; using PoGo.ApiClient.Exceptions; using PoGo.ApiClient.Helpers; using PoGo.ApiClient.Interfaces; using PoGo.ApiClient.Rpc; using POGOProtos.Networking.Envelopes; using POGOProtos.Networking.Requests; using POGOProtos.Networking.Requests.Messages; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace PoGo.ApiClient { /// <summary> /// /// </summary> public partial class PokemonGoApiClient : HttpClient, IPokemonGoApiClient { #region Private Members /// <summary> /// /// </summary> internal CancellationTokenSource CancellationTokenSource; /// <summary> /// /// </summary> /// <remarks> /// We're getting a new RequestBuilder every time we call this property. /// </remarks> internal RequestBuilder RequestBuilder => new RequestBuilder(AuthenticatedUser, CurrentPosition, DeviceProfile, StartTime); /// <summary> /// /// </summary> private static readonly HttpClientHandler Handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate, AllowAutoRedirect = false }; /// <summary> /// /// </summary> private readonly List<RequestType> _singleRequests = new List<RequestType> { RequestType.GetPlayer, }; #endregion #region Properties /// <summary> /// /// </summary> public IApiSettings ApiSettings { get; } /// <summary> /// /// </summary> public string ApiUrl { get; set; } /// <summary> /// /// </summary> public AuthenticatedUser AuthenticatedUser { get; set; } /// <summary> /// /// </summary> public GeoCoordinate CurrentPosition { get; set; } /// <summary> /// /// </summary> public IAuthenticationProvider CurrentProvider { get; private set; } /// <summary> /// /// </summary> public IDeviceProfile DeviceProfile { get; } /// <summary> /// /// </summary> public IDownloadClient Download { get; } /// <summary> /// /// </summary> public IEncounterClient Encounter { get; } /// <summary> /// /// </summary> public IFortClient Fort { get; } /// <summary> /// /// </summary> public IInventoryClient Inventory { get; } /// <summary> /// /// </summary> public IMapClient Map { get; } /// <summary> /// /// </summary> public IPlayerClient Player { get; } /// <summary> /// /// </summary> internal BlockingCollection<RequestEnvelope> RequestQueue { get; } /// <summary> /// /// </summary> public DateTimeOffset StartTime { get; } #endregion #region Constructors /// <summary> /// /// </summary> public PokemonGoApiClient() : base(Handler) { DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", Constants.HttpClientUserAgent); DefaultRequestHeaders.ExpectContinue = false; DefaultRequestHeaders.TryAddWithoutValidation("Connection", Constants.HttpClientConnection); DefaultRequestHeaders.TryAddWithoutValidation("Accept", Constants.HttpClientAccept); DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", Constants.HttpClientContentType); } /// <summary> /// /// </summary> /// <param name="settings"></param> /// <param name="deviceProfile"></param> /// <param name="authenticatedUser"></param> public PokemonGoApiClient(IApiSettings settings, IDeviceProfile deviceProfile, AuthenticatedUser authenticatedUser = null) : this() { StartTime = DateTimeOffset.UtcNow; CancellationTokenSource = new CancellationTokenSource(); RequestQueue = new BlockingCollection<RequestEnvelope>(); Player = new PlayerClient(this); Download = new DownloadClient(this); Inventory = new InventoryClient(this); Map = new MapClient(this); Fort = new FortClient(this); Encounter = new EncounterClient(this); ApiSettings = settings; DeviceProfile = deviceProfile; SetAuthenticationProvider(); AuthenticatedUser = authenticatedUser; Player.SetCoordinates(ApiSettings.DefaultPosition.Latitude, ApiSettings.DefaultPosition.Longitude, ApiSettings.DefaultPosition.Accuracy); } #endregion #region Public Methods /// <summary> /// /// </summary> /// <returns></returns> public async Task AuthenticateAsync() { CancelPendingRequests(); if (AuthenticatedUser == null || AuthenticatedUser.IsExpired) { AuthenticatedUser = await CurrentProvider.GetAuthenticatedUser().ConfigureAwait(false); } // @robertmclaws: We're going to bypass the queue here. var envelope = RequestBuilder.GetInitialRequestEnvelope( new Request { RequestType = RequestType.GetPlayer, RequestMessage = new GetPlayerMessage().ToByteString() }, new Request { RequestType = RequestType.CheckChallenge, RequestMessage = new CheckChallengeMessage().ToByteString() } ); var result = await PostProtoPayload(ApiUrl, envelope); ProcessMessages(result); // @robertmclaws: Not sure if this is right, but should allow the queue to start filling back up. CancellationTokenSource = new CancellationTokenSource(); } /// <summary> /// /// </summary> /// <param name="credentials"></param> /// <returns></returns> public async Task AuthenticateAsync(PoGoCredentials credentials) { ApiSettings.Credentials = credentials; await AuthenticateAsync(); } /// <summary> /// Triggers any currently-executing requests to cancel ASAP. This will also have the effect of clearing the <see cref="RequestQueue"/>. /// </summary> public void CancelCurrentRequests() { CancellationTokenSource.Cancel(); } /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="requestType"></param> /// <returns></returns> /// <remarks> /// robertmclaws: Every request will have a minimum of two payloads. So no single-payload results anymore. /// </remarks> public bool QueueRequest(RequestType requestType, IMessage message) { var envelope = BuildRequestEnvelope(requestType, message); return RequestQueue.TryAdd(envelope); } /// <summary> /// /// </summary> public void SetAuthenticationProvider() { switch (ApiSettings.Credentials.AuthenticationProvider) { case AuthenticationProviderTypes.Google: CurrentProvider = new GoogleAuthenticationProvider(ApiSettings.Credentials.Username, ApiSettings.Credentials.Password); break; case AuthenticationProviderTypes.PokemonTrainerClub: CurrentProvider = new PtcAuthenticationProvider(ApiSettings.Credentials.Username, ApiSettings.Credentials.Password); break; default: throw new ArgumentOutOfRangeException(nameof(ApiSettings.Credentials.AuthenticationProvider), "Unknown AuthType"); } } /// <summary> /// /// </summary> /// <returns></returns> public Task StartProcessingRequests() { return Task.Factory.StartNew(async () => { foreach (var workItem in RequestQueue.GetConsumingEnumerable()) { // robertmclaws: The line below should collapse the queue quickly. if (CancellationTokenSource.IsCancellationRequested) { Logger.Write("A queued request was cancelled before it was processed."); continue; } var response = await PostProtoPayload(ApiUrl, workItem); // robertmclaws: If the request cancelled out for some reason, let's move on. if (response == null) continue; ProcessMessages(response); } }, TaskCreationOptions.LongRunning); } #endregion #region Private Methods /// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="requestType"></param> /// <returns></returns> internal RequestEnvelope BuildRequestEnvelope(RequestType requestType, IMessage message) { RequestEnvelope envelope = null; if (_singleRequests.Contains(requestType)) { envelope = RequestBuilder.GetRequestEnvelope( new Request { RequestType = requestType, RequestMessage = message.ToByteString() }, new Request { RequestType = RequestType.CheckChallenge, RequestMessage = new CheckChallengeMessage().ToByteString() } ); } else { var getInventoryMessage = new GetInventoryMessage { LastTimestampMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }; var downloadSettingsMessage = new DownloadSettingsMessage { Hash = Download.DownloadSettingsHash }; envelope = RequestBuilder.GetRequestEnvelope( new Request { RequestType = requestType, RequestMessage = message.ToByteString() }, new Request { RequestType = RequestType.GetHatchedEggs, RequestMessage = new GetHatchedEggsMessage().ToByteString() }, new Request { RequestType = RequestType.GetInventory, RequestMessage = getInventoryMessage.ToByteString() }, new Request { RequestType = RequestType.CheckAwardedBadges, RequestMessage = new CheckAwardedBadgesMessage().ToByteString() }, new Request { RequestType = RequestType.DownloadSettings, RequestMessage = downloadSettingsMessage.ToByteString() }, new Request { RequestType = RequestType.CheckChallenge, RequestMessage = new CheckChallengeMessage().ToByteString() } ); } envelope.ExpectedResponseTypes = new List<Type>(ResponseMessageMapper.GetExpectedResponseTypes(envelope.Requests)); return envelope; } /// <summary> /// /// </summary> /// <param name="url"></param> /// <param name="requestEnvelope"></param> /// <returns></returns> /// <remarks></remarks> internal async Task<IMessage[]> PostProtoPayload(string url, RequestEnvelope requestEnvelope) { // robertmclaws: Start by preparing the results array based on the types we're expecting to be returned. var result = new IMessage[requestEnvelope.ExpectedResponseTypes.Count - 1]; for (var i = 0; i < requestEnvelope.ExpectedResponseTypes.Count - 1; i++) { result[i] = Activator.CreateInstance(requestEnvelope.ExpectedResponseTypes[i]) as IMessage; if (result[i] == null) { throw new ArgumentException($"ResponseType {i} is not an IMessage"); } } // robertmclaws: We're not using the strategy pattern here anymore. Specific requests will be retried as needed. // For example, there's no need to retry a map request when another will come along in 5 seconds. // Since the function we're calling is now recursive, let's make sure we only encode the payload once. var byteArrayContent = new ByteArrayContent(requestEnvelope.ToByteString().ToByteArray()); var retryPolicy = RetryPolicyManager.GetRetryPolicy(requestEnvelope.Requests[0].RequestType); var response = await PostProto(url, byteArrayContent, retryPolicy, CancellationTokenSource.Token); if (response == null || response.Returns.Count == 0) { // robertmclaws: We didn't get anything back after several attempts. Let's bounce. return null; } // robertmclaws: Now marry up the results from the service whith the type instances we already created. for (var i = 0; i < requestEnvelope.ExpectedResponseTypes.Count - 1; i++) { var item = response.Returns[i]; result[i].MergeFrom(item); } return result; } /// <summary> /// /// </summary> /// <param name="url"></param> /// <param name="payload"></param> /// <param name="retryPolicy"></param> /// <param name="token"></param> /// <param name="attemptCount"></param> /// <param name="redirectCount"></param> /// <returns></returns> internal async Task<ResponseEnvelope> PostProto(string url, ByteArrayContent payload, RetryPolicy retryPolicy, CancellationToken token, int attemptCount = 0, int redirectCount = 0) { // robertmclaws: If someone wants us to be done, we're done. if (token.IsCancellationRequested) { Logger.Write("The request was cancelled. (PostProto cancellation check)"); return null; } attemptCount++; // robertmclaws: If we've exceeded the maximum number of attempts, we're done. if (attemptCount > retryPolicy.MaxFailureAttempts) { Logger.Write("The request exceeded the number of retries allowed and has been cancelled."); return null; } if (redirectCount > retryPolicy.MaxRedirectAttempts) { Logger.Write("The request exceeded the number of redirect attempts allowed and has been cancelled."); return null; } // robertmclaws: We're gonna keep going, so let's be pro-active about token failures, instead of reactive. if (AuthenticatedUser == null || AuthenticatedUser.IsExpired) { // @robertmclaws: Calling "Authenticate" cancels all current requests and fires off a complex login routine. // More than likely, we just want to refresh the tokens. await CurrentProvider.GetAuthenticatedUser().ConfigureAwait(false); } var result = await PostAsync(url, payload, token); var response = new ResponseEnvelope(); var responseData = await result.Content.ReadAsByteArrayAsync(); using (var codedStream = new CodedInputStream(responseData)) { response.MergeFrom(codedStream); } switch ((StatusCodes)response.StatusCode) { case StatusCodes.ValidResponse: if (response.AuthTicket != null) { Logger.Write("Received a new AuthTicket from the Api!"); AuthenticatedUser.AuthTicket = response.AuthTicket; // robertmclaws to do: See if we need to clone the AccessToken so we don't have a threading violation. RaiseAuthenticatedUserUpdated(AuthenticatedUser); } return response; case StatusCodes.AccessDenied: Logger.Write("Account has been banned. Our condolences for your loss."); CancelCurrentRequests(); //RequestQueue.CompleteAdding(); // robertmclaws to do: Allow you to stop adding events to the queue, and re-initialize the queue if needed. throw new AccountLockedException(); case StatusCodes.Redirect: if (!Regex.IsMatch(response.ApiUrl, "pgorelease\\.nianticlabs\\.com\\/plfe\\/\\d+")) { throw new Exception($"Received an incorrect API url '{response.ApiUrl}', status code was '{response.StatusCode}'."); } ApiUrl = $"https://{response.ApiUrl}/rpc"; Logger.Write($"Received an updated API url = {ApiUrl}"); // robertmclaws to do: Check to see if redirects should count against the RetryPolicy. await Task.Delay(retryPolicy.DelayInSeconds * 1000); redirectCount++; return await PostProto(response.ApiUrl, payload, retryPolicy, token, attemptCount, redirectCount); case StatusCodes.InvalidToken: Logger.Write("Received StatusCode 102, reauthenticating."); AuthenticatedUser?.Expire(); // robertmclaws: trigger a retry here. We'll automatically try to log in again on the next request. await Task.Delay(retryPolicy.DelayInSeconds * 1000); return await PostProto(response.ApiUrl, payload, retryPolicy, token, attemptCount, redirectCount); case StatusCodes.ServerOverloaded: // Per @wallycz, on code 52, wait 11 seconds before sending the request again. Logger.Write("Server says to slow the hell down. Try again in 11 sec."); await Task.Delay(11000); return await PostProto(response.ApiUrl, payload, retryPolicy, token, attemptCount, redirectCount); default: Logger.Write($"Unknown status code: {response.StatusCode}"); break; } return response; } #endregion } }
PoGo-Devs/PoGo
src/PoGo.ApiClient/PokemonGoApiClient.cs
C#
mit
19,829
var sys = require('pex-sys'); var glu = require('pex-glu'); var geom = require('pex-geom'); var gen = require('pex-gen'); var materials = require('pex-materials'); var color = require('pex-color'); var gui = require('pex-gui'); var Cube = gen.Cube; var Sphere = gen.Sphere; var Mesh = glu.Mesh; var TexturedCubeMap = materials.TexturedCubeMap; var SkyBox = materials.SkyBox; var PerspectiveCamera = glu.PerspectiveCamera; var Arcball = glu.Arcball; var Color = color.Color; var TextureCube = glu.TextureCube; var GUI = gui.GUI; sys.Window.create({ settings: { width: 1280, height: 720, type: '3d', fullscreen: sys.Platform.isBrowser }, lod: 4, init: function() { this.gui = new GUI(this); this.gui.addParam('Mipmap level', this, 'lod', { min: 0, max: 8, step: 1 }); var levels = ['m00']; var sides = ['c00', 'c01', 'c02', 'c03', 'c04', 'c05']; var cubeMapFiles = []; levels.forEach(function(level) { sides.forEach(function(side) { cubeMapFiles.push('../../assets/cubemaps/uffizi_lod/uffizi_' + level + '_' + side + '.png'); }); }); var cubeMap = TextureCube.load(cubeMapFiles, { mipmap: true }); this.mesh = new Mesh(new Sphere(), new TexturedCubeMap({ texture: cubeMap })); this.cubeMesh = new Mesh(new Cube(50), new SkyBox({ texture: cubeMap })); this.camera = new PerspectiveCamera(60, this.width / this.height); this.arcball = new Arcball(this, this.camera); }, draw: function() { if (!this.mesh.material.uniforms.texture.ready) return; glu.clearColorAndDepth(Color.Black); glu.enableDepthReadAndWrite(true); this.cubeMesh.material.uniforms.lod = this.lod; this.cubeMesh.draw(this.camera); this.mesh.draw(this.camera); this.mesh.material.uniforms.lod = this.lod; this.gui.draw(); } });
szymonkaliski/pex-examples
src/glu.TextureCube.mipmap/main.js
JavaScript
mit
1,828
// namespace line first import * as XA from "X"; import XD, { X2 } from "X"; import { X3 } from "X";
r-murphy/babel-plugin-ui5
packages/plugin/__test__/fixtures/imports/import-duplicate-src-1.js
JavaScript
mit
101
<?php namespace ONGR\CookiesBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use ONGR\CookiesBundle\DependencyInjection\Compiler\CookieCompilerPass; /** * This class is used to register component into Symfony app kernel. */ class ONGRCookiesBundle extends Bundle { /** * {@inheritdoc} */ public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new CookieCompilerPass()); } }
ongr-io/CookiesBundle
ONGRCookiesBundle.php
PHP
mit
542
import { IFilterOptionDef } from '../../interfaces/iFilter'; import { IScalarFilterParams } from './scalarFilter'; import { ISimpleFilterParams } from './simpleFilter'; import { every } from '../../utils/array'; /* Common logic for options, used by both filters and floating filters. */ export class OptionsFactory { protected customFilterOptions: { [name: string]: IFilterOptionDef; } = {}; protected filterOptions: (IFilterOptionDef | string)[]; protected defaultOption: string; public init(params: IScalarFilterParams, defaultOptions: string[]): void { this.filterOptions = params.filterOptions || defaultOptions; this.mapCustomOptions(); this.selectDefaultItem(params); } public getFilterOptions(): (IFilterOptionDef | string)[] { return this.filterOptions; } private mapCustomOptions(): void { if (!this.filterOptions) { return; } this.filterOptions.forEach(filterOption => { if (typeof filterOption === 'string') { return; } const requiredProperties: (keyof IFilterOptionDef)[] = ['displayKey', 'displayName', 'test']; if (every(requiredProperties, key => { if (!filterOption[key]) { console.warn(`ag-Grid: ignoring FilterOptionDef as it doesn't contain a '${key}'`); return false; } return true; })) { this.customFilterOptions[filterOption.displayKey] = filterOption; } }); } private selectDefaultItem(params: ISimpleFilterParams): void { if (params.defaultOption) { this.defaultOption = params.defaultOption; } else if (this.filterOptions.length >= 1) { const firstFilterOption = this.filterOptions[0]; if (typeof firstFilterOption === 'string') { this.defaultOption = firstFilterOption; } else if (firstFilterOption.displayKey) { this.defaultOption = firstFilterOption.displayKey; } else { console.warn(`ag-Grid: invalid FilterOptionDef supplied as it doesn't contain a 'displayKey'`); } } else { console.warn('ag-Grid: no filter options for filter'); } } public getDefaultOption(): string { return this.defaultOption; } public getCustomOption(name: string): IFilterOptionDef { return this.customFilterOptions[name]; } }
ceolter/angular-grid
community-modules/core/src/ts/filter/provided/optionsFactory.ts
TypeScript
mit
2,502
<?php namespace MatchBundle\Controller; use Intervention\Image\Constraint; use Intervention\Image\ImageManager; use MatchBundle\Entity\Game; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * Class BoatController * @package MatchBundle\Controller */ class BoatController extends Controller { /** * Dynamique CSS * @param Request $request * @param Game $game * * @Route( * name="match.css", * path="/game/{slug}.css", * methods={"GET"}, * requirements={"slug": "([0-9A-Za-z\-]+)"}) * @return Response */ public function cssAction(Request $request, Game $game) { // Default value $isMobile = $this->isMobile($request); $boxSizeDefault = 20; $displayGridDefault = false; // Personal options if ($this->getUser()) { $boxSize = $this->getUser()->getOption('boxSize', $boxSizeDefault); $displayGrid = $this->getUser()->getOption('displayGrid', $displayGridDefault); } // Mobile if ($isMobile) { $boxSize = $boxSizeDefault; $displayGrid = true; } // View (CSS content) $boxSize = (isset($boxSize)) ? $boxSize : $boxSizeDefault; $response = $this->render('@Match/Match/game.css.twig', [ 'widthBox' => $boxSize, 'size' => $boxSize * $game->getSize(), 'borders' => range(0, $game->getSize(), 10), 'displayGrid' => (isset($displayGrid)) ? $displayGrid : $displayGridDefault, 'game' => $game, 'isMobile' => $isMobile, ]); $response->headers->set('Content-Type', 'text/css'); // Compress $content = $response->getContent(); $content = str_replace([" ", "\t", "\r", "\n"], '', $content); $response->setContent($content); return $response; } /** * Get the boat image * @param Request $request * @param string $color * @param integer $size * * @Route( * name="match.boat.img", * path="/img/boats/{color}-{size}.png", * methods={"GET"}, * requirements={"color": "([0-9A-F]{6})", "size": "([2-6]0)"}, * defaults={"size": "60"}) * @return Response */ public function boatImageAction(Request $request, $color, $size = 60) { // Path $rootDir = $this->get('kernel')->getRootDir(); $sourcePath = realpath($rootDir.'/../web/img/boat.png'); $destDir = realpath($rootDir.'/../var/boats'); $destPath = "$destDir/$color-$size.png"; // Create img if (!file_exists($destPath)) { $img = $this->changeColor($sourcePath, [255, 255, 255], $color); $this->resizeImg($img, $destPath, 8 * $size, 7 * $size, false); } // Response return $this->getResponse($request, $destPath); } /** * Get the rocket image * @param Request $request * @param string $color * @param integer $size * * @Route( * name="match.rocket.img", * path="/img/rocket/{color}-{size}.png", * methods={"GET"}, * requirements={"color": "([0-9A-F]{6})", "size": "([2-6]0)"}, * defaults={"size": "60"}) * @return Response */ public function rocketImageAction(Request $request, $color, $size = 60) { // Path $rootDir = $this->get('kernel')->getRootDir(); $sourcePath = realpath($rootDir.'/../web/img/rocket.png'); $destDir = realpath($rootDir.'/../var/boats'); $destPath = "$destDir/rocket-$color-$size.png"; // Create img if (!file_exists($destPath)) { $img = $this->changeColor($sourcePath, [255, 0, 0], $color); $this->resizeImg($img, $destPath, $size / 2); } // Response return $this->getResponse($request, $destPath); } /** * Get the explose image * @param Request $request * @param integer $size * * @Route( * name="match.explose.img", * path="/img/explose-{size}.png", * methods={"GET"}, * requirements={"size": "([2-6]0)"}, * defaults={"size": "60"}) * @return Response */ public function exploseImageAction(Request $request, $size = 60) { // Path $rootDir = $this->get('kernel')->getRootDir(); $sourcePath = realpath($rootDir.'/../web/img/explose.png'); $destDir = realpath($rootDir.'/../var/boats'); $destPath = "$destDir/explose-$size.png"; // Create img if (!file_exists($destPath)) { $this->resizeImg($sourcePath, $destPath, 12 * $size, 2 * $size, false); } // Response return $this->getResponse($request, $destPath); } /** * Change color and resize * @param string $sourcePath * @param array $colorInit RGB values * @param string $colorDest Hexa color * * @return resource */ private function changeColor($sourcePath, $colorInit, $colorDest) { // Dest color $red = hexdec(substr($colorDest, 0, 2)); $green = hexdec(substr($colorDest, 2, 2)); $blue = hexdec(substr($colorDest, 4, 2)); // Change color $img = imagecreatefrompng($sourcePath); $white = imagecolorclosest($img, $colorInit[0], $colorInit[1], $colorInit[2]); imagecolorset($img, $white, $red, $green, $blue); return $img; } /** * Get binary response * @param Request $request * @param string $destPath * * @return BinaryFileResponse */ private function getResponse(Request $request, $destPath) { // Response $response = new BinaryFileResponse($destPath); $response->headers->set('Content-Type', 'image/png'); return $response; } /** * Resize image * @param string|resource $source Source image * @param string $destPath Output file * @param integer $width Width (px) * @param integer|null $height Height (px) * @param boolean $keepRatio Keep the aspect ratio */ private function resizeImg($source, $destPath, $width, $height = null, $keepRatio = true) { // Ration if ($keepRatio) { $ratioClosure = function (Constraint $constraint) { $constraint->aspectRatio(); }; } else { $ratioClosure = null; } $manager = new ImageManager(['driver' => 'gd']); $image = $manager->make($source); $image ->resize($width, $height, $ratioClosure) ->save($destPath) ->destroy(); } /** * Check user-agent for mobile device * @param Request $request * * @return boolean */ private function isMobile(Request $request) { $userAgent = $request->headers->get('user-agent'); $regex = "/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i"; return (preg_match($regex, $userAgent) > 0); } }
matthieuy/battleship
src/MatchBundle/Controller/BoatController.php
PHP
mit
7,632
package com.creationgroundmedia.twitternator.activities; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.View; import com.codepath.oauth.OAuthLoginActionBarActivity; import com.creationgroundmedia.twitternator.R; import com.creationgroundmedia.twitternator.TwitterClient; public class LoginActivity extends OAuthLoginActionBarActivity<TwitterClient> { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); } // Inflate the menu; this adds items to the action bar if it is present. @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.login, menu); return true; } // OAuth authenticated successfully, launch primary authenticated activity // i.e Display application "homepage" @Override public void onLoginSuccess() { Intent i = new Intent(this, TimelineActivity.class); startActivity(i); finish(); } // OAuth authentication flow failed, handle the error // i.e Display an error dialog or toast @Override public void onLoginFailure(Exception e) { e.printStackTrace(); } // Click handler method for the button used to start OAuth flow // Uses the client to initiate OAuth authorization // This should be tied to a button used to login public void loginToRest(View view) { getClient().connect(); } }
geocohn/Twitternator
app/src/main/java/com/creationgroundmedia/twitternator/activities/LoginActivity.java
Java
mit
1,426
// // models.hpp // animeloop-cli // // Created by ShinCurry on 2017/4/3. // Copyright © 2017年 ShinCurry. All rights reserved. // #ifndef models_hpp #define models_hpp #include <iostream> #include <opencv2/opencv.hpp> namespace al { typedef std::tuple<long, long> LoopDuration; typedef std::vector<LoopDuration> LoopDurations; typedef std::vector<std::string> HashVector; typedef std::vector<cv::Mat> FrameVector; typedef std::vector<int> CutVector; struct VideoInfo { double fps; double fourcc; cv::Size size; int frame_count; }; } #endif /* models_hpp */
moeoverflow/animeloop-cli
animeloop-cli/models.hpp
C++
mit
638
<?php namespace RoyallTheFourth\HtmlDocument\Set; use RoyallTheFourth\HtmlDocument\RenderInterface; interface SetInterface extends RenderInterface { public function iterate(); public function add($item); public function merge($set); }
royallthefourth/html-document
src/Set/SetInterface.php
PHP
mit
250
#ifndef BIGUNSIGNEDINABASE_H #define BIGUNSIGNEDINABASE_H #include "NumberlikeArray.hh" #include "BigUnsigned.hh" #include <string> /* * A BigUnsignedInABase object represents a nonnegative integer of size limited * only by available memory, represented in a user-specified base that can fit * in an `unsigned short' (most can, and this saves memory). * * BigUnsignedInABase is intended as an intermediary class with little * functionality of its own. BigUnsignedInABase objects can be constructed * from, and converted to, BigUnsigneds (requiring multiplication, mods, etc.) * and `std::string's (by switching digit values for appropriate characters). * * BigUnsignedInABase is similar to BigUnsigned. Note the following: * * (1) They represent the number in exactly the same way, except that * BigUnsignedInABase uses ``digits'' (or Digit) where BigUnsigned uses * ``blocks'' (or Blk). * * (2) Both use the management features of NumberlikeArray. (In fact, my desire * to add a BigUnsignedInABase class without duplicating a lot of code led me to * introduce NumberlikeArray.) * * (3) The only arithmetic operation supported by BigUnsignedInABase is an * equality test. Use BigUnsigned for arithmetic. */ class BigUnsignedInABase : protected NumberlikeArray<unsigned short> { public: // The digits of a BigUnsignedInABase are unsigned shorts. typedef unsigned short Digit; // That's also the type of a base. typedef Digit Base; protected: // The base in which this BigUnsignedInABase is expressed Base base; // Creates a BigUnsignedInABase with a capacity; for internal use. BigUnsignedInABase(int, Index c) : NumberlikeArray<Digit>(0, c) {} // Decreases len to eliminate any leading zero digits. void zapLeadingZeros() { while (len > 0 && blk[len - 1] == 0) len--; } public: // Constructs zero in base 2. BigUnsignedInABase() : NumberlikeArray<Digit>(), base(2) {} // Copy constructor BigUnsignedInABase(const BigUnsignedInABase &x) : NumberlikeArray<Digit>(x), base(x.base) {} // Assignment operator void operator =(const BigUnsignedInABase &x) { NumberlikeArray<Digit>::operator =(x); base = x.base; } // Constructor that copies from a given array of digits. BigUnsignedInABase(const Digit *d, Index l, Base base); // Destructor. NumberlikeArray does the delete for us. ~BigUnsignedInABase() {} // LINKS TO BIGUNSIGNED BigUnsignedInABase(const BigUnsigned &x, Base base); operator BigUnsigned() const; /* LINKS TO STRINGS * * These use the symbols ``0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'' to * represent digits of 0 through 35. When parsing strings, lowercase is * also accepted. * * All string representations are big-endian (big-place-value digits * first). (Computer scientists have adopted zero-based counting; why * can't they tolerate little-endian numbers?) * * No string representation has a ``base indicator'' like ``0x''. * * An exception is made for zero: it is converted to ``0'' and not the * empty string. * * If you want different conventions, write your own routines to go * between BigUnsignedInABase and strings. It's not hard. */ operator std::string() const; BigUnsignedInABase(const std::string &s, Base base); public: // ACCESSORS Base getBase() const { return base; } // Expose these from NumberlikeArray directly. //NumberlikeArray<Digit>::getCapacity; //NumberlikeArray<Digit>::getLength; /* Returns the requested digit, or 0 if it is beyond the length (as if * the number had 0s infinitely to the left). */ Digit getDigit(Index i) const { return i >= len ? 0 : blk[i]; } // The number is zero if and only if the canonical length is zero. bool isZero() const { return NumberlikeArray<Digit>::isEmpty(); } /* Equality test. For the purposes of this test, two BigUnsignedInABase * values must have the same base to be equal. */ bool operator ==(const BigUnsignedInABase &x) const { return base == x.base && NumberlikeArray<Digit>::operator ==(x); } bool operator !=(const BigUnsignedInABase &x) const { return !operator ==(x); } }; #endif
marvins/ProjectEuler
cpp/common/BigUnsignedInABase.hh
C++
mit
4,112