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
# -*- coding: utf-8 -*- """ Sitemap builder """ import json, os from treelib import Tree from optimus.conf import settings class SitemapError(Exception): pass class PageSitemap(object): """ Construct ressource page to build and published sitemap """ def __init__(self, tree, view, with_root=False): self.tree = json.loads(tree.to_json(with_data=True)) self.view = view self.with_root = with_root # For public sitemap # Public sitemap self.sitemap = self.get_public_sitemap(self.tree) # Store a flat list of every ressources to build as pages self.ressources = self.recursive_ressources([self.tree]) def get_public_sitemap(self, tree): """ Return a list of sitemap nodes If 'PageSitemap.with_root' is False, return only root children nodes, else return the full dict containing root node. """ if not self.with_root: return tree['root']['children'] return [tree] def recursive_ressources(self, children, pages=[]): """ Return a flat ressources list from given children """ for branch in children: for leaf_name, leaf_content in branch.items(): datas = leaf_content['data'] pages.append(self.view( title=leaf_name, template_name=datas['link'], destination=datas['link'], sitemap=self.sitemap, )) if datas['is_dir']: pages = self.recursive_ressources(leaf_content['children']) return pages def tree_from_directory_structure(scanned_path, base_path=None): """ Scan given "scanned_path" path to find every HTML page file to build sitemap. Assume you want to use templates file names as ressource filename url. * Filenames and directory starting with "_" are ignored; * Expect an "index.html" file in each directory (except ignored ones) which will take the directory name; Return a treelib.Tree of finded pages """ tree = Tree() tree.create_node("root", "root", data={ 'id': "root", 'link': 'index.html', 'is_dir': True, }) if base_path is None: base_path = scanned_path for root, dirs, files in os.walk(scanned_path): # Current relative dir from demos dir relative_dir = os.path.relpath(root, base_path) if not relative_dir.startswith('_'): if relative_dir == '.': parent = None current_dir = "root" dir_name = "Root" else: dir_name = os.path.basename(relative_dir) current_dir = relative_dir # Resolve parent tag parent = "/".join(os.path.split(relative_dir)[:-1]) if not parent: parent = "root" # Add directory node tree.create_node(dir_name.replace('_', ' '), current_dir, parent=parent, data={ 'id': current_dir, 'link': os.path.join(relative_dir, 'index.html'), 'is_dir': True, }) #print "dir_name:{dir_name} | current_dir:{current_dir} | relative_dir:{relative_dir} | parent:{parent}".format( #dir_name=dir_name, current_dir=current_dir, relative_dir=relative_dir, parent=parent) # Recursive find templates in dirs for item in files: if not item.startswith('_') and item != 'index.html': # Get filepath relative to root, remove leading './' filepath = os.path.join(relative_dir, item) if filepath.startswith('./'): filepath = filepath[2:] # Build unique tag identifier tag = filepath #print " * file:{filename} | tag:{tag} | parent:{parent}".format(filename=item, tag=tag, parent=current_dir) # Make title head, tail = os.path.splitext(item) title = head.replace('_', ' ') # Add file node to current directory node tree.create_node(title, tag, parent=current_dir, data={ 'id': tag, 'link': filepath, 'is_dir': False, }) #print return tree
sveetch/Sveetoy
project/sitemap.py
Python
mit
4,546
<?php class MageFM_Cielo_Block_Form extends Mage_Payment_Block_Form_Cc { protected function _construct() { $this->setTemplate('magefm/cielo/form.phtml'); } public function getCcAvailableTypes() { $types = Mage::getModel('magefm_cielo/source_cctype')->toKeyValueArray(); if ($method = $this->getMethod()) { $availableTypes = $method->getConfigData('cctypes'); if ($availableTypes) { $availableTypes = explode(',', $availableTypes); foreach ($types as $code => $name) { if (!in_array($code, $availableTypes)) { unset($types[$code]); } } } } return $types; } }
magefm/cielo
app/code/community/MageFM/Cielo/Block/Form.php
PHP
mit
776
#include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR NOTHINGCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Nothingcoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your nothingcoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); }
barcoin-project/nothingcoin
src/qt/askpassphrasedialog.cpp
C++
mit
9,729
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zm5 16H7v-2h10v2zm-6.7-4L7 10.7l1.4-1.4 1.9 1.9 5.3-5.3L17 7.3 10.3 14z" }), 'OfflinePinSharp');
AlloyTeam/Nuclear
components/icon/esm/offline-pin-sharp.js
JavaScript
mit
279
package it.uniba.di.itps.asd.exams.Lab20101117.pila; /** * Created by acidghost on 27/08/14. */ public class PilaDoubling<T> implements Pila<T> { private T[] pila = (T[]) new Object[1]; private int n = 0; @Override public boolean isEmpty() { return n == 0; } @Override public void push(T e) { if(n == pila.length) { T[] tmp = (T[]) new Object[n * 2]; System.arraycopy(pila, 0, tmp, 0, n); pila = tmp; } pila[n] = e; n++; } @Override public T top() { if(isEmpty()) { throw new EccezioneStrutturaVuota("Pila vuota"); } else { return pila[n-1]; } } @Override public void pop() { if(n <= pila.length/4) { T[] tmp = (T[]) new Object[n / 2]; System.arraycopy(pila, 0, tmp, 0, n); pila = tmp; } n--; } }
acidghost/algorithms-data-structures-java
src/it/uniba/di/itps/asd/exams/Lab20101117/pila/PilaDoubling.java
Java
mit
944
using UnityEngine; using System.Collections; using UnityEngine.Networking; public class PickupSpawner : NetworkBehaviour { public GameObject pistol; public GameObject shotgun; public GameObject cannon; private GameObject pickup; private bool[] canSpawn; private float[] spawnTimes; public float waitBetweenSpawns = 20; // Use this for initialization void Start () { spawnTimes = new float[this.transform.childCount]; canSpawn = new bool[this.transform.childCount]; for (int i = 0; i < this.transform.childCount; i++) { spawnTimes[i] = Time.time - waitBetweenSpawns; canSpawn[i] = true; } } // Update is called once per frame void Update () { for (int i = 0; i < this.transform.childCount; i++) { if (canSpawn[i] == false && this.transform.GetChild(i).transform.childCount == 0) { canSpawn[i] = true; spawnTimes[i] = Time.time + waitBetweenSpawns; } if (spawnTimes[i] < Time.time && canSpawn[i]) { CmdSpawnPickup(i); canSpawn[i] = false; } } } [Command] void CmdSpawnPickup(int i) { int rand = Random.Range(1, 100); //if (rand < 35) //{ // pickup = (GameObject)Instantiate(pistol, this.transform.GetChild(i).transform.position, Quaternion.identity); //} if (rand < 70) { pickup = (GameObject)Instantiate(shotgun, this.transform.GetChild(i).transform.position, Quaternion.identity); } else if (rand <= 100) { pickup = (GameObject)Instantiate(cannon, this.transform.GetChild(i).transform.position, Quaternion.identity); } pickup.transform.parent = this.transform.GetChild(i).transform; pickup.transform.position = pickup.transform.parent.position; NetworkServer.Spawn(pickup); } }
szucs2020/SpaceGame
Assets/Scripts/Pickups/PickupSpawner.cs
C#
mit
1,993
// Copyright (c) 2016, Ben Morgan. All rights reserved. // Use of this source code is governed by an MIT license // that can be found in the LICENSE file. package lackey import ( "os" "os/exec" "strconv" "strings" "github.com/cassava/lackey/audio/mp3" "github.com/goulash/audio" "github.com/goulash/color" "github.com/goulash/osutil" ) type ExecError struct { Err error Output string } func (err *ExecError) Error() string { return err.Err.Error() } type Encoder interface { Ext() string CanCopy(src, dst Audio) bool Encode(src, dst string, md Audio) error } type Runner struct { Color *color.Colorizer Encoder Encoder ForceTranscode bool CopyExtensions []string DryRun bool Verbose bool Strip bool SrcPrefix string DstPrefix string } func (o *Runner) WhichExt(src Audio) string { // At the moment, we always have the same kind of output name := src.FileInfo().Name() for _, ext := range o.CopyExtensions { if strings.HasSuffix(name, ext) { return ext } } return o.Encoder.Ext() } // canEncode returns true if this runner can encode the codec. func (o *Runner) canEncode(c audio.Codec) bool { return c == audio.FLAC || c == audio.MP3 || c == audio.M4A || c == audio.OGG } func (o *Runner) transcodeOrCopy(src, dst Audio) AudioOperation { if o.Encoder.CanCopy(src, dst) { return CopyAudio } return TranscodeAudio } func (o *Runner) Which(src, dst Audio) AudioOperation { // Files we should copy directly, we do so here name := src.FileInfo().Name() for _, ext := range o.CopyExtensions { if strings.HasSuffix(name, ext) { if dst.IsExists() { sfi, dfi := src.FileInfo(), dst.FileInfo() if dfi.Size() == 0 { return CopyAudio } if sfi.ModTime().After(dfi.ModTime()) { return CopyAudio } return SkipAudio } return CopyAudio } } if !o.canEncode(src.Encoding()) { return IgnoreAudio } if o.ForceTranscode { return TranscodeAudio } if !dst.IsExists() { return o.transcodeOrCopy(src, dst) } sfi, dfi := src.FileInfo(), dst.FileInfo() if dfi.Size() == 0 { return o.transcodeOrCopy(src, dst) } if sfi.ModTime().After(dfi.ModTime()) { return UpdateAudio } return SkipAudio } func (o *Runner) Ok(dst string) error { if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } if o.Verbose { o.Color.Printf("@{g.}ok:@|@. %s\n", dst) } return nil } func (o *Runner) Ignore(dst string) error { if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } o.Color.Printf("@{.y}ignoring:@|@. %s\n", dst) return nil } func (o *Runner) Error(err error) error { o.Color.Fprintf(os.Stderr, "@rerror:@| %s\n", err) if e, ok := err.(*ExecError); ok { o.Color.Fprintf(os.Stderr, "@routput:@|\n%s\n", e.Output) } return err } func (o *Runner) Warn(err error) error { o.Color.Fprintf(os.Stderr, "@rwarning:@| %s\n", err) if e, ok := err.(*ExecError); ok { o.Color.Fprintf(os.Stderr, "@routput:@|\n%s\n", e.Output) } return nil } func (o *Runner) RemoveDir(dst string) error { path := dst if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } o.Color.Printf("@grm -r:@| %s\n", dst) if o.DryRun { return nil } return os.RemoveAll(path) } func (o *Runner) CreateDir(dst string) error { path := dst if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } o.Color.Printf("@gmkdir:@| %s\n", dst) if o.DryRun { return nil } return os.MkdirAll(path, 0777) } func (o *Runner) RemoveFile(dst string) error { path := dst if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } o.Color.Printf("@grm:@| %s\n", dst) if o.DryRun { return nil } return os.Remove(path) } func (o *Runner) CopyFile(src, dst string) error { path := dst if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } o.Color.Printf("@gcp:@| %s\n", dst) if o.DryRun { return nil } return osutil.CopyFile(src, path) } func (o *Runner) Transcode(src string, dst string, md Audio) error { path := dst if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } o.Color.Printf("@gencode:@| %s\n", dst) if o.DryRun { return nil } if ex, _ := osutil.FileExists(path); ex { err := os.Remove(path) if err != nil { return err } } return o.Encoder.Encode(src, path, md) } func (o *Runner) Update(src string, dst string, md Audio) error { path := dst if o.Strip { dst = strings.TrimPrefix(dst, o.DstPrefix) } o.Color.Printf("@gupdate:@| %s\n", dst) if o.DryRun { return nil } err := os.Remove(path) if err != nil { return err } o.Color.Printf(" -> ") return o.Transcode(src, path, md) } type MP3Encoder struct { TargetQuality int BitrateThreshold int } func (e *MP3Encoder) Ext() string { return ".mp3" } func (e *MP3Encoder) CanCopy(src, dst Audio) bool { if src.Encoding() != audio.MP3 { return false } sm := src.Metadata() if sm.EncodingBitrate() > e.BitrateThreshold { return false } return true } func (e *MP3Encoder) Encode(src, dst string, md Audio) error { q := strconv.FormatInt(int64(e.TargetQuality), 10) var bs []byte var err error if md.Encoding() == audio.MP3 { // We are much more reliable using lame directly than over ffmpeg when downsampling // MP3 files directly. bs, err = exec.Command("lame", "--mp3input", "-h", "-V"+q, src, dst).CombinedOutput() } else if md.Encoding() == audio.FLAC { // Because ffmpeg is having some bugs, we avoid using it when possible. enc := mp3.NewEncoder() enc.Quality = e.TargetQuality dec := exec.Command("flac", "-c", "-d", src) bs, err = enc.EncodeFromStdin(dec, dst, md.Metadata()) } else { bs, err = exec.Command("ffmpeg", "-i", src, "-vn", "-qscale:a", q, dst).CombinedOutput() } if err != nil { return &ExecError{ Err: err, Output: string(bs), } } return nil } type OPUSEncoder struct { Extension string TargetBitrate string } func (e *OPUSEncoder) Ext() string { if e.Extension == "" { return ".opus" } return e.Extension } func (e *OPUSEncoder) CanCopy(src, dst Audio) bool { return false } func (e *OPUSEncoder) Encode(src, dst string, md Audio) error { bs, err := exec.Command("ffmpeg", "-i", src, "-vn", "-acodec", "libopus", "-vbr", "on", "-compression_level", "10", "-b:a", e.TargetBitrate, dst).CombinedOutput() if err != nil { return &ExecError{ Err: err, Output: string(bs), } } return nil }
cassava/lackey
active.go
GO
mit
6,380
require './ruby_2048' describe R2048 do before(:each) do @r2048 = R2048.new end it "should jump to [2, 0, 0, 0] when input [0, 0, 0, 2]" do @r2048.set_jump_step([0, 0, 0, 2]).should == [2, 0, 0, 0] end it "should jump to [2, 4, 0, 0] when input [2, 0, 4, 0]" do @r2048.set_jump_step([2, 0, 4, 0]).should == [2, 4, 0, 0] end it "should jump to [4, 0, 0, 0] when input [2, 0, 2, 0]" do @r2048.set_jump_step([2, 0, 2, 0]).should == [4, 0, 0, 0] end it "should jump to [2, 4, 4, 0] when input [2, 4, 2, 2]" do @r2048.set_jump_step([2, 4, 2, 2]).should == [2, 4, 4, 0] end it "should jump to [4, 4, 0, 0] when input [2, 2, 2, 2]" do @r2048.set_jump_step([2, 2, 2, 2]).should == [4, 4, 0, 0] end it "should + 1 chess if generate_init_num" do expect { @r2048.generate_init_num }.to change{@r2048.chessboard.flatten.count{|chess| chess!= 0} }.by(1) end it "should have already have two chess when inited" do expect{@r2048.count} == 2 end end
xumc/ruby_2048
ruby_2048_spec.rb
Ruby
mit
1,012
require_relative 'pieces' require_relative '../chess_utils/chess_utils' class Board include ChessUtils include ChessUtils::Renderable def initialize @rows = Array.new(SIZE) { Array.new(SIZE) } end def [](pos) row, col = pos rows[row][col] end def []=(pos, piece) row, col = pos rows[row][col] = piece end def move_piece(piece, pos) self[pos] = piece self[piece.pos] = nil piece.pos = pos end def in_range?(pos) pos.all? { |coord| coord.between?(0, SIZE - 1) } end def in_check?(color) king = pieces.find do |piece| piece.is_a?(King) && piece.color == color end opposing_pieces = pieces.reject { |piece| piece.color == color } opposing_pieces.any? do |piece| piece.moves.any? { |move| move == king.pos } end end def pieces rows.flatten.compact end def dup duped_board = self.class.new pieces.each do |piece| piece.class.new(duped_board, piece.color, piece.pos) end duped_board end def empty?(pos) self[pos].nil? end def piece?(pos) self[pos].is_a?(Piece) end def checkmate?(color) pieces = self.pieces.select { |piece| piece.color == color } in_check?(color) && pieces.all? { |piece| piece.valid_moves.empty? } end def fill_rows positions.map do |coord, piece| piece.new(self, :black, [0, coord]) piece.new(self, :white, [(SIZE - 1), coord]) end (0...SIZE).each do |coord| Pawn.new(self, :black, [1, coord]) Pawn.new(self, :white, [(SIZE - 2), coord]) end end def add_piece(piece, pos) raise 'space not empty' unless empty?(pos) self[pos] = piece end protected attr_reader :rows private def positions STARTING_POSITIONS.inject({}) do |positions, (coord, piece)| positions.merge(coord => constantize(piece)) end end def constantize(piece) Object.const_get(piece.to_s.capitalize) end end
cribbles/chess
lib/chess/board.rb
Ruby
mit
1,956
<?php get_header(); ?> <div class=""> <?php get_template_part(contact); ?> <div class="page" id="<?php the_title(); ?>"> <header class="bp-header cf about animate row" data-emergence="hidden" > <h1 class="bp-header__title animate col-lg-12 col-md-12 col-sm-12 col-xs-12" data-emergence="hidden">It is just that page which shows you something bad is happened (404)</h1> <div class="info col-lg-6 col-md-8 col-sm-12 col-xs-12"> </div> </header> </div> </div> <?php get_footer(); ?>
reskir/spintus
404.php
PHP
mit
537
import rcblog if __name__ == '__main__': rcblog.main()
sanchopanca/rcblog
run.py
Python
mit
60
package com.github.itimur.downloader; import com.github.itimur.callbacks.FutureDownloadCallback; import com.google.common.collect.ImmutableList; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; /** * @author Timur */ public class AsyncDownloader implements Downloader { @Override public void startAllAsync(ImmutableList<DownloadTask> tasks, ListeningExecutorService executor, EventBus evenBus) { FutureDownloadCallback downloadCallback = new FutureDownloadCallback(evenBus); for (ListenableFuture<Download> future : submitTasks(tasks, executor)) { Futures.addCallback(future, downloadCallback, executor); } } private ImmutableList<ListenableFuture<Download>> submitTasks(ImmutableList<DownloadTask> tasks, ListeningExecutorService executor) { ImmutableList.Builder<ListenableFuture<Download>> futures = ImmutableList.builder(); for (DownloadTask task : tasks) { futures.add(executor.submit(task)); } return futures.build(); } }
timur86/console-downloader
src/main/java/com/github/itimur/downloader/AsyncDownloader.java
Java
mit
1,331
#include "stage.h" #include <assert.h> #include <map> #include <string> #include <vector> #include "util.h" static std::vector<std::string> stageStrings = {"planning", "alpha", "beta", "release", "mature", "inactive", "abandoned", "deleted", "unknown"}; static std::map<std::string, Stage> stageMap = std::map<std::string, Stage>(); static std::map<Stage, std::string> stageMap2 = std::map<Stage, std::string>(); // idgaf anymore static void initMaps() { if (stageMap.empty()) { for (int i = Stage::kAlpha; i != Stage::kUnknown; i++) { stageMap[stageStrings[i - Stage::kAlpha]] = (Stage) i; stageMap2[(Stage) i] = stageStrings[i - Stage::kAlpha]; } } } Stage stageFromString(std::string str) { initMaps(); if (stageMap.count(str) > 0) { return stageMap[str]; } else { return Stage::kUnknown; } } std::string stringFromStage(Stage stage) { initMaps(); return stageMap2[stage]; }
caseif/dbo-get
stage.cpp
C++
mit
981
import * as actions from './actions' describe('App actions', () => { it('selectTerm should create SELECT_TERM action', () => { expect(actions.selectTerm('term')).toEqual({ type: 'SELECT_TERM', term: 'term' }) }) it('startFetch should create START_FETCH action', () => { expect(actions.startFetch()).toEqual({ type: 'START_FETCH', isBusy: true }) }) it('fetchTerm calls RECEIVE_ERROR on complete lookup failure', () => { let failingLookup = (url, settings, onDone ) => { throw "Error" }; let conceptNet = { lookup: failingLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") }; actions.getIsA(dispatch, conceptNet, "next term"); }) it('fetchTerm calls RECEIVE_ERROR on lookup returning error to onDone', () => { let errorLookup = (url, settings, onDone ) => { onDone("Error", null) }; let conceptNet = { lookup: errorLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_ERROR") }; actions.getIsA(dispatch, conceptNet, "next term"); }) it('fetchTerm calls RECEIVE_RESPONSE on lookup returning results to onDone', () => { let successLookup = (url, settings, onDone ) => { onDone(null, {'edges': []}) }; let conceptNet = { lookup: successLookup }; let dispatch = (arg) => { expect(arg['type']).toEqual("RECEIVE_RESPONSE") }; actions.getIsA(dispatch, conceptNet, "next term"); }) })
AlexanderAA/conceptnet
src/actions/actions.spec.js
JavaScript
mit
1,444
/* *************************************************************************** * Mica - the Java(tm) Graphics Framework * *************************************************************************** * NOTICE: Permission to use, copy, and modify this software and its * * documentation is hereby granted provided that this notice appears in * * all copies. * * * * Permission to distribute un-modified copies of this software and its * * documentation is hereby granted provided that no fee is charged and * * that this notice appears in all copies. * * * * SOFTWARE FARM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE * * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT * * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR * * A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOFTWARE FARM SHALL NOT BE * * LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR * * CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, MODIFICATION OR * * DISTRIBUTION OF THIS SOFTWARE OR ITS DERIVATIVES. * * * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND * * DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * * *************************************************************************** * Copyright (c) 1997-2004 Software Farm, Inc. All Rights Reserved. * *************************************************************************** */ package com.swfm.mica; import com.swfm.mica.util.Strings; /** * @version %I% %G% * @author Michael L. Davis * @release 1.4.1 * @module %M% * @language Java (JDK 1.4) */ public class MiBasicPropertyPanel extends MiPropertyPanel { private MiTable table; private MiScrolledBox scrolledBox; public MiBasicPropertyPanel(boolean scrollable) { this(scrollable, 1); } public MiBasicPropertyPanel(boolean scrollable, int numberOfColumns) { MiColumnLayout layout = new MiColumnLayout(); layout.setElementHSizing(Mi_EXPAND_TO_FILL); layout.setUniqueElementIndex(0); layout.setUniqueElementSizing(Mi_EXPAND_TO_FILL); setLayout(layout); MiParts scrolledBoxReturn = new MiParts(); table = makePropertyPanelTable(this, scrollable, numberOfColumns, scrolledBoxReturn); scrolledBox = scrolledBoxReturn.size() > 0 ? (MiScrolledBox )scrolledBoxReturn.get(0) : null; } public int getInspectedObjectIndex() { return(-1); } public MiTable getTable() { return(table); } public MiScrolledBox getScrolledBox() { return(scrolledBox); } protected void generatePanel() { makePropertyPanelWidgets(this, table); } public static MiTable makePropertyPanelTable(MiPart container, boolean scrollable) { return(makePropertyPanelTable(container, scrollable, 1)); } public static MiTable makePropertyPanelTable( MiPart container, boolean scrollable, int numberOfColumns) { return(makePropertyPanelTable(container, scrollable, numberOfColumns)); } public static MiTable makePropertyPanelTable( MiPart container, boolean scrollable, int numberOfColumns, MiParts scrolledBoxReturn) { MiTable table = new MiTable(); table.getTableWideDefaults().setHorizontalJustification(Mi_LEFT_JUSTIFIED); table.getTableWideDefaults().setHorizontalSizing(Mi_SAME_SIZE); table.setTotalNumberOfColumns(numberOfColumns * 2); table.setHasFixedTotalNumberOfColumns(true); table.setMinimumNumberOfVisibleColumns(numberOfColumns * 2); table.setMaximumNumberOfVisibleColumns(numberOfColumns * 2); table.getSectionMargins().setMargins(0); table.getTableWideDefaults().insetMargins.setMargins(4, 2, 4, 2); table.getMadeColumnDefaults(1).setColumnHorizontalSizing(Mi_EXPAND_TO_FILL); MiRectangle cellBackgroundRect = new MiRectangle(); cellBackgroundRect.setBorderLook(Mi_RAISED_BORDER_LOOK); table.getBackgroundManager().appendCellBackgrounds(cellBackgroundRect); table.setPropertyValue(MiTable.Mi_CELL_BG_PROPERTY_NAME + ".backgroundColor", MiColorManager.getColorName(table.getBackgroundColor())); table.getSelectionManager().setMaximumNumberSelected(0); table.getSelectionManager().setBrowsable(false); if (scrollable) { MiScrolledBox scrolledBox = new MiScrolledBox(table); container.appendPart(scrolledBox); scrolledBoxReturn.add(scrolledBox); } else { table.setPreferredNumberOfVisibleRows(-1); container.appendPart(table); } return(table); } public static void makePropertyPanelWidgets(MiPropertyPanel panel, MiTable table) { table.removeAllCells(); MiPropertyWidgets properties = panel.getPropertyWidgets(); if (properties.size() < table.getPreferredNumberOfVisibleRows()) { table.setPreferredNumberOfVisibleRows(properties.size()); } MiParts parts = new MiParts(); for (int i = 0; i < properties.size(); ++i) { MiText label = new MiText(properties.elementAt(i).getDisplayName()); MiWidget widget = properties.elementAt(i).getWidget(); label.setStatusHelp(widget.getStatusHelp(widget.getCenter())); label.setDialogHelp(widget.getDialogHelp(null)); parts.addElement(label); parts.addElement(widget); } table.appendItems(parts); } }
justacoder/mica
src/parts/MiBasicPropertyPanel.java
Java
mit
5,741
#include "StdAfx.h" #include "Tetris.h" #include "TetrisDlg.h" /* case dir when 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * x * . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . when 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . . . x . . . . . . . . . . . * * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . when 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * . . . . . . . . . * x * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . when 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . * * . . . . . . . . . . . x . . . . . . . . . . . * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . */ BlockL::BlockL(unsigned char clr, unsigned char **board) : Block(clr, board) { board[0][3] = clr; board[0][4] = clr; board[0][5] = clr; board[1][3] = clr; } bool BlockL::canMoveDown() { unsigned char *nextRow = board[row + 1]; unsigned char *secondNextRow = board[row + 2]; switch(dir) { case 0: return row < CTetrisDlg::ROW - 2 && !nextRow[col] && !nextRow[col + 1] && !secondNextRow[col - 1]; case 1: return row < CTetrisDlg::ROW - 2 && !secondNextRow[col] && !secondNextRow[col + 1]; case 2: return row < CTetrisDlg::ROW - 1 && !nextRow[col - 1] && !nextRow[col] && !nextRow[col + 1]; default: return row < CTetrisDlg::ROW - 2 && !secondNextRow[col] && !board[row][col - 1]; } } bool BlockL::canMoveLeft() { switch(dir) { case 0: return col > 1 && !board[row][col - 2] && !board[row + 1][col - 2]; case 1: return col > 0 && !board[row - 1][col - 1] && !board[row][col - 1] && !board[row + 1][col - 1]; case 2: return col > 1 && !board[row - 1][col] && !board[row][col - 2]; default: return col > 1 && !board[row - 1][col - 2] && !board[row][col - 1] && !board[row + 1][col - 1]; } } bool BlockL::canMoveRight() { switch(dir) { case 0: return col < CTetrisDlg::COL - 2 && !board[row][col + 2] && !board[row + 1][col]; case 1: return col < CTetrisDlg::COL - 2 && !board[row - 1][col + 1] && !board[row][col + 1] && !board[row + 1][col + 2]; case 2: return col < CTetrisDlg::COL - 2 && !board[row - 1][col + 2] && !board[row][col + 2]; default: return col < CTetrisDlg::COL - 1 && !board[row - 1][col + 1] && !board[row][col + 1] && !board[row + 1][col + 1]; } } bool BlockL::canTurn() { unsigned char *prevRow = board[row - 1]; unsigned char *thisRow = board[row]; unsigned char *nextRow = board[row + 1]; switch(dir) { case 0: return row > 0 && !prevRow[col] && !nextRow[col] && !nextRow[col + 1]; case 1: return col > 0 && !prevRow[col + 1] && !thisRow[col - 1] && !thisRow[col + 1]; case 2: return row < CTetrisDlg::ROW - 1 && !prevRow[col - 1] && !prevRow[col] && !nextRow[col]; default: return col < CTetrisDlg::COL - 1 && !thisRow[col - 1] && !thisRow[col + 1] && !nextRow[col - 1]; } } void BlockL::moveDown() { unsigned char *prevRow = board[row - 1]; unsigned char *thisRow = board[row]; unsigned char *nextRow = board[row + 1]; switch(dir) { case 0: thisRow[col - 1] = 0; thisRow[col] = 0; thisRow[col + 1] = 0; nextRow[col] = clr; nextRow[col + 1] = clr; ++row; board[row + 1][col - 1] = clr; return; case 1: prevRow[col] = 0; nextRow[col + 1] = 0; ++row; board[row + 1][col] = clr; board[row + 1][col + 1] = clr; return; case 2: prevRow[col + 1] = 0; thisRow[col - 1] = 0; thisRow[col] = 0; nextRow[col - 1] = clr; nextRow[col] = clr; nextRow[col + 1] = clr; ++row; return; default: prevRow[col - 1] = 0; prevRow[col] = 0; thisRow[col - 1] = clr; ++row; board[row + 1][col] = clr; } } void BlockL::moveLeft() { unsigned char *prevRow = board[row - 1]; unsigned char *thisRow = board[row]; unsigned char *nextRow = board[row + 1]; switch(dir) { case 0: thisRow[col + 1] = 0; nextRow[col - 1] = 0; --col; thisRow[col - 1] = clr; nextRow[col - 1] = clr; return; case 1: prevRow[col] = 0; thisRow[col] = 0; nextRow[col + 1] = 0; prevRow[col - 1] = clr; thisRow[col - 1] = clr; nextRow[col - 1] = clr; --col; return; case 2: prevRow[col + 1] = 0; thisRow[col + 1] = 0; prevRow[col] = clr; --col; thisRow[col - 1] = clr; return; default: prevRow[col] = 0; thisRow[col] = 0; nextRow[col] = 0; thisRow[col - 1] = clr; nextRow[col - 1] = clr; --col; prevRow[col - 1] = clr; } } void BlockL::moveRight() { unsigned char *prevRow = board[row - 1]; unsigned char *thisRow = board[row]; unsigned char *nextRow = board[row + 1]; switch(dir) { case 0: thisRow[col - 1] = 0; nextRow[col - 1] = 0; nextRow[col] = clr; ++col; thisRow[col + 1] = clr; return; case 1: prevRow[col] = 0; thisRow[col] = 0; nextRow[col] = 0; prevRow[col + 1] = clr; thisRow[col + 1] = clr; ++col; nextRow[col + 1] = clr; return; case 2: prevRow[col + 1] = 0; thisRow[col - 1] = 0; ++col; prevRow[col + 1] = clr; thisRow[col + 1] = clr; return; default: prevRow[col - 1] = 0; thisRow[col] = 0; nextRow[col] = 0; prevRow[col + 1] = clr; thisRow[col + 1] = clr; nextRow[col + 1] = clr; ++col; } } void BlockL::turn() { unsigned char *prevRow = board[row - 1]; unsigned char *thisRow = board[row]; unsigned char *nextRow = board[row + 1]; switch(dir) { case 0: thisRow[col - 1] = 0; thisRow[col + 1] = 0; nextRow[col - 1] = 0; prevRow[col] = clr; nextRow[col] = clr; nextRow[col + 1] = clr; break; case 1: prevRow[col] = 0; nextRow[col] = 0; nextRow[col + 1] = 0; prevRow[col + 1] = clr; thisRow[col - 1] = clr; thisRow[col + 1] = clr; break; case 2: prevRow[col + 1] = 0; thisRow[col - 1] = 0; thisRow[col + 1] = 0; prevRow[col - 1] = clr; prevRow[col] = clr; nextRow[col] = clr; break; default: prevRow[col - 1] = 0; prevRow[col] = 0; nextRow[col] = 0; thisRow[col - 1] = clr; thisRow[col + 1] = clr; nextRow[col - 1] = clr; } ++dir %= 4; }
zhangsu/tetris
BlockL.cpp
C++
mit
7,341
package com.fcduarte.todoapp.activity; import android.app.Activity; import android.app.Fragment; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.widget.CursorAdapter; import android.support.v4.widget.SimpleCursorAdapter; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.fcduarte.todoapp.R; import com.fcduarte.todoapp.database.TodoContract.TodoItem; import com.fcduarte.todoapp.database.TodoItemDataSource; import com.fcduarte.todoapp.util.SwipeDismissListViewTouchListener; public class TodoActivity extends Activity { public static int RESULT_OK = 200; public static int RESULT_NOT_MODIFIED = 304; private static int REQUEST_EDIT_ITEM = 0; private static TodoItemDataSource datasource; private static SimpleCursorAdapter itemsAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_todo); if (savedInstanceState == null) { getFragmentManager().beginTransaction().add(R.id.container, new MainFragment()).commit(); } datasource = new TodoItemDataSource(this); datasource.open(); itemsAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, datasource.getAll(), new String[] { TodoItem.COLUMN_NAME_ITEM_DESCRIPTION }, new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.todo, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK && requestCode == REQUEST_EDIT_ITEM) { Long itemId = data.getLongExtra(EditItemActivity.ITEM_ID, -1); String newItemDescription = data.getStringExtra(EditItemActivity.ITEM_DESCRIPTION); updateItem(itemId, newItemDescription); } } public static class MainFragment extends Fragment { private ListView lvItems; private View rootView; private Button btnAddItem; private EditText etNewItem; public MainFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_todo, container, false); etNewItem = (EditText) rootView.findViewById(R.id.etNewItem); lvItems = (ListView) rootView.findViewById(R.id.lvItems); lvItems.setAdapter(itemsAdapter); SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener( lvItems, new SwipeDismissListViewTouchListener.DismissCallbacks() { @Override public boolean canDismiss(int position) { return true; } @Override public void onDismiss(ListView listView, int[] reverseSortedPositions) { for (int position : reverseSortedPositions) { removeTodoItem(position); } } }); lvItems.setOnTouchListener(touchListener); lvItems.setOnScrollListener(touchListener.makeScrollListener()); lvItems.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor cursor = itemsAdapter.getCursor(); Intent intent = new Intent(getActivity(), EditItemActivity.class); intent.putExtra(EditItemActivity.ITEM_ID, cursor.getLong(TodoItem.COLUMN_NAME_ID_POSITION)); intent.putExtra(EditItemActivity.ITEM_DESCRIPTION, cursor.getString(TodoItem.COLUMN_NAME_ITEM_DESCRIPTION_POSITION)); getActivity().startActivityForResult(intent, TodoActivity.REQUEST_EDIT_ITEM); } }); btnAddItem = (Button) rootView.findViewById(R.id.btnAddItem); btnAddItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { addTodoItem(); etNewItem.setText(""); lvItems.smoothScrollToPosition(itemsAdapter.getCount()); } }); return rootView; } private void addTodoItem() { datasource.create(etNewItem.getText().toString()); itemsAdapter.changeCursor(datasource.getAll()); } private void removeTodoItem(int position) { Cursor cursor = itemsAdapter.getCursor(); cursor.moveToPosition(position); datasource.delete(cursor.getLong(TodoItem.COLUMN_NAME_ID_POSITION)); itemsAdapter.changeCursor(datasource.getAll()); } } private void updateItem(Long itemId, String newItemDescription) { datasource.update(itemId, newItemDescription); itemsAdapter.changeCursor(datasource.getAll()); } }
fcduarte/simple-todo
src/com/fcduarte/todoapp/activity/TodoActivity.java
Java
mit
5,147
/* Nihonium Engine This file is licensed under the terms of the MIT License. See LICENCE.txt for the full licence. */ #include "../common/object.h" #include "../common/screen.h" #include "../windows/windows_filesystem.h" #include "../windows/windows_input.h" #include "../windows/windows_audio.h" int main(int argc, char** argv) { filesystem::instance = new filesystem::WindowsFilesystem(); input::instance = new input::WindowsInput(); audio::instance = new audio::WindowsAudio(); audio::instance->init(nullptr); audio::BaseMusic* music = audio::instance->new_music("resources/music/music.ogg"); // TODO: This is a temporary testing feature. audio::instance->play_music(music); screen::init(); object::load_scene("resources/scenes/main.lua"); while (!screen::should_close) { double frame_time = screen::get_frame_time(); object::update(frame_time, object::root); screen::end_frame(); } screen::uninit(); return 0; }
IDidMakeThat/gameengine-temp
source/windows/main.cpp
C++
mit
960
/** * @version: 1.0.1 * @author: Dan Grossman http://www.dangrossman.info/ * @date: 2012-08-20 * @copyright: Copyright (c) 2012 Dan Grossman. All rights reserved. * @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0 * @website: http://www.improvely.com/ */ !function ($) { var DateRangePicker = function (element, options, cb) { var hasOptions = typeof options == 'object' var localeObject; //state this.startDate = Date.today(); this.endDate = Date.today(); this.minDate = false; this.maxDate = false; this.changed = false; this.ranges = {}; this.opens = 'right'; this.cb = function () { }; this.format = 'MM/dd/yyyy'; this.separator = ' - '; this.showWeekNumbers = false; this.buttonClasses = ['btn-primary']; this.locale = { applyLabel: 'Apply', fromLabel: 'From', toLabel: 'To', weekLabel: 'W', customRangeLabel: 'Custom Range', daysOfWeek: Date.CultureInfo.shortestDayNames, monthNames: Date.CultureInfo.monthNames, firstDay: 0 }; localeObject = this.locale; this.leftCalendar = { month: Date.today().set({ day: 1, month: this.startDate.getMonth(), year: this.startDate.getFullYear() }), calendar: Array() }; this.rightCalendar = { month: Date.today().set({ day: 1, month: this.endDate.getMonth(), year: this.endDate.getFullYear() }), calendar: Array() }; // by default, the daterangepicker element is placed at the bottom of HTML body this.parentEl = 'body'; //element that triggered the date range picker this.element = $(element); if (this.element.hasClass('pull-right')) this.opens = 'left'; if (this.element.is('input')) { this.element.on({ click: $.proxy(this.show, this), focus: $.proxy(this.show, this) }); } else { this.element.on('click', $.proxy(this.show, this)); } if (hasOptions) { if(typeof options.locale == 'object') { $.each(localeObject, function (property, value) { localeObject[property] = options.locale[property] || value; }); } } var DRPTemplate = '<div class="daterangepicker dropdown-menu">' + '<div class="calendar left"></div>' + '<div class="calendar right"></div>' + '<div class="ranges">' + '<div class="range_inputs">' + '<div>' + '<label for="daterangepicker_start">' + this.locale.fromLabel + '</label>' + '<input class="input-mini form-control" type="text" name="daterangepicker_start" value="" disabled="disabled" />' + '</div>' + '<div>' + '<label for="daterangepicker_end">' + this.locale.toLabel + '</label>' + '<input class="input-mini form-control" type="text" name="daterangepicker_end" value="" disabled="disabled" />' + '</div>' + '<button class="btn btn-small" disabled="disabled">' + this.locale.applyLabel + '</button>' + '</div>' + '</div>' + '</div>'; this.parentEl = (hasOptions && options.parentEl && $(options.parentEl)) || $(this.parentEl); //the date range picker this.container = $(DRPTemplate).appendTo(this.parentEl); if (hasOptions) { if (typeof options.format == 'string') this.format = options.format; if (typeof options.separator == 'string') this.separator = options.separator; if (typeof options.startDate == 'string') this.startDate = Date.parse(options.startDate, this.format); if (typeof options.endDate == 'string') this.endDate = Date.parse(options.endDate, this.format); if (typeof options.minDate == 'string') this.minDate = Date.parse(options.minDate, this.format); if (typeof options.maxDate == 'string') this.maxDate = Date.parse(options.maxDate, this.format); if (typeof options.startDate == 'object') this.startDate = options.startDate; if (typeof options.endDate == 'object') this.endDate = options.endDate; if (typeof options.minDate == 'object') this.minDate = options.minDate; if (typeof options.maxDate == 'object') this.maxDate = options.maxDate; if (typeof options.ranges == 'object') { for (var range in options.ranges) { var start = options.ranges[range][0]; var end = options.ranges[range][1]; if (typeof start == 'string') start = Date.parse(start); if (typeof end == 'string') end = Date.parse(end); // If we have a min/max date set, bound this range // to it, but only if it would otherwise fall // outside of the min/max. if (this.minDate && start < this.minDate) start = this.minDate; if (this.maxDate && end > this.maxDate) end = this.maxDate; // If the end of the range is before the minimum (if min is set) OR // the start of the range is after the max (also if set) don't display this // range option. if ((this.minDate && end < this.minDate) || (this.maxDate && start > this.maxDate)) { continue; } this.ranges[range] = [start, end]; } var list = '<ul>'; for (var range in this.ranges) { list += '<li>' + range + '</li>'; } list += '<li>' + this.locale.customRangeLabel + '</li>'; list += '</ul>'; this.container.find('.ranges').prepend(list); } // update day names order to firstDay if (typeof options.locale == 'object') { if (typeof options.locale.firstDay == 'number') { this.locale.firstDay = options.locale.firstDay; var iterator = options.locale.firstDay; while (iterator > 0) { this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()); iterator--; } } } if (typeof options.opens == 'string') this.opens = options.opens; if (typeof options.showWeekNumbers == 'boolean') { this.showWeekNumbers = options.showWeekNumbers; } if (typeof options.buttonClasses == 'string') { this.buttonClasses = [options.buttonClasses]; } if (typeof options.buttonClasses == 'object') { this.buttonClasses = options.buttonClasses; } } //apply CSS classes to buttons var c = this.container; $.each(this.buttonClasses, function (idx, val) { c.find('button').addClass(val); }); if (this.opens == 'right') { //swap calendar positions var left = this.container.find('.calendar.left'); var right = this.container.find('.calendar.right'); left.removeClass('left').addClass('right'); right.removeClass('right').addClass('left'); } if (typeof options == 'undefined' || typeof options.ranges == 'undefined') this.container.find('.calendar').show(); if (typeof cb == 'function') this.cb = cb; this.container.addClass('opens' + this.opens); //event listeners this.container.on('mousedown', $.proxy(this.mousedown, this)); this.container.find('.calendar').on('click', '.prev', $.proxy(this.clickPrev, this)); this.container.find('.calendar').on('click', '.next', $.proxy(this.clickNext, this)); this.container.find('.ranges').on('click', 'button', $.proxy(this.clickApply, this)); this.container.find('.calendar').on('click', 'td.available', $.proxy(this.clickDate, this)); this.container.find('.calendar').on('mouseenter', 'td.available', $.proxy(this.enterDate, this)); this.container.find('.calendar').on('mouseleave', 'td.available', $.proxy(this.updateView, this)); this.container.find('.ranges').on('click', 'li', $.proxy(this.clickRange, this)); this.container.find('.ranges').on('mouseenter', 'li', $.proxy(this.enterRange, this)); this.container.find('.ranges').on('mouseleave', 'li', $.proxy(this.updateView, this)); this.element.on('keyup', $.proxy(this.updateFromControl, this)); this.updateView(); this.updateCalendars(); }; DateRangePicker.prototype = { constructor: DateRangePicker, mousedown: function (e) { e.stopPropagation(); e.preventDefault(); }, updateView: function () { this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.container.find('input[name=daterangepicker_start]').val(this.startDate.toString(this.format)); this.container.find('input[name=daterangepicker_end]').val(this.endDate.toString(this.format)); if (this.startDate.equals(this.endDate) || this.startDate.isBefore(this.endDate)) { this.container.find('button').removeAttr('disabled'); } else { this.container.find('button').attr('disabled', 'disabled'); } }, updateFromControl: function () { if (!this.element.is('input')) return; var dateString = this.element.val().split(this.separator); var start = Date.parseExact(dateString[0], this.format); var end = Date.parseExact(dateString[1], this.format); if (start == null || end == null) return; if (end.isBefore(start)) return; this.startDate = start; this.endDate = end; this.updateView(); this.cb(this.startDate, this.endDate); this.updateCalendars(); }, notify: function () { this.updateView(); if (this.element.is('input')) { this.element.val(this.startDate.toString(this.format) + this.separator + this.endDate.toString(this.format)); } this.cb(this.startDate, this.endDate); }, move: function () { var parentOffset = { top: this.parentEl.offset().top - this.parentEl.scrollTop(), left: this.parentEl.offset().left - this.parentEl.scrollLeft() }; if (this.opens == 'left') { this.container.css({ top: this.element.offset().top + this.element.outerHeight(), right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left, left: 'auto' }); } else { this.container.css({ top: this.element.offset().top + this.element.outerHeight(), left: this.element.offset().left - parentOffset.left, right: 'auto' }); } }, show: function (e) { this.container.show(); this.move(); if (e) { e.stopPropagation(); e.preventDefault(); } this.changed = false; $(document).on('mousedown', $.proxy(this.hide, this)); }, hide: function (e) { this.container.hide(); $(document).off('mousedown', this.hide); if (this.changed) { this.changed = false; this.notify(); } }, enterRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.updateView(); } else { var dates = this.ranges[label]; this.container.find('input[name=daterangepicker_start]').val(dates[0].toString(this.format)); this.container.find('input[name=daterangepicker_end]').val(dates[1].toString(this.format)); } }, clickRange: function (e) { var label = e.target.innerHTML; if (label == this.locale.customRangeLabel) { this.container.find('.calendar').show(); } else { var dates = this.ranges[label]; this.startDate = dates[0]; this.endDate = dates[1]; this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.updateCalendars(); this.changed = true; this.container.find('.calendar').hide(); this.hide(); } }, clickPrev: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add({ months: -1 }); } else { this.rightCalendar.month.add({ months: -1 }); } this.updateCalendars(); }, clickNext: function (e) { var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.leftCalendar.month.add({ months: 1 }); } else { this.rightCalendar.month.add({ months: 1 }); } this.updateCalendars(); }, enterDate: function (e) { var title = $(e.target).attr('title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].toString(this.format)); } else { this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].toString(this.format)); } }, clickDate: function (e) { var title = $(e.target).attr('title'); var row = title.substr(1, 1); var col = title.substr(3, 1); var cal = $(e.target).parents('.calendar'); if (cal.hasClass('left')) { startDate = this.leftCalendar.calendar[row][col]; endDate = this.endDate; } else { startDate = this.startDate; endDate = this.rightCalendar.calendar[row][col]; } cal.find('td').removeClass('active'); if (startDate.equals(endDate) || startDate.isBefore(endDate)) { $(e.target).addClass('active'); if (!startDate.equals(this.startDate) || !endDate.equals(this.endDate)) this.changed = true; this.startDate = startDate; this.endDate = endDate; } this.leftCalendar.month.set({ month: this.startDate.getMonth(), year: this.startDate.getFullYear() }); this.rightCalendar.month.set({ month: this.endDate.getMonth(), year: this.endDate.getFullYear() }); this.updateCalendars(); }, clickApply: function (e) { this.hide(); }, updateCalendars: function () { this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.getMonth(), this.leftCalendar.month.getFullYear()); this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.getMonth(), this.rightCalendar.month.getFullYear()); this.container.find('.calendar.left').html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.endDate)); this.container.find('.calendar.right').html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate)); }, buildCalendar: function (month, year) { var firstDay = Date.today().set({ day: 1, month: month, year: year }); var lastMonth = firstDay.clone().add(-1).day().getMonth(); var lastYear = firstDay.clone().add(-1).day().getFullYear(); var daysInMonth = Date.getDaysInMonth(year, month); var daysInLastMonth = Date.getDaysInMonth(lastYear, lastMonth); var dayOfWeek = firstDay.getDay(); //initialize a 6 rows x 7 columns array for the calendar var calendar = Array(); for (var i = 0; i < 6; i++) { calendar[i] = Array(); } //populate the calendar with date objects var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1; if (startDay > daysInLastMonth) startDay -= 7; if (dayOfWeek == this.locale.firstDay) startDay = daysInLastMonth - 6; var curDate = Date.today().set({ day: startDay, month: lastMonth, year: lastYear }); for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = curDate.clone().add(1).day()) { if (i > 0 && col % 7 == 0) { col = 0; row++; } calendar[row][col] = curDate; } return calendar; }, renderCalendar: function (calendar, selected, minDate, maxDate) { var html = '<table class="table-condensed">'; html += '<thead>'; html += '<tr>'; // add empty cell for week number if (this.showWeekNumbers) html += '<th></th>'; if (!minDate || minDate < calendar[1][1]) { html += '<th class="prev available"><i class="icon-arrow-left"></i></th>'; } else { html += '<th></th>'; } html += '<th colspan="5" style="width: auto">' + this.locale.monthNames[calendar[1][1].getMonth()] + calendar[1][1].toString(" yyyy") + '</th>'; if (!maxDate || maxDate > calendar[1][1]) { html += '<th class="next available"><i class="icon-arrow-right"></i></th>'; } else { html += '<th></th>'; } html += '</tr>'; html += '<tr>'; // add week number label if (this.showWeekNumbers) html += '<th class="week">' + this.locale.weekLabel + '</th>'; $.each(this.locale.daysOfWeek, function (index, dayOfWeek) { html += '<th>' + dayOfWeek + '</th>'; }); html += '</tr>'; html += '</thead>'; html += '<tbody>'; for (var row = 0; row < 6; row++) { html += '<tr>'; // add week number if (this.showWeekNumbers) html += '<td class="week">' + calendar[row][0].getWeek() + '</td>'; for (var col = 0; col < 7; col++) { var cname = 'available '; cname += (calendar[row][col].getMonth() == calendar[1][1].getMonth()) ? '' : 'off'; // Normalise the time so the comparison won't fail selected.setHours(0,0,0,0); if ( (minDate && calendar[row][col] < minDate) || (maxDate && calendar[row][col] > maxDate)) { cname = 'off disabled'; } else if (calendar[row][col].equals(selected)) { cname += 'active'; } var title = 'r' + row + 'c' + col; html += '<td class="' + cname + '" title="' + title + '">' + calendar[row][col].getDate() + '</td>'; } html += '</tr>'; } html += '</tbody>'; html += '</table>'; return html; } }; $.fn.daterangepicker = function (options, cb) { this.each(function() { var el = $(this); if (!el.data('daterangepicker')) el.data('daterangepicker', new DateRangePicker(el, options, cb)); }); return this; }; } (window.jQuery);
bernatixer/QUEDEM.CAT
assets/bootstrap-daterangepicker/daterangepicker.js
JavaScript
mit
22,195
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ import React from 'react'; import {NoDevices} from '../NoDevices'; export function TroubleshootingGuide(_props: { showGuide: boolean; devicesDetected: number; }) { if (_props.devicesDetected == 0) return <NoDevices />; else { return <></>; } }
facebook/flipper
desktop/flipper-ui-core/src/sandy-chrome/appinspect/fb-stubs/TroubleshootingGuide.tsx
TypeScript
mit
465
<?php declare(strict_types = 1); namespace LidskaSila\Prooph\Tests\ServiceBus\Configurators\ServiceBusConfigurators; use LidskaSila\Prooph\Tests\Configurators\ProophExtensionTestCase; use Prooph\ServiceBus\QueryBus; class QueryBusConfiguratorTest extends ProophExtensionTestCase { private const TEST_CONFIG_PATH = 'ServiceBusConfiguratorTests/CommandBusConfiguratorTest.neon'; public function testGetServiceBusByType_FromTestContainer_ShouldReturnExpectedInstance() { $this->givenTestContainer(self::TEST_CONFIG_PATH); $repository = $this->whenGetServiceByTypeFromContainer(QueryBus::class); $this->thenIsInstanceOfExpectedClass(QueryBus::class, $repository); } }
LidskaSila/Prooph
tests/Prooph/ServiceBus/ServiceBusConfigurators/QueryBusConfiguratorTest.php
PHP
mit
681
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.AutoCAD.Colors; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; namespace Linq2Acad { public partial class SampleCode { /// <summary> /// This sample removes all entities from the model space /// </summary> [CommandMethod("Linq2AcadExample1")] public void RemovingAllEntitiesFromTheModelSpace() { WriteMessage("This sample removes all entities from the model space"); using (var db = AcadDatabase.Active()) { db.ModelSpace .Clear(); } WriteMessage("Model space cleared"); } /// <summary> /// This sample removes all BlockReferences from the model space /// </summary> [CommandMethod("Linq2AcadExample2")] public void ErasingAllBlockReferencesFromTheModelSpace() { WriteMessage("This sample removes all BlockReferences from the model space"); using (var db = AcadDatabase.Active()) { foreach (var br in db.ModelSpace .OfType<BlockReference>() .UpgradeOpen()) { br.Erase(); } } WriteMessage("All block references removed from model space"); } /// <summary> /// This sample adds a line to the model space /// </summary> [CommandMethod("Linq2AcadExample3")] public void AddingALineToTheModelSpace() { WriteMessage("This sample adds a line to the model space"); using (var db = AcadDatabase.Active()) { db.ModelSpace .Add(new Line(Point3d.Origin, new Point3d(100, 100, 0))); } WriteMessage("Line added to model space"); } /// <summary> /// This sample creates a new layer /// </summary> [CommandMethod("Linq2AcadExample4")] public void CreatingANewLayer() { WriteMessage("This sample creates a new layer"); var layerName = GetString("Enter layer name"); var colorName = GetString("Enter color name"); if (layerName != null && colorName != null) { using (var db = AcadDatabase.Active()) { var layer = db.Layers.Create(layerName); layer.Color = Color.FromColor(System.Drawing.Color.FromName(colorName)); } WriteMessage($"Layer {layerName} created"); } } /// <summary> /// This sample prints all layer names /// </summary> [CommandMethod("Linq2AcadExample5")] public void PrintingAllLayerNames() { WriteMessage("This sample prints all layer names"); using (var db = AcadDatabase.Active()) { foreach (var layer in db.Layers) { WriteMessage(layer.Name); } } } /// <summary> /// This sample turns off all layers, except the one the user enters /// </summary> [CommandMethod("Linq2AcadExample6")] public void TurningOffAllLayersExceptTheOneTheUserEnters() { WriteMessage("This sample turns off all layers, except the one the user enters"); var layerName = GetString("Enter layer name"); if (layerName != null) { using (var db = AcadDatabase.Active()) { var layerToIgnore = db.Layers .Element(layerName); foreach (var layer in db.Layers .Except(layerToIgnore) .UpgradeOpen()) { layer.IsOff = true; } } WriteMessage($"All layers turned off, except {layerName}"); } } /// <summary> /// This sample creates a layer and adds all red lines in the model space to it /// </summary> [CommandMethod("Linq2AcadExample7")] public void CreatingALayerAndAddingAllRedLinesInTheModelSpaceToIt() { WriteMessage("This sample creates a layer and This sample adds all red lines in the model space to it"); var layerName = GetString("Enter layer name"); if (layerName != null) { using (var db = AcadDatabase.Active()) { var lines = db.ModelSpace .OfType<Line>() .Where(l => l.Color.ColorValue.Name == "ffff0000"); db.Layers .Create(layerName, lines); } WriteMessage($"All red lines moved to new layer {layerName}"); } } /// <summary> /// This sample moves entities from one layer to another /// </summary> [CommandMethod("Linq2AcadExample8")] public void MovingEntitiesFromOneLayerToAnother() { WriteMessage("This sample moves entities from one layer to another"); var sourceLayerName = GetString("Enter source layer name"); var targetLayerName = GetString("Enter target layer name"); if (sourceLayerName != null && targetLayerName != null) { using (var db = AcadDatabase.Active()) { var entities = db.CurrentSpace .Where(e => e.Layer == sourceLayerName); db.Layers .Element(targetLayerName) .AddRange(entities); } WriteMessage($"All entities on layer {sourceLayerName} moved to layer {targetLayerName}"); } } /// <summary> /// This sample imports a block from a drawing file /// </summary> [CommandMethod("Linq2AcadExample9")] public void ImportingABlockFromADrawingFile() { WriteMessage("This sample imports a block from a drawing file"); var filePath = GetString("Enter file path"); var blockName = GetString("Enter block name"); if (filePath != null && blockName != null) { using (var sourceDb = AcadDatabase.OpenReadOnly(filePath)) { var block = sourceDb.Blocks .Element(blockName); using (var activeDb = AcadDatabase.Active()) { activeDb.Blocks .Import(block); } } WriteMessage($"Block {blockName} imported"); } } /// <summary> /// This sample opens a drawing from file and counts the BlockReferences in the model space /// </summary> [CommandMethod("Linq2AcadExample10")] public void OpeningADrawingFromFileAndCountingTheBlockReferencesInTheModelSpace() { WriteMessage("This sample opens a drawing from file and counting the BlockReferences in the model space"); var filePath = GetString("Enter file path"); if (filePath != null) { using (var db = AcadDatabase.OpenReadOnly(filePath)) { var count = db.ModelSpace .OfType<BlockReference>() .Count(); WriteMessage($"Model space block references in file {filePath}: {count}"); } } } /// <summary> /// This sample picks an entity and saves a string on it /// </summary> [CommandMethod("Linq2AcadExample11")] public void PickingAnEntityAndSavingAStringOnIt() { WriteMessage("This sample picks an entity and saves a string on it"); var entityId = GetEntity("Pick an entity"); var key = GetString("Enter key"); var str = GetString("Enter string to save"); if (entityId.IsValid && key != null && str != null) { using (var db = AcadDatabase.Active()) { db.CurrentSpace .Element(entityId) .SaveData(key, str); } WriteMessage($"Key-value-pair {key}:{str} saved on entity"); } } /// <summary> /// This sample picks an entity and reads a string from it /// </summary> [CommandMethod("Linq2AcadExample12")] public void PickingAnEntityAndReadingAStringFromIt() { WriteMessage("This sample picks an entity and reads a string from it"); var entityId = GetEntity("Pick an entity"); var key = GetString("Enter key"); if (entityId.IsValid && key != null) { using (var db = AcadDatabase.Active()) { var str = db.CurrentSpace .Element(entityId) .GetData<string>(key); WriteMessage($"String {str} read from entity"); } } } /// <summary> /// This sample picks an entity and reads a string from it (with XData as the data source) /// </summary> [CommandMethod("Linq2AcadExample13")] public void PickingAnEntityAndReadingAStringFromItWithXDataAsTheDataSource() { WriteMessage("This sample picks an entity and reads a string from it (with XData as the data source)"); var entityId = GetEntity("Pick an entity"); var key = GetString("Enter RegApp name"); if (entityId.IsValid && key != null) { using (var db = AcadDatabase.Active()) { var str = db.CurrentSpace .Element(entityId) .GetData<string>(key, true); WriteMessage($"String {str} read from entity's XData"); } } } /// <summary> /// This sample counts the number of entities in all paper space layouts /// </summary> [CommandMethod("Linq2AcadExample14")] public void CountingTheNumberOfEntitiesInAllPaperSpaceLayouts() { WriteMessage("This sample counts the number of entities in all paper space layouts"); using (var db = AcadDatabase.Active()) { var count = db.PaperSpace .SelectMany(ps => ps) .Count(); WriteMessage($"{count} entities in all paper space layouts"); } } /// <summary> /// This sample changes the summary info /// </summary> [CommandMethod("Linq2AcadExample15")] public void ChangingTheSummaryInfo() { WriteMessage("This sample changes the summary info"); using (var db = AcadDatabase.Active()) { db.SummaryInfo.Author = "John Doe"; db.SummaryInfo.CustomProperties["CustomData1"] = "42"; } WriteMessage("Summary info updated"); } /// <summary> /// This sample reloads all loaded XRefs /// </summary> [CommandMethod("Linq2AcadExample16")] public void ReloadingAllLoadedXRefs() { WriteMessage("This sample reloads all loaded XRefs"); using (var db = AcadDatabase.Active()) { foreach (var xRef in db.XRefs .Where(xr => xr.IsLoaded)) { xRef.Reload(); } } WriteMessage("XRefs reloaded"); } } }
wtertinek/Linq2Acad
src/Sources/Linq2Acad.SampleCode.CS/SampleCode.cs
C#
mit
10,745
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <HTML> <head> <title>Welcome to CodeIgniter 3.X | Multiple Upload File</title> </head> <body> <?php echo form_open_multipart('upload/do_upload_multi');?> <h2>For Multiple Upload Codeigniter 3.X</h2> <div style="border: 1px dotted #000;margin:10px 0;padding:10px;"> <input type="file" name="images[]" /> <input type="file" name="images[]"/> <input type="file" name="images[]"/> </div> <br /><br /> <input type="submit" value="upload" name="upload" /> </form> </body> </HTML>
iwane021/codeigniter-multi-upload
application/views/upload_form_multi_2.php
PHP
mit
569
using ArtportalenApp.DependencyInjection; using ArtportalenApp.Interfaces; using ArtportalenApp.ViewModels; using Autofac; using Xamarin.Forms; namespace ArtportalenApp.Views { public class SiteDetailPage : TabbedPage, IPage<SiteDetailViewModel> { private SiteDetailViewModel _viewModel; private SiteDetailInfoPage infoPage; public SiteDetailPage() { var pageFactory = AutofacContainer.Container.Resolve<IPageFactory>(); infoPage = pageFactory.CreatePage<SiteDetailInfoPage, SiteDetailInfoViewModel>(); Children.Add(infoPage); /* Children.Add(pageFactory.CreatePage<ChooseSiteNearbyPage, ChooseSiteNearbyViewModel>( done: async vm => { ViewModel.SelectedSite = vm.SelectedSite; await ViewModel.DoneAction(); }, cancel: async vm => { await ViewModel.CancelAction(); })); Children.Add(pageFactory.CreatePage<ChooseSiteSearchPage, ChooseSiteSearchViewModel>( done: async vm => { ViewModel.SelectedSite = vm.SelectedSite; await ViewModel.DoneAction(); }, cancel: async vm => { await ViewModel.CancelAction(); })); Children.Add(pageFactory.CreatePage<ChooseSiteMapPage, ChooseSiteMapViewModel>( done: async vm => { ViewModel.SelectedSite = vm.SelectedSite; await ViewModel.DoneAction(); }, cancel: async vm => { await ViewModel.CancelAction(); }));*/ } public SiteDetailViewModel ViewModel { get { return _viewModel; } set { _viewModel = value; if (value != null) { if (value.SelectedSite != null) { infoPage.ViewModel.SelectedSite = value.SelectedSite; } } } } } }
unger/ArtportalenApp
ArtportalenApp/Views/SiteDetailPage.cs
C#
mit
2,293
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * ------------------------------- * XYIntervalSeriesCollection.java * ------------------------------- * (C) Copyright 2006-2013, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 20-Oct-2006 : Version 1 (DG); * 13-Feb-2007 : Provided a number of method overrides that enhance * performance, and added a proper clone() * implementation (DG); * 18-Jan-2008 : Added removeSeries() and removeAllSeries() methods (DG); * 22-Apr-2008 : Implemented PublicCloneable (DG); * 02-Jul-2013 : Use ParamChecks (DG); * */ package org.jfree.data.xy; import java.io.Serializable; import java.util.List; import org.jfree.chart.util.ParamChecks; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.util.ObjectUtilities; import org.jfree.util.PublicCloneable; /** * A collection of {@link XYIntervalSeries} objects. * * @since 1.0.3 * * @see XYIntervalSeries */ public class XYIntervalSeriesCollection extends AbstractIntervalXYDataset implements IntervalXYDataset, PublicCloneable, Serializable { /** Storage for the data series. */ private List data; /** * Creates a new instance of <code>XIntervalSeriesCollection</code>. */ public XYIntervalSeriesCollection() { this.data = new java.util.ArrayList(); } /** * Adds a series to the collection and sends a {@link DatasetChangeEvent} * to all registered listeners. * * @param series the series (<code>null</code> not permitted). */ public void addSeries(XYIntervalSeries series) { ParamChecks.nullNotPermitted(series, "series"); this.data.add(series); series.addChangeListener(this); fireDatasetChanged(); } /** * Returns the number of series in the collection. * * @return The series count. */ public int getSeriesCount() { return this.data.size(); } /** * Returns a series from the collection. * * @param series the series index (zero-based). * * @return The series. * * @throws IllegalArgumentException if <code>series</code> is not in the * range <code>0</code> to <code>getSeriesCount() - 1</code>. */ public XYIntervalSeries getSeries(int series) { if ((series < 0) || (series >= getSeriesCount())) { throw new IllegalArgumentException("Series index out of bounds"); } return (XYIntervalSeries) this.data.get(series); } /** * Returns the key for a series. * * @param series the series index (in the range <code>0</code> to * <code>getSeriesCount() - 1</code>). * * @return The key for a series. * * @throws IllegalArgumentException if <code>series</code> is not in the * specified range. */ public Comparable getSeriesKey(int series) { // defer argument checking return getSeries(series).getKey(); } /** * Returns the number of items in the specified series. * * @param series the series (zero-based index). * * @return The item count. * * @throws IllegalArgumentException if <code>series</code> is not in the * range <code>0</code> to <code>getSeriesCount() - 1</code>. */ public int getItemCount(int series) { // defer argument checking return getSeries(series).getItemCount(); } /** * Returns the x-value for an item within a series. * * @param series the series index. * @param item the item index. * * @return The x-value. */ public Number getX(int series, int item) { XYIntervalSeries s = (XYIntervalSeries) this.data.get(series); return s.getX(item); } /** * Returns the start x-value (as a double primitive) for an item within a * series. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The value. */ public double getStartXValue(int series, int item) { XYIntervalSeries s = (XYIntervalSeries) this.data.get(series); return s.getXLowValue(item); } /** * Returns the end x-value (as a double primitive) for an item within a * series. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The value. */ public double getEndXValue(int series, int item) { XYIntervalSeries s = (XYIntervalSeries) this.data.get(series); return s.getXHighValue(item); } /** * Returns the y-value (as a double primitive) for an item within a * series. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The value. */ public double getYValue(int series, int item) { XYIntervalSeries s = (XYIntervalSeries) this.data.get(series); return s.getYValue(item); } /** * Returns the start y-value (as a double primitive) for an item within a * series. * * @param series the series index (zero-based). * @param item the item index (zero-based). * * @return The value. */ public double getStartYValue(int series, int item) { XYIntervalSeries s = (XYIntervalSeries) this.data.get(series); return s.getYLowValue(item); } /** * Returns the end y-value (as a double primitive) for an item within a * series. * * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The value. */ public double getEndYValue(int series, int item) { XYIntervalSeries s = (XYIntervalSeries) this.data.get(series); return s.getYHighValue(item); } /** * Returns the y-value for an item within a series. * * @param series the series index. * @param item the item index. * * @return The y-value. */ public Number getY(int series, int item) { return new Double(getYValue(series, item)); } /** * Returns the start x-value for an item within a series. * * @param series the series index. * @param item the item index. * * @return The x-value. */ public Number getStartX(int series, int item) { return new Double(getStartXValue(series, item)); } /** * Returns the end x-value for an item within a series. * * @param series the series index. * @param item the item index. * * @return The x-value. */ public Number getEndX(int series, int item) { return new Double(getEndXValue(series, item)); } /** * Returns the start y-value for an item within a series. This method * maps directly to {@link #getY(int, int)}. * * @param series the series index. * @param item the item index. * * @return The start y-value. */ public Number getStartY(int series, int item) { return new Double(getStartYValue(series, item)); } /** * Returns the end y-value for an item within a series. This method * maps directly to {@link #getY(int, int)}. * * @param series the series index. * @param item the item index. * * @return The end y-value. */ public Number getEndY(int series, int item) { return new Double(getEndYValue(series, item)); } /** * Removes a series from the collection and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param series the series index (zero-based). * * @since 1.0.10 */ public void removeSeries(int series) { if ((series < 0) || (series >= getSeriesCount())) { throw new IllegalArgumentException("Series index out of bounds."); } XYIntervalSeries ts = (XYIntervalSeries) this.data.get(series); ts.removeChangeListener(this); this.data.remove(series); fireDatasetChanged(); } /** * Removes a series from the collection and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @param series the series (<code>null</code> not permitted). * * @since 1.0.10 */ public void removeSeries(XYIntervalSeries series) { ParamChecks.nullNotPermitted(series, "series"); if (this.data.contains(series)) { series.removeChangeListener(this); this.data.remove(series); fireDatasetChanged(); } } /** * Removes all the series from the collection and sends a * {@link DatasetChangeEvent} to all registered listeners. * * @since 1.0.10 */ public void removeAllSeries() { // Unregister the collection as a change listener to each series in // the collection. for (int i = 0; i < this.data.size(); i++) { XYIntervalSeries series = (XYIntervalSeries) this.data.get(i); series.removeChangeListener(this); } this.data.clear(); fireDatasetChanged(); } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof XYIntervalSeriesCollection)) { return false; } XYIntervalSeriesCollection that = (XYIntervalSeriesCollection) obj; return ObjectUtilities.equal(this.data, that.data); } /** * Returns a clone of this dataset. * * @return A clone of this dataset. * * @throws CloneNotSupportedException if there is a problem cloning. */ public Object clone() throws CloneNotSupportedException { XYIntervalSeriesCollection clone = (XYIntervalSeriesCollection) super.clone(); int seriesCount = getSeriesCount(); clone.data = new java.util.ArrayList(seriesCount); for (int i = 0; i < this.data.size(); i++) { clone.data.set(i, getSeries(i).clone()); } return clone; } }
Epsilon2/Memetic-Algorithm-for-TSP
jfreechart-1.0.16/source/org/jfree/data/xy/XYIntervalSeriesCollection.java
Java
mit
11,638
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.08.07 at 06:17:52 PM CEST // package org.w3._1998.math.mathml; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for named-space. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="named-space"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="veryverythinmathspace"/&gt; * &lt;enumeration value="verythinmathspace"/&gt; * &lt;enumeration value="thinmathspace"/&gt; * &lt;enumeration value="mediummathspace"/&gt; * &lt;enumeration value="thickmathspace"/&gt; * &lt;enumeration value="verythickmathspace"/&gt; * &lt;enumeration value="veryverythickmathspace"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "named-space") @XmlEnum public enum NamedSpace { @XmlEnumValue("veryverythinmathspace") VERYVERYTHINMATHSPACE("veryverythinmathspace"), @XmlEnumValue("verythinmathspace") VERYTHINMATHSPACE("verythinmathspace"), @XmlEnumValue("thinmathspace") THINMATHSPACE("thinmathspace"), @XmlEnumValue("mediummathspace") MEDIUMMATHSPACE("mediummathspace"), @XmlEnumValue("thickmathspace") THICKMATHSPACE("thickmathspace"), @XmlEnumValue("verythickmathspace") VERYTHICKMATHSPACE("verythickmathspace"), @XmlEnumValue("veryverythickmathspace") VERYVERYTHICKMATHSPACE("veryverythickmathspace"); private final String value; NamedSpace(String v) { value = v; } public static NamedSpace fromValue(String v) { for (NamedSpace c: NamedSpace.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } public String value() { return value; } }
digitalheir/java-legislation-gov-uk-library
src/main/java/org/w3/_1998/math/mathml/NamedSpace.java
Java
mit
2,257
/** * This module is used to create different point distributions that can be * turned into different tile sets when made into a graph format. There are * various different distributions that can be used to create interesting * tile patterns when turned into a voronoi diagram. * * @class PointDistribution */ "use strict"; import Poisson from "poisson-disk-sample"; import Vector from "../geometry/Vector"; import Rectangle from "../geometry/Rectangle"; import Rand from "./Rand"; /** * Creates a random distribution of points in a particular bounding box * with a particular average distance between points. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {number} [seed=null] If specified use a local seed for creating the point * distribution. Otherwise, use the current global seed for generation * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function random(bbox, d, seed = null) { const rng = seed ? new Rand(seed) : Rand; const nPoints = bbox.area / (d * d); let points = []; for (let i = 0; i < nPoints; i++) { points.push(rng.vector(bbox)); } return points; } /** * Creates a square grid like distribution of points in a particular bounding * box with a particular distance between points. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function square(bbox, d) { const dx = d / 2; const dy = dx; let points = []; for (let y = 0; y < bbox.height; y += d) { for (let x = 0; x < bbox.width; x += d) { points.push(new Vector(dx + x, dy + y)); } } return points; } /** * Creates a square grid like distribution of points in a particular bounding * box with a particular distance between points. The grid has also been * slightly purturbed or jittered so that the distribution is not completely * even. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {number} amm The ammount of jitter that has been applied to the grid * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function squareJitter(bbox, d, amm) { return square(bbox, d).map(v => Rand.jitter(v, amm)); } /** * Creates a uniform hexagonal distribution of points in a particular bounding * box with a particular distance between points. The hexagons can also be * specified to have a particular width or height as well as creating hexagons * that have "pointy" tops or "flat" tops. By default it makes flat tops. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {boolean} [flatTop=true] Create hecagons with flat tops by default. * Otherwise go with the pointy top hexagons. * @param {number} w The width of the hexagon tiles * @param {number} h The height of the hexagon tiles * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function hexagon(bbox, d, flatTop = true, w, h) { // Need to allow for the change of height and width // Running into "Uncaught Voronoi.closeCells() > this makes no sense!" const dx = d / 2; const dy = dx; let points = []; const altitude = Math.sqrt(3) / 2 * d; var N = Math.sqrt(bbox.area / (d * d)); for (let y = 0; y < N; y++) { for (let x = 0; x < N; x++) { points.push(new Vector((0.5 + x) / N * bbox.width, (0.25 + 0.5 * x % 2 + y) / N * bbox.height)); // points.push(new Vector((y % 2) * dx + x * d + dx, y * d + dy)); // Pointy Top // points.push(new Vector(x * d, (x % 2) * dx + y * d)); // Flat Top } } return points; } /** * Creates a blue noise distribution of points in a particular bounding box * with a particular average distance between points. This is done by * creating a grid system and picking a random point in each grid. This has * the effect of creating a less random distribution of points. The second * parameter m determins the spacing between points in the grid. This ensures * that no two points are in the same grid. * * @summary Create a jittered grid based random blue noise point distribution. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @param {number} [seed=null] If specified use a local seed for creating the point * distribution. Otherwise, use the current global seed for generation * @param {number} [m=0] Maximum distance away from the edge of the grid that a * point can be placed. This acts to increase the padding between points. * This makes the noise less random. This number must be smaller than d. * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function jitteredGrid(bbox, d, seed = null, m = 0) { const rng = seed ? new Rand(seed) : Rand; let points = []; let pointBox; for (let y = 0; y < bbox.height - d; y += d) { for (let x = 0; x < bbox.width - d; x += d) { // Local bbox for the point to generate in const boxPos = new Vector(x - d + m, y - d + m); pointBox = new Rectangle(boxPos, x - m, y - m); points.push(rng.vector(pointBox)); } } return points; } /** * Creates a poisson, or blue noise distribution of points in a particular * bounding box with a particular average distance between points. This is * done by using poisson disk sampling which tries to create points so that the * distance between neighbors is as close to a fixed number (the distance d) * as possible. This algorithm is implemented using the poisson dart throwing * algorithm. * * @summary Create a blue noise distribution of points using poisson disk * sampling. * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * * @see {@link https://www.jasondavies.com/poisson-disc/} * @see {@link https://github.com/jeffrey-hearn/poisson-disk-sample} * @memberof PointDistribution */ export function poisson(bbox, d) { var sampler = new Poisson(bbox.width, bbox.height, d, d); var solution = sampler.sampleUntilSolution(); var points = solution.map(point => Vector.add(new Vector(point), bbox.position)); return points; } /** * Creates a blue noise distribution of points in a particular bounding box * with a particular average distance between points. This is done by using * recursive wang tiles to create this distribution of points. * * @summary Not Implemented Yet * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function recursiveWang(bbox, d) { throw "Error: Not Implemented"; } /** * Creates a circular distribution of points in a particular bounding box * with a particular average distance between points. * * @summary Not Implemented Yet * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number} d Average distance between points * @returns {Vector[]} The list of randomly distributed points * @memberof PointDistribution */ export function circular(bbox, d) { throw "Error: Not Implemented"; }
Evelios/Atum
src/utilities/PointDistribution.js
JavaScript
mit
7,914
<?php namespace Expense\SiteBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
mahasayz/expenses
src/Expense/SiteBundle/Tests/Controller/DefaultControllerTest.php
PHP
mit
401
'use strict'; angular.module('refugeesApp') .controller('SettingsController', function ($scope, Principal, Auth, Language, $translate) { $scope.success = null; $scope.error = null; Principal.identity().then(function(account) { $scope.settingsAccount = copyAccount(account); }); $scope.save = function () { Auth.updateAccount($scope.settingsAccount).then(function() { $scope.error = null; $scope.success = 'OK'; Principal.identity(true).then(function(account) { $scope.settingsAccount = copyAccount(account); }); Language.getCurrent().then(function(current) { if ($scope.settingsAccount.langKey !== current) { $translate.use($scope.settingsAccount.langKey); } }); }).catch(function() { $scope.success = null; $scope.error = 'ERROR'; }); }; /** * Store the "settings account" in a separate variable, and not in the shared "account" variable. */ var copyAccount = function (account) { return { activated: account.activated, email: account.email, firstName: account.firstName, langKey: account.langKey, lastName: account.lastName, login: account.login } } });
hubek/Refugees
src/main/webapp/scripts/app/account/settings/settings.controller.js
JavaScript
mit
1,537
using System.Windows.Controls; namespace pzy.AO.ClickSaver { /// <summary> /// Interaction logic for MissionInfo.xaml /// </summary> public partial class MissionInfo : UserControl { public MissionInfo() { InitializeComponent(); } public void Clear() { _tbLocation.Text = ""; _tbType.Text = ""; _tbRewardItem.Text = ""; _tbFindItem.Text = ""; _tbExperience.Text = ""; _tbCash.Text = ""; _tbValue.Text = ""; _tbTotal.Text = ""; } } }
pzychotic/AO.ClickSaver
AO.ClickSaver/Source/MissionInfo.xaml.cs
C#
mit
617
var UTIL = require('./util'); var ShadowNode; module.exports = ShadowNode = function(patch,options){ this.shadow = options.shadow; this.native = options.native; this.elem = new patch.type(this); this.elem.props = patch.props; this.elem.props.children = patch.children; this.elem.state = this.elem.getInitialState ? this.elem.getInitialState() : {}; this.elem.componentWillMount(); this.render(); this.elem.componentDidMount(); }; var proto = ShadowNode.prototype; Object.defineProperty(proto,'parent',{ get : function(){ return this.native.parent; } }); proto.setPatch = function(patch){ var oldProps = this.elem.props; this.elem._isUpdating = true; var newProps = patch.props; newProps.children = patch.children; this.elem.componentWillRecieveProps(newProps); this.elem.props = newProps; this.elem.componentDidRecieveProps(oldProps); this.update(); }; proto.update = function(){ // This is called by set state and by props updating this.elem.componentWillUpdate(); this.render(); this.elem.componentWillUpdate(); }; proto.remove = function(){ this.elem.componentWillUnmount(); this.destroyed = true; if (this.figure){ return this.figure.remove(); } this.shadow = void 0; this.figure = void 0; this.native = void 0; this.elem.componentDidUnmount(); }; proto.render = function(){ var newPatch = this.elem.render(); var lastPatch = this.lastPatch; this.lastPatch = newPatch; if (!lastPatch && !newPatch) return; if (UTIL.isNative(newPatch)){ if (this.figure){ this.figure.remove(); this.figure = void 0; } this.native.shadowTail = this; return this.native.setPatch(newPatch); } if (UTIL.differentTypes(lastPatch,newPatch)){ if (this.figure) this.figure.remove(); this.figure = new ShadowNode(newPatch,{ shadow : this,native : this.native }); return this.figure; } if (UTIL.differentPatch(lastPatch,newPatch)){ // component will update this.figure.setPatch(newPatch); // component did update } };
guisouza/tEmbO
src/render/ShadowNode.js
JavaScript
mit
2,061
<?php namespace Cacic\CommonBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; class ModuloController extends Controller { /** * * Tela de exibição dos módulos do CACIC */ public function indexAction() { $em = $this->getDoctrine()->getManager(); $usuario = $this->getUser()->getIdUsuario(); $nivel = $em->getRepository('CacicCommonBundle:Usuario' )->nivel($usuario); $local = $this->getUser()->getIdLocal(); // Recupera o Local da sessão do usuário logado if($this->get('security.context')->isGranted('ROLE_ADMIN')) { $totalRedes = $em->getRepository('CacicCommonBundle:Rede')->countByLocalADM(); $inativos = $em->getRepository("CacicCommonBundle:Acao")->listarModulosInativos(); $modulos = $em->getRepository('CacicCommonBundle:Acao')->listarModulosOpcionais( ); } else { $totalRedes = $this->getDoctrine()->getRepository('CacicCommonBundle:Rede')->countByLocal( $local->getIdLocal() ); $modulos = $em->getRepository('CacicCommonBundle:Acao')->listarModulosOpcionais( $local->getIdLocal() ); } //Debug::dump($modulos);die; return $this->render( 'CacicCommonBundle:Modulo:index.html.twig', array( 'modulos' => $modulos, 'local' => $local, 'totalRedes' => $totalRedes, 'inativos' => $inativos ) ); } /** * * Tela de configuração do módulo informado * @todo Verificar padrão de codificação do Symfony * @param int $idAcao * @param Request $request */ public function editarAction( $idAcao, Request $request ) { $em = $this->getDoctrine()->getManager(); $logger = $this->get('logger'); $modulo = $em->getRepository( 'CacicCommonBundle:Acao' )->find( $idAcao ); if ( ! $modulo ) throw $this->createNotFoundException( 'Página não encontrada' ); if(!$this->get('security.context')->isGranted('ROLE_ADMIN')) { $local = $this->getUser()->getIdLocal(); $redes = $em->getRepository( 'CacicCommonBundle:Rede' )->listarPorLocal( $local ); } else { $local = $em->getRepository('CacicCommonBundle:Local')->findAll(); /* @todo Em caso de usuário administrativo, escolher o Local */ $redes = $em->getRepository( 'CacicCommonBundle:Rede' )->listarPorLocalADM(); } if ( $request->isMethod('POST') ) { $_data = $request->get('modulo'); $novasRedes = array_key_exists( 'rede', $_data ) ? $_data['rede'] : array(); $em->getRepository( 'CacicCommonBundle:AcaoRede' )->atualizarPorLocal( $idAcao, $local, $novasRedes ); // if ( $novasRedes ) // throw $this->createNotFoundException( 'Subrede não encontrado' ); $novosSO = array_key_exists( 'so', $_data ) ? $_data['so'] : array(); $em->getRepository( 'CacicCommonBundle:AcaoSo' )->atualizarPorLocal( $idAcao, $local, $novasRedes, $novosSO ); // if ( $novosSO ) // throw $this->createNotFoundException( 'Subrede não encontrado' ); $novasExcecoes = array_key_exists( 'mac', $_data ) ? explode(',', $_data['mac'] ) : array(); $em->getRepository( 'CacicCommonBundle:AcaoExcecao' )->atualizarPorLocal( $idAcao, $local, $novasRedes, $novasExcecoes ); $this->get('session')->getFlashBag()->add('success', 'Dados salvos com sucesso!'); return $this->redirect( $this->generateUrl( 'cacic_modulo_editar', array('idAcao'=>$idAcao) ) ); } $so = $em->getRepository( 'CacicCommonBundle:So' )->listar(); // Recupera a lista de SOs cadastrados $redesSelecionadas = array_keys( // Recupera as Redes já associadas à Ação $em->getRepository( 'CacicCommonBundle:AcaoRede' )->getArrayChaveValorRedesPorAcao( $idAcao ) ); $soSelecionados = array_keys( // Recupera os SOs já associados à Ação $em->getRepository( 'CacicCommonBundle:AcaoSo' )->getArrayChaveValorSoPorAcao( $idAcao ) ); $excecoes = $em->getRepository( 'CacicCommonBundle:AcaoExcecao' )->getArrayExcecoesPorAcao( $idAcao ); // Recupera a lista de excecoes return $this->render( 'CacicCommonBundle:Modulo:editar.html.twig', array( 'modulo' => $modulo, 'redes' => $redes, 'so' => $so, 'redesSelecionadas' => $redesSelecionadas, 'soSelecionados' => $soSelecionados, 'excecoesCadastradas' => $excecoes ) ); } public function desativarAction(Request $request, $idAcao) { if ( ! $request->isXmlHttpRequest() ) { $this->get('session')->getFlashBag()->add('error', 'Página não encontrada'); throw $this->createNotFoundException( 'Página não encontrada' ); } $em = $this->getDoctrine()->getManager(); $acao = $em->getRepository("CacicCommonBundle:Acao")->find($idAcao); if ( empty($acao) ) { $this->get('session')->getFlashBag()->add('error', 'Ação não encontrada!'); throw $this->createNotFoundException( 'Ação não encontrada' ); } $acao->setAtivo(false); $em->persist($acao); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'Módulo desativado com sucesso'); $response = new JsonResponse(); $response->setContent(json_encode(array( 'status' => 'ok' ))); $response->setStatusCode(200); return $response; } public function ativarAction(Request $request, $idAcao) { if ( ! $request->isXmlHttpRequest() ) { $this->get('session')->getFlashBag()->add('error', 'Página não encontrada'); throw $this->createNotFoundException( 'Página não encontrada' ); } $em = $this->getDoctrine()->getManager(); $acao = $em->getRepository("CacicCommonBundle:Acao")->find($idAcao); if ( empty($acao) ) { $this->get('session')->getFlashBag()->add('error', 'Ação não encontrada'); throw $this->createNotFoundException( 'Ação não encontrada' ); } $acao->setAtivo(true); $em->persist($acao); $em->flush(); $this->get('session')->getFlashBag()->add('success', 'Módulo ativado com sucesso'); $response = new JsonResponse(); $response->setContent(json_encode(array( 'status' => 'ok' ))); $response->setStatusCode(200); return $response; } }
lightbase/cacic
src/Cacic/CommonBundle/Controller/ModuloController.php
PHP
mit
6,575
package stacks3; import java.io.*; // Todo public class Zad3 { public static void main(String[] args) { Stos stos = new Stos(); while (true) { System.out.println("Podaj napis do odwrócenia (Puste konczy program)"); String napis = ""; try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); napis = br.readLine(); System.out.println(napis); } catch (IOException e){ e.printStackTrace(); } if (napis.isEmpty()) { break; } for (String litera : napis.split("")) { stos.dodajDoStosu(litera); } String napisDoWypisania = ""; while (true){ try{ napisDoWypisania += stos.pobierzZeStosu(); } catch (PustyStosException e){ break; } } System.out.println(napisDoWypisania); } } }
novirael/school-codebase
java/algorithms/src/stacks3/Zad3.java
Java
mit
1,100
#include "jai_texture_object.h" #include "jai_shader_define.h" namespace jai { namespace drawable { TextureObject::TextureObject() { mColorEffect.setIdentity(); } void TextureObject::_prepareDraw(int sample, Mat4 const & transform) { using namespace jai::ogl; auto sct = mShader ? mShader : ShaderCoordSample::GetNoraml(); sct->use(); unsigned char * buffer = (unsigned char *)mVertexts.data(); draw::SetVertexAttribData(sct->mACoord, 4, EDataType::Float, false, sizeof(Vertext), buffer + JumpPos); draw::SetVertexAttribData(sct->mASmpCoord, 2, EDataType::Float, false, sizeof(Vertext), buffer + JumpTV); if(sct->hasEffect()) draw::SetUniformMat(sct->mUEffect, mColorEffect); draw::SetUniformInt(sct->mUSmp, sample); draw::SetUniformFloat(sct->mUColor, mColor.red, mColor.green, mColor.blue, mColor.alpha); draw::SetUniformMat(sct->mUTransform, transform); draw::EnableVertexAttrib(sct->mACoord); draw::EnableVertexAttrib(sct->mASmpCoord); } }}
angzel/jai
source/jai/jai_drawable/jai_texture_object.cpp
C++
mit
1,145
<?php /** * @author Jay Zeng (jayzeng@jay-zeng.com) * @version 0.1 */ namespace Dao; /** * @package Dao */ class Db { /** * Default adapter to be used * * @var string */ private $_adapter = '\Dao\Adapter'; /** * Empty constructor */ public function __construct() {} /** * Sets an adapter * * @param String $adapter * @return self */ public function setAdapter($adapter) { $this->_adapter = $adapter; return $this; } /** * Return an adapter instance * * @return \Dao\Adapter adapter to be used * @throws \InvalidArgumentException */ public function getAdapter() { if( class_exists($this->_adapter) ) { return new $this->_adapter; } throw new \InvalidArgumentException( "Class {$this->_adapter} does not exist"); } } ?>
jayzeng/DAO
Src/Dao/Db.php
PHP
mit
900
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var videoWorksSchema = new Schema ({ title: { type: String }, directedBy: { type: [String] }, editedBy: { type: [String] }, cast: { type: [String] }, videoUrl: { type: String }, copyright: { type: String }, workInfo: { type: String }, coverImageUrl: { type: String }, created: { type: Date, default: Date.now } }); mongoose.model('videoWorks', videoWorksSchema);
joshm101/blackwashed_portfolio
modules/video-works/server/models/video-works.server.models.js
JavaScript
mit
527
package com.example.plugintest.manymethods.f.c; public class A5 { public static void a0(String msg) { System.out.println("msg=" + msg + 0); } public static void a1(String msg) { System.out.println("msg=" + msg + 1); } public static void a2(String msg) { System.out.println("msg=" + msg + 2); } public static void a3(String msg) { System.out.println("msg=" + msg + 3); } public static void a4(String msg) { System.out.println("msg=" + msg + 4); } public static void a5(String msg) { System.out.println("msg=" + msg + 5); } public static void a6(String msg) { System.out.println("msg=" + msg + 6); } public static void a7(String msg) { System.out.println("msg=" + msg + 7); } public static void a8(String msg) { System.out.println("msg=" + msg + 8); } public static void a9(String msg) { System.out.println("msg=" + msg + 9); } public static void a10(String msg) { System.out.println("msg=" + msg + 10); } public static void a11(String msg) { System.out.println("msg=" + msg + 11); } public static void a12(String msg) { System.out.println("msg=" + msg + 12); } public static void a13(String msg) { System.out.println("msg=" + msg + 13); } public static void a14(String msg) { System.out.println("msg=" + msg + 14); } public static void a15(String msg) { System.out.println("msg=" + msg + 15); } public static void a16(String msg) { System.out.println("msg=" + msg + 16); } public static void a17(String msg) { System.out.println("msg=" + msg + 17); } public static void a18(String msg) { System.out.println("msg=" + msg + 18); } public static void a19(String msg) { System.out.println("msg=" + msg + 19); } public static void a20(String msg) { System.out.println("msg=" + msg + 20); } public static void a21(String msg) { System.out.println("msg=" + msg + 21); } public static void a22(String msg) { System.out.println("msg=" + msg + 22); } public static void a23(String msg) { System.out.println("msg=" + msg + 23); } public static void a24(String msg) { System.out.println("msg=" + msg + 24); } public static void a25(String msg) { System.out.println("msg=" + msg + 25); } public static void a26(String msg) { System.out.println("msg=" + msg + 26); } public static void a27(String msg) { System.out.println("msg=" + msg + 27); } public static void a28(String msg) { System.out.println("msg=" + msg + 28); } public static void a29(String msg) { System.out.println("msg=" + msg + 29); } public static void a30(String msg) { System.out.println("msg=" + msg + 30); } public static void a31(String msg) { System.out.println("msg=" + msg + 31); } public static void a32(String msg) { System.out.println("msg=" + msg + 32); } public static void a33(String msg) { System.out.println("msg=" + msg + 33); } public static void a34(String msg) { System.out.println("msg=" + msg + 34); } public static void a35(String msg) { System.out.println("msg=" + msg + 35); } public static void a36(String msg) { System.out.println("msg=" + msg + 36); } public static void a37(String msg) { System.out.println("msg=" + msg + 37); } public static void a38(String msg) { System.out.println("msg=" + msg + 38); } public static void a39(String msg) { System.out.println("msg=" + msg + 39); } public static void a40(String msg) { System.out.println("msg=" + msg + 40); } public static void a41(String msg) { System.out.println("msg=" + msg + 41); } public static void a42(String msg) { System.out.println("msg=" + msg + 42); } public static void a43(String msg) { System.out.println("msg=" + msg + 43); } public static void a44(String msg) { System.out.println("msg=" + msg + 44); } public static void a45(String msg) { System.out.println("msg=" + msg + 45); } public static void a46(String msg) { System.out.println("msg=" + msg + 46); } public static void a47(String msg) { System.out.println("msg=" + msg + 47); } public static void a48(String msg) { System.out.println("msg=" + msg + 48); } public static void a49(String msg) { System.out.println("msg=" + msg + 49); } public static void a50(String msg) { System.out.println("msg=" + msg + 50); } public static void a51(String msg) { System.out.println("msg=" + msg + 51); } public static void a52(String msg) { System.out.println("msg=" + msg + 52); } public static void a53(String msg) { System.out.println("msg=" + msg + 53); } public static void a54(String msg) { System.out.println("msg=" + msg + 54); } public static void a55(String msg) { System.out.println("msg=" + msg + 55); } public static void a56(String msg) { System.out.println("msg=" + msg + 56); } public static void a57(String msg) { System.out.println("msg=" + msg + 57); } public static void a58(String msg) { System.out.println("msg=" + msg + 58); } public static void a59(String msg) { System.out.println("msg=" + msg + 59); } public static void a60(String msg) { System.out.println("msg=" + msg + 60); } public static void a61(String msg) { System.out.println("msg=" + msg + 61); } public static void a62(String msg) { System.out.println("msg=" + msg + 62); } public static void a63(String msg) { System.out.println("msg=" + msg + 63); } public static void a64(String msg) { System.out.println("msg=" + msg + 64); } public static void a65(String msg) { System.out.println("msg=" + msg + 65); } public static void a66(String msg) { System.out.println("msg=" + msg + 66); } public static void a67(String msg) { System.out.println("msg=" + msg + 67); } public static void a68(String msg) { System.out.println("msg=" + msg + 68); } public static void a69(String msg) { System.out.println("msg=" + msg + 69); } public static void a70(String msg) { System.out.println("msg=" + msg + 70); } public static void a71(String msg) { System.out.println("msg=" + msg + 71); } public static void a72(String msg) { System.out.println("msg=" + msg + 72); } public static void a73(String msg) { System.out.println("msg=" + msg + 73); } public static void a74(String msg) { System.out.println("msg=" + msg + 74); } public static void a75(String msg) { System.out.println("msg=" + msg + 75); } public static void a76(String msg) { System.out.println("msg=" + msg + 76); } public static void a77(String msg) { System.out.println("msg=" + msg + 77); } public static void a78(String msg) { System.out.println("msg=" + msg + 78); } public static void a79(String msg) { System.out.println("msg=" + msg + 79); } public static void a80(String msg) { System.out.println("msg=" + msg + 80); } public static void a81(String msg) { System.out.println("msg=" + msg + 81); } public static void a82(String msg) { System.out.println("msg=" + msg + 82); } public static void a83(String msg) { System.out.println("msg=" + msg + 83); } public static void a84(String msg) { System.out.println("msg=" + msg + 84); } public static void a85(String msg) { System.out.println("msg=" + msg + 85); } public static void a86(String msg) { System.out.println("msg=" + msg + 86); } public static void a87(String msg) { System.out.println("msg=" + msg + 87); } public static void a88(String msg) { System.out.println("msg=" + msg + 88); } public static void a89(String msg) { System.out.println("msg=" + msg + 89); } public static void a90(String msg) { System.out.println("msg=" + msg + 90); } public static void a91(String msg) { System.out.println("msg=" + msg + 91); } public static void a92(String msg) { System.out.println("msg=" + msg + 92); } public static void a93(String msg) { System.out.println("msg=" + msg + 93); } public static void a94(String msg) { System.out.println("msg=" + msg + 94); } public static void a95(String msg) { System.out.println("msg=" + msg + 95); } public static void a96(String msg) { System.out.println("msg=" + msg + 96); } public static void a97(String msg) { System.out.println("msg=" + msg + 97); } public static void a98(String msg) { System.out.println("msg=" + msg + 98); } public static void a99(String msg) { System.out.println("msg=" + msg + 99); } }
limpoxe/Android-Plugin-Framework
Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/f/c/A5.java
Java
mit
8,249
'use strict'; module.exports = { extends: ['./index', './rules/imports', './rules/frontend', './rules/vue'].map(require.resolve).concat(['plugin:vue/recommended']), parser: 'vue-eslint-parser', parserOptions: { parser: 'babel-eslint', sourceType: 'module', ecmaVersion: 2017, ecmaFeatures: { jsx: true, experimentalObjectRestSpread: true, }, }, rules: { // this two doesn't work in vue 'import/no-named-as-default': 'off', 'import/no-named-as-default-member': 'off', }, };
AfterShip/eslint-config-aftership
vue.js
JavaScript
mit
508
package com.yostajsc.style.designs.animations.sliders; /* * The MIT License (MIT) * * Copyright (c) 2014 daimajia * * 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. */ import android.view.View; import android.view.ViewGroup; import com.nineoldandroids.animation.ObjectAnimator; import com.yostajsc.style.designs.animations.BaseViewAnimator; public class SlideOutUpAnimator extends BaseViewAnimator { @Override public void prepare(View target) { ViewGroup parent = (ViewGroup) target.getParent(); getAnimatorAgent().playTogether( ObjectAnimator.ofFloat(target, "alpha", 1, 0), ObjectAnimator.ofFloat(target, "translationY", 0, -target.getBottom()) ); } }
nphau/Android-VFindWeek
yostajsc-style/src/main/java/com/yostajsc/style/designs/animations/sliders/SlideOutUpAnimator.java
Java
mit
1,754
using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using Quilt4.Service.Interface.Business; using Quilt4Net.Core.DataTransfer; namespace Quilt4.Service.Controllers.WebAPI.Client { [Authorize] public class ClientUserController : ApiController { private readonly IUserBusiness _userBusiness; public ClientUserController(IUserBusiness userBusiness) { _userBusiness = userBusiness; } [Authorize(Roles = Constants.Administrators)] [Route("api/Client/User")] public IEnumerable<UserResponse> Get() { var response = _userBusiness.GetAllUsers().Select(x => new UserResponse { UserName = x.Username, EMail = x.Email }); return response; } [HttpGet] [Route("api/Client/User/{searchString}")] public IEnumerable<QueryUserResponse> Get([FromUri]string searchString) { var callerIp = HttpContext.Current.Request.UserHostAddress; var response = _userBusiness.SearchUsers(searchString, callerIp).Select(x => new QueryUserResponse { UserName = x.Username, EMail = x.Email }); return response; } } }
Quilt4/Quilt4.Service
Quilt4.Service/Controllers/WebAPI/Client/ClientUserController.cs
C#
mit
1,237
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ReviewU { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
Chanh-L-L/ReviewU
ReviewU/App_Start/RouteConfig.cs
C#
mit
577
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Ioc.Net")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Ioc.Net")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("f6d4ae6f-4e01-40b2-bc0a-ea8c7eb517d5")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
plantain-00/csharp-demo
Playthings/Ioc.Net/Ioc.Net/Properties/AssemblyInfo.cs
C#
mit
1,302
module V1 module Map class PortsController < RegionRestrictedController expose(:port) before_action :check_port, only: :show def index render json: current_region.ports end def show render json: port end def calculate calculator = PortCostCalculator.new(yacht: current_user.yacht, port: port).call render status: calculator.status, json: { port: calculator } end private def check_port render status: 404, nothing: true if port.region_id != current_region.id end end end end
czajkovsky/sailhero-api
app/controllers/v1/map/ports_controller.rb
Ruby
mit
642
package com.faforever.client.leaderboard; import lombok.Data; @Data public class RatingStat { private final int rating; private final int totalCount; private final int countWithEnoughGamesPlayed; }
micheljung/downlords-faf-client
src/main/java/com/faforever/client/leaderboard/RatingStat.java
Java
mit
206
import React, {PropTypes} from 'react'; import { Link, IndexLink } from 'react-router'; // import {Navbar, Nav, NavItem, NavDropdown, MenuItem} from 'react-bootstrap'; class Header extends React.Component { constructor(props) { super(props); } render() { return ( <div id="container" className="link_box"> <div id="itemA"></div> <div id="itemB"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/ntop_all02.jpg" alt="dscount"/> </Link> </div> <div id="itemC"> <Link to="/"> <img src=" http://cdn.dscount.com/images_2016/top/btn_dscoupon02.jpg" alt="dscount"/> </Link> </div> <div id="itemD"></div> <div id="itemE"> <Link to="" >ログイン</Link> </div> <div id="itemF"> <Link to="/signup">会員登録</Link> </div> <div id="itemG"> <a href="#" >マイページ{" "}▼</a> </div> <div id="itemH"> <a href="#" >お客様センター{" "}▼</a> </div> <div id="itemI"> <a href="#" > <span className="glyphicon glyphicon-shopping-cart">(0)</span> </a> </div> <div id="itemJ"> <a href="#" > <span className="glyphicon glyphicon-heart">(1)</span> </a> </div> <form id="itemK"> <div className="field"> <button className="drop-down-btn" type="button" id="search">総合検索{" "}▼</button> <input className="header-search-input" type="text" id="searchterm" placeholder=" what do you want ?" /> <button className="search-submit" type="button" id="search"> <span className="glyphicon glyphicon-search"></span> </button> </div> </form> <div id="itemL"></div> </div> ); } } export default Header;
masakiando/dscount
src/components/common/Header.js
JavaScript
mit
1,959
//ButtonTable is a very very special case, because I am still not sure why it is a table :-) // alternate design is to make it a field. Filed looks more logical, but table is more convenient at this time. // we will review this design later and decide, meanwhile here is the ButtonPane table that DOES NOT inherit from AbstractTable //button field is only a data structure that is stored under buttons collection var ButtonField = function (nam, label, actionName) { this.name = nam; this.label = label; this.actionName = actionName; }; var ButtonPanel = function () { this.name = null; this.P2 = null; this.renderingOption = null; this.buttons = new Object(); //collection of buttonFields }; ButtonPanel.prototype.setData = function (dc) { var data = dc.grids[this.name]; if (data.length <= 1) { if (this.renderingOption == 'nextToEachOther') { this.P2.hideOrShowPanels([this.name], 'none'); } else { var listName = this.name + 'ButtonList'; var buttonList = this.P2.doc.getElementById(listName); //should we do the following or just say buttonList.innerHTML = '' while (buttonList.options.length) { buttonList.remove(0); } } return; } data = this.transposeIfRequired(data); //possible that it was hidden earlier.. Let us show it first this.P2.hideOrShowPanels([this.name], ''); if (this.renderingOption == 'nextToEachOther') this.enableButtons(data); else this.buildDropDown(data); }; //enable/disable buttons in a button panel based on data received from server ButtonPanel.prototype.enableButtons = function (data) { var doc = this.P2.doc; var n = data.length; if (n <= 1) return; //if the table has its second column, it is interpreted as Yes/No for enable. 0 or empty string is No, everything else is Yes var hasFlag = data[0].length > 1; //for convenience, get the buttons into a collection indexed by name var btnsToEnable = {}; for (var i = 1; i < n; i++) { var row = data[i]; if (hasFlag) { var flag = row[1]; if (!flag || flag == '0') continue; } btnsToEnable[row[0]] = true; } //now let us go thru each button, and hide or who it for (var btnName in this.buttons) { var ele = doc.getElementById(btnName); if (!ele) { debug('Design Error: Button panel ' + this.name + ' has not produced a DOM element with name ' + btnName); continue; } ele.style.display = btnsToEnable[btnName] ? '' : 'none'; } }; ButtonPanel.prototype.buildDropDown = function (data) { var flag; var doc = this.P2.doc; var ele = doc.getElementById(this.name + 'ButtonList'); if (!ele) { debug('DESIGN ERROR: Button Panel ' + this.name + ' has not produced a drop-down boc with name = ' + this.Name + 'ButtonList'); return; } //zap options first ele.innerHTML = ''; //that took away the first one also. Add a blank option var option = doc.createElement('option'); ele.appendChild(option); //this.buttons has all the button names defined for this panel with value = 'disabled' // i.e. this.buttons['button1'] = 'disabled'; // for the rows that are in data, mark them as enabled. var n = data.length; if (n <= 1) return; if ((n == 2) && (data[0].length > 1)) { var hasFlag = data[0].length > 1; for (var i = 0; i < data[0].length; i++) { if (hasFlag) { flag = data[1][i]; if (!flag || flag == '0') continue; } var btnName = data[0][i]; var btn = this.buttons[btnName]; if (!btn) { debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button'); continue; } option = doc.createElement('option'); option.value = btn.actionName; option.innerHTML = btn.label; ele.appendChild(option); } } else { var hasFlag = data[0].length > 1; for (var i = 1; i < n; i++) { if (hasFlag) { flag = data[i][1]; if (!flag || flag == '0') continue; } var btnName = data[i][0]; var btn = this.buttons[btnName]; if (!btn) { debug('Button Panel ' + this.name + ' is not defined with a button with name ' + btnName + ' but server is trying to enable this button'); continue; } option = doc.createElement('option'); option.value = btn.actionName; option.innerHTML = btn.label; ele.appendChild(option); } } }; //Standard way of getting data from server is a grid with first row as header row and rest a data rows. //But it is possible that server may send button names in first row, and optional second row as enable flag. //We detect the second case, and transpose the grid, so that a common logic can be used. ButtonPanel.prototype.transposeIfRequired = function (data) { //we need to transpose only if we have one or two rows var nbrRows = data && data.length; if (!nbrRows || nbrRows > 2) return data; var row = data[0]; var nbrCols = row.length; if (!nbrCols) return data; //We make a simple assumption, that the label for last column can not clash with the name of a button. if (!this.buttons[row[nbrCols - 1]]) return data; //we transpose the grid, with an empty header row var newData = null; if (data.length == 1) //button name only { newData = [['']]; for (var i = 0; i < nbrCols; i++) newData.push([row[i]]); } else { //button name with enable flag newData = [['', '']]; var row1 = data[1]; for (var i = 0; i < nbrCols; i++) newData.push([row[i], row1[i]]); } return newData; };
ExilantTechnologies/ExilityCore-5.0.0-ExampleProject
WebContent/exilityClient/js/api/features/tableButton.js
JavaScript
mit
6,354
package net.joelinn.stripe.response.transfers; import net.joelinn.stripe.response.AbstractListResponse; /** * User: Joe Linn * Date: 5/26/2014 * Time: 9:06 PM */ public class ListTransfersResponse extends AbstractListResponse<TransferResponse>{ }
jlinn/stripe-api-java
src/main/java/net/joelinn/stripe/response/transfers/ListTransfersResponse.java
Java
mit
253
/** * The MIT License (MIT) * Copyright (c) 2012 David Carver * 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. */ package us.nineworlds.serenity.volley; import us.nineworlds.plex.rest.model.impl.MediaContainer; import us.nineworlds.serenity.core.OkHttpStack; import android.content.Context; import android.util.Log; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.Volley; /** * @author dcarver * */ public class VolleyUtils { private static RequestQueue queue; public static RequestQueue getRequestQueueInstance(Context context) { if (queue == null) { queue = Volley.newRequestQueue(context, new OkHttpStack()); } return queue; } public static Request volleyXmlGetRequest(String url, Response.Listener response, Response.ErrorListener error) { SimpleXmlRequest<MediaContainer> request = new SimpleXmlRequest<MediaContainer>( Request.Method.GET, url, MediaContainer.class, response, error); if (queue == null) { Log.e("VolleyUtils", "Initialize Request Queue!"); return null; } return queue.add(request); } }
0359xiaodong/serenity-android
serenity-app/src/main/java/us/nineworlds/serenity/volley/VolleyUtils.java
Java
mit
2,183
</div> <!-- /#wrapper --> <!-- Metis Menu Plugin JavaScript --> <script src="<?php echo base_url('assets/js/plugins/metisMenu/metisMenu.min.js')?>"></script> <!-- Morris Charts JavaScript --> <script src="<?php echo base_url('assets/js/plugins/morris/raphael.min.js')?>"></script> <!-- Custom Theme JavaScript --> <script src="<?php echo base_url('assets/js/sb-admin-2.js')?>"></script> <script src="<?php echo base_url('assets/angular/angular.min.js')?>"></script> <script src="<?php echo base_url('assets/sweetalert/dist/sweetalert.min.js')?>"></script> <script src="<?php echo base_url('assets/js/swal-forms.js')?>"></script> <script src="<?php echo base_url('assets/js/ui-bootstrap-tpls-1.3.2.min.js')?>"></script> <script src="<?php echo base_url('assets/js/angularController.js')?>"></script> </body> </html>
hafiznuzal/sirumkit1
application/views/template/admin_footer.php
PHP
mit
876
package com.main.junaidstore.activities; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Parcelable; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.Toast; import com.main.junaidstore.R; import com.main.junaidstore.adapters.CategoriesAdapter; import com.main.junaidstore.adapters.MainGridAdapter; import com.main.junaidstore.interfaces.AsyncCallback; import com.main.junaidstore.libraries.GeneralFunctions; import com.main.junaidstore.libraries.NetworkInterface; import com.mikepenz.materialdrawer.AccountHeader; import com.mikepenz.materialdrawer.AccountHeaderBuilder; import com.mikepenz.materialdrawer.Drawer; import com.mikepenz.materialdrawer.DrawerBuilder; import com.mikepenz.materialdrawer.model.DividerDrawerItem; import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; import com.mikepenz.materialdrawer.model.ProfileDrawerItem; import com.mikepenz.materialdrawer.model.SecondaryDrawerItem; import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; import org.parceler.Parcels; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends FragmentActivity implements AsyncCallback { @BindView(R.id.activity_main) RelativeLayout main_activity_view; @BindView(R.id.main_image_grid) GridView image_grid; @BindView(R.id.main_header_tags) LinearLayout main_header_tags; @BindView(R.id.main_header_date) Spinner main_header_date; @BindView(R.id.main_header_category) Spinner main_header_category; private final String GET_POSTS_ALL_CATEGORIES = "All"; private final String GET_POSTS_FIRST_TIME = "firstTime"; public static final int CODE_POST_CATEGORIES = 291; public static final int CODE_POST_DATES = 292; public static final int CODE_POSTS = 293; public NetworkInterface networkInterface; public boolean initialDataLoadedCat = false; public boolean initialDataLoadedDates = false; public List<com.main.junaidstore.models.Categories> categoriesList; public List<com.main.junaidstore.models.Posts> datesList; public List<com.main.junaidstore.models.Posts> postsList; ProgressDialog progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); networkInterface = new NetworkInterface(this); progress = new ProgressDialog(this); progress.setTitle("Loading"); progress.setMessage("loading more records..."); progress.show(); main_header_date.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if(initialDataLoadedCat && initialDataLoadedDates && datesList.size()!=0 && categoriesList.size()!=0){ loadBasedOnNewCategories(); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); main_header_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if(initialDataLoadedCat && initialDataLoadedDates && datesList.size()!=0 && categoriesList.size()!=0){ loadBasedOnNewCategories(); } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); if(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.usertype)).equals("2")) { createDrawerForEmployee(); } else{ createDrawer(); } } private void loadBasedOnNewCategories(){ progress.show(); String categoryid = GET_POSTS_ALL_CATEGORIES; for(int i=0;i<this.categoriesList.size();i++){ if(this.categoriesList.get(i).getCategory().equals(main_header_category.getSelectedItem().toString())){ categoryid = this.categoriesList.get(i).getID(); } } MainActivity.this.networkInterface.getPosts(GeneralFunctions.getSessionValue(MainActivity.this,getResources().getString(R.string.userid)), GeneralFunctions.getSessionValue(MainActivity.this,getResources().getString(R.string.access_token)), categoryid, main_header_date.getSelectedItem().toString(), CODE_POSTS); } @Override protected void onResume(){ super.onResume(); initialDataLoadedCat = false; initialDataLoadedDates = false; this.networkInterface.getCategories(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.userid)), GeneralFunctions.getSessionValue(this,getResources().getString(R.string.access_token)), CODE_POST_CATEGORIES); this.networkInterface.getPostDates(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.userid)), GeneralFunctions.getSessionValue(this,getResources().getString(R.string.access_token)), CODE_POST_DATES); this.networkInterface.getPosts(GeneralFunctions.getSessionValue(this,getResources().getString(R.string.userid)), GeneralFunctions.getSessionValue(this,getResources().getString(R.string.access_token)), GET_POSTS_FIRST_TIME, "", CODE_POSTS); } private void createDrawerForEmployee(){ AccountHeader headerResult = new AccountHeaderBuilder() .withActivity(this) .withHeaderBackground(R.drawable.cover) .addProfiles( new ProfileDrawerItem().withName(getResources().getString(R.string.app_name)).withIcon(ContextCompat.getDrawable(getApplicationContext(),R.drawable.app_cover)) ) .build(); //Now create your drawer and pass the AccountHeader.Result Drawer result = new DrawerBuilder() .withAccountHeader(headerResult) .withActivity(this) .withTranslucentStatusBar(false) .withActionBarDrawerToggle(true) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // do something with the clicked item :D if(position == 3){ startActivity(new Intent(MainActivity.this,Categories.class)); } else if(position == 1){ startActivity(new Intent(MainActivity.this,AddNewItem.class)); } else if(position == -1 ){ new AlertDialog.Builder(MainActivity.this) .setTitle("Logout") .setMessage("Are you sure you want to logout ?") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.access_token),""); GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.usertype),""); GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.userid),""); Intent intent = new Intent(MainActivity.this,login.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); }}) .setNegativeButton(android.R.string.no, null).show(); } return false; } }) .build(); result.addStickyFooterItem(new PrimaryDrawerItem().withName("Logout")); } private void createDrawer(){ ////if you want to update the items at a later time it is recommended to keep it in a variable SecondaryDrawerItem item1 = new SecondaryDrawerItem ().withIdentifier(1).withName(R.string.add_item).withSelectable(true); SecondaryDrawerItem item2 = new SecondaryDrawerItem().withIdentifier(2).withName(R.string.category).withSelectable(true); AccountHeader headerResult = new AccountHeaderBuilder() .withActivity(this) .withHeaderBackground(R.drawable.cover) .addProfiles( new ProfileDrawerItem().withName(getResources().getString(R.string.app_name)).withIcon(ContextCompat.getDrawable(getApplicationContext(),R.drawable.app_cover)) ) .build(); //Now create your drawer and pass the AccountHeader.Result Drawer result = new DrawerBuilder() .withAccountHeader(headerResult) .withActivity(this) .withTranslucentStatusBar(false) .withActionBarDrawerToggle(true) .addDrawerItems( item1, new DividerDrawerItem(), item2 ) .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { // do something with the clicked item :D if(position == 3){ startActivity(new Intent(MainActivity.this,Categories.class)); } else if(position == 1){ startActivity(new Intent(MainActivity.this,AddNewItem.class)); } else if(position == -1 ){ new AlertDialog.Builder(MainActivity.this) .setTitle("Logout") .setMessage("Are you sure you want to logout ?") .setIcon(android.R.drawable.ic_dialog_alert) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.access_token),""); GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.usertype),""); GeneralFunctions.addSessionValue(MainActivity.this,getResources().getString(R.string.userid),""); Intent intent = new Intent(MainActivity.this,login.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); }}) .setNegativeButton(android.R.string.no, null).show(); } return false; } }) .build(); result.addStickyFooterItem(new PrimaryDrawerItem().withName("Logout")); } @Override public void AsyncCallback(int resultCode, Parcelable rf) { com.main.junaidstore.models.Response response = Parcels.unwrap(rf); if(CODE_POST_CATEGORIES == resultCode){ categoriesList = response.getCategories(); populateCategoriesDropdown(categoriesList); initialDataLoadedCat = true; } else if(CODE_POST_DATES == resultCode){ datesList = response.getPosts(); populateDatesDropdown(datesList); initialDataLoadedDates = true; } else if(CODE_POSTS == resultCode){ this.postsList = response.getPosts(); if(this.postsList.size() == 0){ Toast.makeText(getApplicationContext(),"No Records in this category",Toast.LENGTH_SHORT).show(); progress.dismiss(); return; } image_grid.setAdapter(new MainGridAdapter(getApplicationContext(),this.postsList,this)); } progress.dismiss(); } private void populateCategoriesDropdown(List<com.main.junaidstore.models.Categories> categories){ List<String> str = new ArrayList<>(); str.add("All"); for(com.main.junaidstore.models.Categories cat: categoriesList){ str.add(cat.getCategory()); } ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, str); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); main_header_category.setAdapter(adapter); } private void populateDatesDropdown(List<com.main.junaidstore.models.Posts> posts){ List<String> str = new ArrayList<>(); for(int i=posts.size() -1 ;i>=0;i--){ str.add(posts.get(i).getCreatedAt()); } ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_spinner_item, str); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); main_header_date.setAdapter(adapter); } }
mozi22/ImageUploadAndroidExample
app/src/main/java/com/main/junaidstore/activities/MainActivity.java
Java
mit
14,871
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "utilitydialog.h" #include "ui_helpmessagedialog.h" #include "bitcoingui.h" #include "clientmodel.h" #include "guiutil.h" #include "clientversion.h" #include "init.h" #include <stdio.h> #include <QCloseEvent> #include <QLabel> #include <QRegExp> #include <QVBoxLayout> /** "Help message" or "About" dialog box */ HelpMessageDialog::HelpMessageDialog(QWidget *parent, bool about) : QDialog(parent), ui(new Ui::HelpMessageDialog) { ui->setupUi(this); GUIUtil::restoreWindowGeometry("nHelpMessageDialogWindow", this->size(), this); QString version = tr("Fastcoin Core") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()); /* On x86 add a bit specifier to the version so that users can distinguish between * 32 and 64 bit builds. On other architectures, 32/64 bit may be more ambigious. */ #if defined(__x86_64__) version += " " + tr("(%1-bit)").arg(64); #elif defined(__i386__ ) version += " " + tr("(%1-bit)").arg(32); #endif if (about) { setWindowTitle(tr("About Fastcoin Core")); /// HTML-format the license message from the core QString licenseInfo = QString::fromStdString(LicenseInfo()); QString licenseInfoHTML = licenseInfo; // Make URLs clickable QRegExp uri("<(.*)>", Qt::CaseSensitive, QRegExp::RegExp2); uri.setMinimal(true); // use non-greedy matching licenseInfoHTML.replace(uri, "<a href=\"\\1\">\\1</a>"); // Replace newlines with HTML breaks licenseInfoHTML.replace("\n\n", "<br><br>"); ui->helpMessageLabel->setTextFormat(Qt::RichText); ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); text = version + "\n" + licenseInfo; ui->helpMessageLabel->setText(version + "<br><br>" + licenseInfoHTML); ui->helpMessageLabel->setWordWrap(true); } else { setWindowTitle(tr("Command-line options")); QString header = tr("Usage:") + "\n" + " fastcoin-qt [" + tr("command-line options") + "] " + "\n"; QString coreOptions = QString::fromStdString(HelpMessage(HMM_BITCOIN_QT)); QString uiOptions = tr("UI options") + ":\n" + " -choosedatadir " + tr("Choose data directory on startup (default: 0)") + "\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -rootcertificates=<file> " + tr("Set SSL root certificates for payment request (default: -system-)") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)"); ui->helpMessageLabel->setFont(GUIUtil::bitcoinAddressFont()); text = version + "\n" + header + "\n" + coreOptions + "\n" + uiOptions; ui->helpMessageLabel->setText(text); } } HelpMessageDialog::~HelpMessageDialog() { GUIUtil::saveWindowGeometry("nHelpMessageDialogWindow", this); delete ui; } void HelpMessageDialog::printToConsole() { // On other operating systems, the expected action is to print the message to the console. fprintf(stdout, "%s\n", qPrintable(text)); } void HelpMessageDialog::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } void HelpMessageDialog::on_okButton_accepted() { close(); } /** "Shutdown" window */ ShutdownWindow::ShutdownWindow(QWidget *parent, Qt::WindowFlags f): QWidget(parent, f) { QVBoxLayout *layout = new QVBoxLayout(); layout->addWidget(new QLabel( tr("Fastcoin Core is shutting down...") + "<br /><br />" + tr("Do not shut down the computer until this window disappears."))); setLayout(layout); } void ShutdownWindow::showShutdownWindow(BitcoinGUI *window) { if (!window) return; // Show a simple window indicating shutdown status QWidget *shutdownWindow = new ShutdownWindow(); // We don't hold a direct pointer to the shutdown window after creation, so use // Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually. shutdownWindow->setAttribute(Qt::WA_DeleteOnClose); shutdownWindow->setWindowTitle(window->windowTitle()); // Center shutdown window at where main window was const QPoint global = window->mapToGlobal(window->rect().center()); shutdownWindow->move(global.x() - shutdownWindow->width() / 2, global.y() - shutdownWindow->height() / 2); shutdownWindow->show(); } void ShutdownWindow::closeEvent(QCloseEvent *event) { event->ignore(); }
m0gliE/fastcoin-cli
src/qt/utilitydialog.cpp
C++
mit
4,995
/* function Canvas(paper, props){ var props = $.extend(true, { "x" : 0, "y" : 0, "width" : "100%", "height" : "100%" }, (props || {})), _scale = 1, _translateX = 0, _translateY = 0, self = this, lx = 0, ly = 0, ox = 0, oy = 0, canvasBg = paper.rect(props.x, props.y, props.width, props.height), canvas = paper.group(), elements = [] ; var moveFnc = function(dx, dy){ lx = dx * (1 / _scale) + ox; ly = dy * (1 / _scale) + oy; self.setTranslate(lx, ly); }, startFnc = function(){ var transform = canvasBg.transform(); for(var i = 0; i < transform.length; i++){ if(transform[i][0].toLowerCase() === "t"){ ox = parseInt(transform[i][1]) * _scale; oy = parseInt(transform[i][2]) * _scale; } } }, endFnc = function(){ ox = lx; oy = ly; }, applyTransform = function(){ canvas.transform("s" + _scale + "t" + _translateX + "," + _translateY); canvasBg.transform("s" + _scale + "t" + _translateX + "," + _translateY); } ; this.add = function(el){ canvas.add(el.getObj()); elements.push(el); return this; }; this.setTranslate = function(x, y){ _translateX = x; _translateY = y; applyTransform(); return this; }; this.getTranslate = function(){ return { "x" : _translateX, "y" : _translateY }; }; this.setScale = function(s, onEachElement){ _scale = s; applyTransform(); if(onEachElement){ for(var i = 0; i < elements.length; i++){ onEachElement(elements[i], s); } } return this; }; this.getScale = function(){ return _scale; }; this.getProps = function(){ return props; }; canvasBg.attr({ "fill" : "rgba(255, 255, 0, .5)", "stroke" : "#000000", "stroke-width" : 1 }); this .setTranslate(0, 0) .setScale(1) ; canvasBg.drag(moveFnc, startFnc, endFnc); } */
meszaros-lajos-gyorgy/meszaros-lajos-gyorgy.github.io
logica/js/class/Canvas.js
JavaScript
mit
1,852
<?php $column_width = (int)(80/count($columns)); if (!empty($list)) { ?><div class="bDiv" > <table cellspacing="0" cellpadding="0" border="0" id="flex1"> <thead> <tr class='hDiv'> <?php foreach ($columns as $column) { ?> <th width='<?php echo $column_width; ?>%'> <div class="text-left field-sorting <?php if (isset($order_by[0]) && $column->field_name == $order_by[0]) { ?><?php echo $order_by[1]; ?><?php }?>" rel='<?php echo $column->field_name; ?>'> <?php if (strtolower($column->display_as) == 'advertiser_game_id'): ?> <?php echo $this->l('advertiser_game_id'); ?> <?php else: ?> <?php echo $this->l($column->display_as); ?> <?php endif; ?> </div> </th> <?php } ?> <?php if (!$unset_delete || !$unset_edit || !$unset_read || !empty($actions)) { ?> <th align="left" abbr="tools" axis="col1" class="" width='20%'> <div class="text-right"> <?php echo $this->l('list_actions'); ?> </div> </th> <?php } ?> </tr> </thead> <tbody> <?php foreach ($list as $num_row => $row) { ?> <tr <?php if ($num_row % 2 == 1) { ?>class="erow"<?php } ?>> <?php foreach ($columns as $column) { ?> <?php $row_update_url = $row->edit_url; $row_update_url = str_replace("/edit/", "/update/", $row_update_url); ?> <input type="hidden" class="update-url" value="<?php echo $row_update_url; ?>" /> <td width='<?php echo $column_width; ?>%' class='<?php if (isset($order_by[0]) && $column->field_name == $order_by[0]) { ?>sorted<?php } ?>'> <div class='text-left'> <?php if ($column->field_name == 'created_on') { echo date('Y-m-d', $row->{$column->field_name}); } elseif ($column->field_name == 'recharge_status') { echo '<a href="#">'.$this->l('Recharge status').'</a>'; } elseif ($column->field_name == 'active') { echo '<span>'; if ($row->{$column->field_name} == 1) { echo $this->l('user_activated'); } else { echo $this->l('user_inactivated'); } echo '</span>'; echo '<input type="button" value="'.$this->l('list_actions').'" class="crud_search custom-btn custom-btn-primary m-l-20 activate-action">'; echo '<input type="hidden" value="'.$row->{$column->field_name}.'" name="activated_state" class="activated-state" />'; } elseif ($column->field_name == 'is_online') { if ($row->{$column->field_name} == 1) { echo $this->l('online'); } else { echo $this->l('offline'); } } elseif ($column->field_name == 'isproxy') { } elseif ($column->field_name == 'bind_status') { } else { echo $row->{$column->field_name} != '' ? $row->{$column->field_name} : '&nbsp;' ; } ?> </div> </td> <?php } ?> <?php if (!$unset_delete || !$unset_edit || !$unset_read || !empty($actions)) { ?> <td align="left" width='20%'> <div class='tools'> <?php if (!$unset_delete) { ?> <a href='<?php echo $row->delete_url; ?>' title='<?php echo $this->l('list_delete'); ?> <?php echo $subject; ?>' class="delete-row" > <span class='delete-icon'></span> </a> <?php } ?> <?php if (!$unset_edit) { ?> <a href='<?php echo $row->edit_url; ?>' title='<?php echo $this->l('view_details'); ?>' class="edit_button"><?php echo $this->l('view_details'); ?></a> <?php } ?> <?php if (!$unset_read) { ?> <a href='<?php echo $row->read_url; ?>' title='<?php echo $this->l('view_details'); ?>' class="edit_button"><?php echo $this->l('view_details'); ?></a> <?php } ?> <?php if (!empty($row->action_urls)) { foreach ($row->action_urls as $action_unique_id => $action_url) { $action = $actions[$action_unique_id]; ?> <a href="<?php echo $action_url; ?>" class="<?php echo $action->css_class; ?> crud-action" title="<?php echo $action->label; ?>"><?php if (!empty($action->image_url)) { ?><img src="<?php echo $action->image_url; ?>" alt="<?php echo $action->label; ?>" /><?php } ?></a> <?php } } ?> <div class='clear'></div> </div> </td> <?php }?> </tr> <?php } ?> </tbody> </table> </div> <?php } else { ?> <br/> &nbsp;&nbsp;&nbsp;&nbsp; <?php echo $this->l('list_no_items'); ?> <br/> <br/> <?php } ?> <div class="modal fade" id="game_details_action_modal" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> </div> <div class="modal-body"> <button type="button" class="close" data-dismiss="modal">&times;</button> <?php echo $this->l('confirm'); ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary" data-dismiss="modal"><?php echo $this->l('ok'); ?></button> <button type="reset" class="btn btn-default" data-dismiss="modal"><?php echo $this->l('cancel'); ?></button> </div> </div> </div> </div>
YoshitoshiAbe/haotian
assets/grocery_crud/themes/flexigrid/views/list_advertiser.php
PHP
mit
6,340
/* Bento * * $Id: Holder.java,v 1.14 2014/01/14 14:42:45 sthippo Exp $ * * Copyright (c) 2002-2014 by bentodev.org * * Use of this code in source or compiled form is subject to the * Bento Poetic License at http://www.bentodev.org/poetic-license.html */ package bento.runtime; import bento.lang.Definition; import bento.lang.ArgumentList; import bento.lang.ResolvedInstance; /** * A simple container for associating a definition with an instantiated * object. A Holder is useful for lazy instantiation (avoiding instantiation * till the last possible moment) and for providing name, type, source code * and other metadata about the object that can be obtained from the * definition * * * @author mash * */ public class Holder { public Definition nominalDef; public ArgumentList nominalArgs; public Definition def; public ArgumentList args; public Object data; public ResolvedInstance resolvedInstance; public Holder() { this(null, null, null, null, null, null, null); } public Holder(Definition nominalDef, ArgumentList nominalArgs, Definition def, ArgumentList args, Context context, Object data, ResolvedInstance resolvedInstance) { this.nominalDef = nominalDef; this.nominalArgs = nominalArgs; this.def = def; this.args = args; this.data = data; this.resolvedInstance = resolvedInstance; } public String toString() { return "{ nominalDef: " + (nominalDef == null ? "(null)" : nominalDef.getName()) + "\n nominalArgs: " + (nominalArgs == null ? "(null)" : nominalArgs.toString()) + "\n def: " + (def == null ? "(null)" : def.getName()) + "\n args: " + (args == null ? "(null)" : args.toString()) + "\n data: " + (data == null ? "(null)" : data.toString()) + "\n resolvedInstance: " + (resolvedInstance == null ? "(null)" : resolvedInstance.getName()) + "\n}"; } }
bentodev/bentolang
src/bento/runtime/Holder.java
Java
mit
2,076
// MvxReference.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com namespace MvvmCross.Plugins.Messenger { public enum MvxReference { // note that default subscription is Weak in MvvmCross messenger Weak = 0, Strong = 1 } }
martijn00/MvvmCross-Plugins
Messenger/MvvmCross.Plugins.Messenger/MvxReference.cs
C#
mit
461
/* * Copyright (c) 2014 airbug inc. http://airbug.com * * bugpack-registry may be freely distributed under the MIT license. */ //------------------------------------------------------------------------------- // Requires //------------------------------------------------------------------------------- var buildbug = require("buildbug"); //------------------------------------------------------------------------------- // Simplify References //------------------------------------------------------------------------------- var buildProject = buildbug.buildProject; var buildProperties = buildbug.buildProperties; var buildScript = buildbug.buildScript; var buildTarget = buildbug.buildTarget; var enableModule = buildbug.enableModule; var parallel = buildbug.parallel; var series = buildbug.series; var targetTask = buildbug.targetTask; //------------------------------------------------------------------------------- // Enable Modules //------------------------------------------------------------------------------- var aws = enableModule("aws"); var bugpack = enableModule('bugpack'); var bugunit = enableModule('bugunit'); var core = enableModule('core'); var lintbug = enableModule("lintbug"); var nodejs = enableModule('nodejs'); var uglifyjs = enableModule("uglifyjs"); //------------------------------------------------------------------------------- // Values //------------------------------------------------------------------------------- var name = "bugpack-registry"; var version = "0.1.7"; var dependencies = { bugpack: "0.2.2" }; //------------------------------------------------------------------------------- // Declare Properties //------------------------------------------------------------------------------- buildProperties({ name: name, version: version }); buildProperties({ node: { packageJson: { name: "{{name}}", version: "{{version}}", description: "Registry builder for the bugpack package loader", main: "./scripts/bugpack-registry-node.js", author: "Brian Neisler <brian@airbug.com>", dependencies: dependencies, repository: { type: "git", url: "https://github.com/airbug/bugpack.git" }, bugs: { url: "https://github.com/airbug/bugpack/issues" }, licenses: [ { type : "MIT", url : "https://raw.githubusercontent.com/airbug/bugpack/master/LICENSE" } ] }, sourcePaths: [ "../buganno/libraries/buganno/js/src", "../bugcore/libraries/bugcore/js/src", "../bugfs/libraries/bugfs/js/src", "../bugmeta/libraries/bugmeta/js/src", "./libraries/bugpack-registry/js/src" ], scriptPaths: [ "../buganno/libraries/buganno/js/scripts", "./projects/bugpack-registry-node/js/scripts" ], readmePath: "./README.md", unitTest: { packageJson: { name: "{{name}}-test", version: "{{version}}", main: "./scripts/bugpack-registry-node.js", dependencies: dependencies, scripts: { test: "node ./test/scripts/bugunit-run.js" } }, sourcePaths: [ "../bugdouble/libraries/bugdouble/js/src", "../bugunit/libraries/bugunit/js/src", "../bugyarn/libraries/bugyarn/js/src" ], scriptPaths: [ "../bugunit/libraries/bugunit/js/scripts" ], testPaths: [ "../buganno/libraries/buganno/js/test", "../bugcore/libraries/bugcore/js/test", "../bugfs/libraries/bugfs/js/test", "../bugmeta/libraries/bugmeta/js/test", "./libraries/bugpack-registry/js/test" ] } }, lint: { targetPaths: [ "." ], ignorePatterns: [ ".*\\.buildbug$", ".*\\.bugunit$", ".*\\.git$", ".*node_modules$" ] } }); //------------------------------------------------------------------------------- // BuildTargets //------------------------------------------------------------------------------- // Clean BuildTarget //------------------------------------------------------------------------------- buildTarget("clean").buildFlow( targetTask("clean") ); // Local BuildTarget //------------------------------------------------------------------------------- buildTarget("local").buildFlow( series([ targetTask("clean"), targetTask('lint', { properties: { targetPaths: buildProject.getProperty("lint.targetPaths"), ignores: buildProject.getProperty("lint.ignorePatterns"), lintTasks: [ "cleanupExtraSpacingAtEndOfLines", "ensureNewLineEnding", "indentEqualSignsForPreClassVars", "orderBugpackRequires", "orderRequireAnnotations", "updateCopyright" ] } }), parallel([ series([ targetTask("createNodePackage", { properties: { packageJson: buildProject.getProperty("node.packageJson"), packagePaths: { "./": [buildProject.getProperty("node.readmePath")], "./lib": buildProject.getProperty("node.sourcePaths").concat( buildProject.getProperty("node.unitTest.sourcePaths") ), "./scripts": buildProject.getProperty("node.scriptPaths").concat( buildProject.getProperty("node.unitTest.scriptPaths") ), "./test": buildProject.getProperty("node.unitTest.testPaths") } } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask("packNodePackage", { properties: { packageName: "{{node.packageJson.name}}", packageVersion: "{{node.packageJson.version}}" } }), targetTask('startNodeModuleTests', { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage( buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version") ); task.updateProperties({ modulePath: packedNodePackage.getFilePath() }); } }), targetTask("s3PutFile", { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version")); task.updateProperties({ file: packedNodePackage.getFilePath(), options: { acl: 'public-read', encrypt: true } }); }, properties: { bucket: "{{local-bucket}}" } }) ]) ]) ]) ).makeDefault(); // Prod BuildTarget //------------------------------------------------------------------------------- buildTarget("prod").buildFlow( series([ targetTask("clean"), targetTask('lint', { properties: { targetPaths: buildProject.getProperty("lint.targetPaths"), ignores: buildProject.getProperty("lint.ignorePatterns"), lintTasks: [ "cleanupExtraSpacingAtEndOfLines", "ensureNewLineEnding", "indentEqualSignsForPreClassVars", "orderBugpackRequires", "orderRequireAnnotations", "updateCopyright" ] } }), parallel([ //Create test bugpack-registry package series([ targetTask('createNodePackage', { properties: { packageJson: buildProject.getProperty("node.unitTest.packageJson"), packagePaths: { "./": [buildProject.getProperty("node.readmePath")], "./lib": buildProject.getProperty("node.sourcePaths").concat( buildProject.getProperty("node.unitTest.sourcePaths") ), "./scripts": buildProject.getProperty("node.scriptPaths").concat( buildProject.getProperty("node.unitTest.scriptPaths") ), "./test": buildProject.getProperty("node.unitTest.testPaths") } } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("node.unitTest.packageJson.name"), buildProject.getProperty("node.unitTest.packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask('packNodePackage', { properties: { packageName: "{{node.unitTest.packageJson.name}}", packageVersion: "{{node.unitTest.packageJson.version}}" } }), targetTask('startNodeModuleTests', { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage( buildProject.getProperty("node.unitTest.packageJson.name"), buildProject.getProperty("node.unitTest.packageJson.version") ); task.updateProperties({ modulePath: packedNodePackage.getFilePath(), checkCoverage: true }); } }) ]), // Create production bugpack-registry package series([ targetTask('createNodePackage', { properties: { packageJson: buildProject.getProperty("node.packageJson"), packagePaths: { "./": [buildProject.getProperty("node.readmePath")], "./lib": buildProject.getProperty("node.sourcePaths"), "./scripts": buildProject.getProperty("node.scriptPaths") } } }), targetTask('generateBugPackRegistry', { init: function(task, buildProject, properties) { var nodePackage = nodejs.findNodePackage( buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version") ); task.updateProperties({ sourceRoot: nodePackage.getBuildPath() }); } }), targetTask('packNodePackage', { properties: { packageName: "{{node.packageJson.name}}", packageVersion: "{{node.packageJson.version}}" } }), targetTask("s3PutFile", { init: function(task, buildProject, properties) { var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"), buildProject.getProperty("node.packageJson.version")); task.updateProperties({ file: packedNodePackage.getFilePath(), options: { acl: 'public-read', encrypt: true } }); }, properties: { bucket: "{{prod-deploy-bucket}}" } }), targetTask('npmConfigSet', { properties: { config: buildProject.getProperty("npmConfig") } }), targetTask('npmAddUser'), targetTask('publishNodePackage', { properties: { packageName: "{{node.packageJson.name}}", packageVersion: "{{node.packageJson.version}}" } }) ]) ]) ]) ); //------------------------------------------------------------------------------- // Build Scripts //------------------------------------------------------------------------------- buildScript({ dependencies: [ "bugcore", "bugflow", "bugfs" ], script: "./lintbug.js" });
airbug/bugpack-registry
buildbug.js
JavaScript
mit
15,072
<?php namespace App\Http\Controllers\Admin\Empresa; use App\Empresa; use Illuminate\Http\Request; class EmpresaController extends Controller { public function __construct() { $this->middleware('auth:web'); } public function empresasView() { $empresas = Empresa::where('ativo', '=', 1)->orderBy('created_at')->get(); return view('admin.empresa.empresas-view', compact('empresas')); } }
jthanlopes/SysGAP
app/Http/Controllers/Admin/Empresa/EmpresaController.php
PHP
mit
408
# -*- coding: utf-8 -*- # @Time : 2017/7/27 18:04 # @Author : play4fun # @File : calibrateCamera2.py # @Software: PyCharm """ calibrateCamera2.py: """ import cv2 import numpy as np def draw_axis(img, charuco_corners, charuco_ids, board): vecs = np.load("./calib.npz") # I already calibrated the camera mtx, dist, _, _ = [vecs[i] for i in ('mtx', 'dist', 'rvecs', 'tvecs')] ret, rvec, tvec = cv2.aruco.estimatePoseCharucoBoard( charuco_corners, charuco_ids, board, mtx, dist) if ret is not None and ret is True: cv2.aruco.drawAxis(img, mtx, dist, rvec, tvec, 0.1) def get_image(camera): ret, img = camera.read() return img def make_grayscale(img): ret = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) return ret def main(): camera = cv2.VideoCapture(0) img = get_image(camera) while True: cv2.imshow('calibration', img) cv2.waitKey(10) img = get_image(camera) gray = make_grayscale(img) corners, ids, rejected = cv2.aruco.detectMarkers(gray, aruco_dict, corners, ids) cv2.aruco.drawDetectedMarkers(img, corners, ids) if ids is not None and corners is not None \ and len(ids) > 0 and len(ids) == len(corners): diamond_corners, diamond_ids = \ cv2.aruco.detectCharucoDiamond(img, corners, ids, 0.05 / 0.03, cameraMatrix=mtx, distCoeffs=dist) cv2.aruco.drawDetectedDiamonds(img, diamond_corners, diamond_ids) '''if diamond_ids is not None and len(diamond_ids) >= 4: break''' board = cv2.aruco.CharucoBoard_create(9, 6, 0.05, 0.03, aruco_dict) if diamond_corners is not None and diamond_ids is not None \ and len(diamond_corners) == len(diamond_ids): count, char_corners, char_ids = \ cv2.aruco.interpolateCornersCharuco(diamond_corners, diamond_ids, gray, board) if count >= 3: draw_axis(img, char_corners, char_ids, board) if __name__ == '__main__': main()
makelove/OpenCV-Python-Tutorial
ch200_Extra_modules/aruco/Camera Calibration using ChArUco and Python/calibrateCamera2.py
Python
mit
2,398
def hamming_distance(bytes1, bytes2): distance = 0 for b1, b2 in zip(bytes1, bytes2): xored = b1^b2 distance += sum(1 for n in range(8) if (xored >> n) & 0x01) return distance
nfschmidt/cryptopals
python/byte.py
Python
mit
206
package jaredbgreat.climaticbiome.blocks; import jaredbgreat.climaticbiome.ClimaticBiomes; import jaredbgreat.climaticbiome.util.IHaveModel; import net.minecraft.block.BlockBush; import net.minecraft.item.Item; abstract public class BlockBushBase extends BlockBush implements IHaveModel { @Override public void registerModel() { ClimaticBiomes.proxy.registerItemRender(Item .getItemFromBlock(this), 0, "inventory"); } }
BlackJar72/ClimaticBiomePlacement
main/java/jaredbgreat/climaticbiome/blocks/BlockBushBase.java
Java
mit
434
export default function(that) { return !isNaN(that.curValue) && that.curValue%1===0; }
c0defre4k/vue-form-2
lib/validation/rules/integer.js
JavaScript
mit
89
'use strict'; angular.module('core').controller('SidebarController', ['$scope', 'Authentication', function($scope, Authentication) { $scope.authentication = Authentication; } ]);
Jean2bob/Gathering-mean-0.4
modules/core/client/controllers/sidebar.client.controller.js
JavaScript
mit
196
""" Module containing MPG Ranch NFC coarse classifier, version 3.1. An NFC coarse classifier classifies an unclassified clip as a `'Call'` if it appears to be a nocturnal flight call, or as a `'Noise'` otherwise. It does not classify a clip that has already been classified, whether manually or automatically. This classifier uses the same model as version 3.0, which was developed for TensorFlow 1, but updated for TensorFlow 2. The two classifiers were compared by running both on 16429 clips created by the Old Bird Thrush Detector Redux 1.1 and 22505 clips created by the Old Bird Tseep Detector Redux 1.1 from 17 nights of recordings made in Ithaca, NY from 2021-04-03 through 2021-04-19. The older classifier ran with TensorFlow 1.15.5 and the newer one with TensorFlow 2.5.0rc1. The two classifiers labeled the clips exactly the same. 1711 thrush clips were labeled as calls and the others as noises, and 2636 tseep clips were labeled as calls and the others as noises. """ from collections import defaultdict import logging import numpy as np import resampy import tensorflow as tf from vesper.command.annotator import Annotator from vesper.django.app.models import AnnotationInfo from vesper.singleton.clip_manager import clip_manager from vesper.util.settings import Settings import vesper.django.app.model_utils as model_utils import vesper.mpg_ranch.nfc_coarse_classifier_3_1.classifier_utils as \ classifier_utils import vesper.mpg_ranch.nfc_coarse_classifier_3_1.dataset_utils as \ dataset_utils import vesper.util.open_mp_utils as open_mp_utils import vesper.util.signal_utils as signal_utils import vesper.util.yaml_utils as yaml_utils _EVALUATION_MODE_ENABLED = False ''' This classifier can run in one of two modes, *normal mode* and *evaluation mode*. In normal mode, it annotates only unclassified clips, assigning to each a "Classification" annotation value or either "Call" or "Noise". In evaluation mode, the classifier classifies every clip whose clip type (e.g. "Tseep" or "Thrush") it recognizes and that already has a classification that is "Noise" or starts with "Call" or "XCall". The new classification is a function of both the existing classification and the *normal classification* that the classifier would assign to the clip in normal mode if it had no existing classification. The new classifications are as follows (where the classification pairs are (existing classification, normal classification)): (Noise, Noise) -> Noise (i.e. no change) (Noise, Call) -> FP (Call*, Call) -> Call* (i.e. no change) (Call*, Noise) -> FN* (i.e. only coarse part changes) (XCall*, Call) -> XCallP* (i.e. only coarse part changes) (XCall*, Noise) -> XCallN* (i.e. only coarse part changes) This reclassifies clips for which the normal classification differs from the existing classification in such a way that important sets of clips (i.e. false positives, false negatives, excluded call positives, and excluded call negatives) can subsequently be viewed in clip albums. ''' class Classifier(Annotator): extension_name = 'MPG Ranch NFC Coarse Classifier 3.1' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) open_mp_utils.work_around_multiple_copies_issue() # Suppress TensorFlow INFO and DEBUG log messages. logging.getLogger('tensorflow').setLevel(logging.WARN) self._classifiers = dict( (t, _Classifier(t)) for t in ('Tseep', 'Thrush')) if _EVALUATION_MODE_ENABLED: self._score_annotation_info = \ AnnotationInfo.objects.get(name='Score') def annotate_clips(self, clips): """Annotates the specified clips with the appropriate classifiers.""" clip_lists = self._get_clip_lists(clips) num_clips_classified = 0 for clip_type, clips in clip_lists.items(): classifier = self._classifiers.get(clip_type) if classifier is not None: # have classifier for this clip type num_clips_classified += self._annotate_clips(clips, classifier) return num_clips_classified def _get_clip_lists(self, clips): """Gets a mapping from clip types to lists of clips to classify.""" clip_lists = defaultdict(list) for clip in clips: if _EVALUATION_MODE_ENABLED or \ self._get_annotation_value(clip) is None: # clip should be classified clip_type = model_utils.get_clip_type(clip) clip_lists[clip_type].append(clip) return clip_lists def _annotate_clips(self, clips, classifier): """Annotates the specified clips with the specified classifier.""" num_clips_classified = 0 triples = classifier.classify_clips(clips) # if _EVALUATION_MODE_ENABLED and len(triples) > 0: # self._show_classification_errors(triples) for clip, auto_classification, score in triples: if auto_classification is not None: if _EVALUATION_MODE_ENABLED: old_classification = self._get_annotation_value(clip) new_classification = self._get_new_classification( old_classification, auto_classification) if new_classification is not None: self._annotate(clip, new_classification) num_clips_classified += 1 self._set_clip_score(clip, score) else: # normal mode self._annotate(clip, auto_classification) num_clips_classified += 1 return num_clips_classified def _get_new_classification(self, old_classification, auto_classification): old = old_classification auto = auto_classification if old is None: return None elif old.startswith('Call') and auto == 'Noise': return 'FN' + old[len('Call'):] elif old == 'Noise' and auto == 'Call': return 'FP' elif old.startswith('XCall') and auto == 'Noise': return 'XCallN' + old_classification[len('XCall'):] elif old.startswith('XCall') and auto == 'Call': return 'XCallP' + old_classification[len('XCall'):] else: return None def _set_clip_score(self, clip, score): value = '{:.3f}'.format(score) model_utils.annotate_clip( clip, self._score_annotation_info, value, creating_user=self._creating_user, creating_job=self._creating_job, creating_processor=self._creating_processor) def _show_classification_errors(self, triples): num_positives = 0 num_negatives = 0 false_positives = [] false_negatives = [] for i, (clip, new_classification, score) in enumerate(triples): old_classification = self._get_annotation_value(clip) if old_classification.startswith('Call'): num_positives += 1 if new_classification == 'Noise': false_negatives.append( (i, old_classification, new_classification, score)) else: # old classification does not start with 'Call' num_negatives += 1 if new_classification == 'Call': false_positives.append( (i, old_classification, new_classification, score)) num_clips = len(triples) logging.info('Classified {} clips.'.format(num_clips)) self._show_classification_errors_aux( 'calls', false_negatives, num_positives) self._show_classification_errors_aux( 'non-calls', false_positives, num_negatives) num_errors = len(false_positives) + len(false_negatives) accuracy = 100 * (1 - num_errors / num_clips) logging.info( 'The overall accuracy was {:.1f} percent.'.format(accuracy)) def _show_classification_errors_aux(self, category, errors, num_clips): num_errors = len(errors) percent = 100 * num_errors / num_clips logging.info(( '{} of {} {} ({:.1f} percent) where incorrectly ' 'classified:').format(num_errors, num_clips, category, percent)) for i, old_classification, new_classification, score in errors: logging.info( ' {} {} -> {} {}'.format( i, old_classification, new_classification, score)) class _Classifier: def __init__(self, clip_type): self.clip_type = clip_type self._model = self._load_model() self._settings = self._load_settings() # Configure waveform slicing. s = self._settings fs = s.waveform_sample_rate s2f = signal_utils.seconds_to_frames self._waveform_start_time = \ s.waveform_start_time + s.inference_waveform_start_time_offset self._waveform_duration = s.waveform_duration self._waveform_length = s2f(self._waveform_duration, fs) self._classification_threshold = \ self._settings.classification_threshold def _load_model(self): path = classifier_utils.get_keras_model_file_path(self.clip_type) logging.info(f'Loading classifier model from "{path}"...') return tf.keras.models.load_model(path) def _load_settings(self): path = classifier_utils.get_settings_file_path(self.clip_type) logging.info(f'Loading classifier settings from "{path}"...') text = path.read_text() d = yaml_utils.load(text) return Settings.create_from_dict(d) def classify_clips(self, clips): # logging.info('Collecting clip waveforms for scoring...') waveforms, indices = self._slice_clip_waveforms(clips) if len(waveforms) == 0: return [] else: # have at least one waveform slice to classify # Stack waveform slices to make 2-D NumPy array. self._waveforms = np.stack(waveforms) # logging.info('Scoring clip waveforms...') dataset = \ dataset_utils.create_spectrogram_dataset_from_waveforms_array( self._waveforms, dataset_utils.DATASET_MODE_INFERENCE, self._settings, batch_size=64, feature_name=self._settings.model_input_name) scores = self._model.predict(dataset).flatten() # logging.info('Classifying clips...') triples = [ self._classify_clip(i, score, clips) for i, score in zip(indices, scores)] return triples def _slice_clip_waveforms(self, clips): waveforms = [] indices = [] for i, clip in enumerate(clips): try: waveform = self._get_clip_samples(clip) except Exception as e: logging.warning(( 'Could not classify clip "{}", since its ' 'samples could not be obtained. Error message was: ' '{}').format(str(clip), str(e))) else: # got clip samples waveforms.append(waveform) indices.append(i) return waveforms, indices def _get_clip_samples(self, clip): clip_sample_rate = clip.sample_rate classifier_sample_rate = self._settings.waveform_sample_rate s2f = signal_utils.seconds_to_frames start_offset = s2f(self._waveform_start_time, clip_sample_rate) if clip_sample_rate != classifier_sample_rate: # need to resample # Get clip samples, including a millisecond of padding at # the end. I don't know what if any guarantees the # `resampy.resample` function offers about the relationship # between its input and output lengths, so we add the padding # to try to ensure that we don't wind up with too few samples # after resampling. length = s2f(self._waveform_duration + .001, clip_sample_rate) samples = clip_manager.get_samples( clip, start_offset=start_offset, length=length) # Resample clip samples to classifier sample rate. samples = resampy.resample( samples, clip_sample_rate, classifier_sample_rate) # Discard any extra trailing samples we wound up with. samples = samples[:self._waveform_length] if len(samples) < self._waveform_length: raise ValueError('Resampling produced too few samples.') else: # don't need to resample samples = clip_manager.get_samples( clip, start_offset=start_offset, length=self._waveform_length) return samples def _classify_clip(self, index, score, clips): if score >= self._classification_threshold: classification = 'Call' else: classification = 'Noise' return clips[index], classification, score
HaroldMills/Vesper
vesper/mpg_ranch/nfc_coarse_classifier_3_1/classifier.py
Python
mit
14,590
<?php /* * This file is part of the Sonata package. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\Cache\Adapter\Cache; use Sonata\Cache\CacheElement; /** * Handles APC cache. */ class ApcCache extends BaseCacheHandler { /** * @var string */ protected $url; /** * @var string */ protected $prefix; /** * @var array */ protected $servers; /** * @var bool */ protected $currentOnly; /** * @var array */ protected $timeout = array(); /** * Constructor. * * @param string $url A router instance * @param string $prefix A prefix to avoid clash between instances * @param array $servers An array of servers * @param array $timeout An array of timeout options */ public function __construct($url, $prefix, array $servers, array $timeout = array()) { $this->url = $url; $this->prefix = $prefix; $this->servers = $servers; $defaultTimeout = array( 'sec' => 5, 'usec' => 0, ); $this->timeout['RCV'] = isset($timeout['RCV']) ? array_merge($defaultTimeout, $timeout['RCV']) : $defaultTimeout; $this->timeout['SND'] = isset($timeout['SND']) ? array_merge($defaultTimeout, $timeout['SND']) : $defaultTimeout; } /** * @param bool $bool */ public function setCurrentOnly($bool) { $this->currentOnly = $bool; } /** s * {@inheritdoc} */ public function flushAll() { if ($this->currentOnly) { return apc_clear_cache('user') && apc_clear_cache(); } $result = true; foreach ($this->servers as $server) { if (count(explode('.', $server['ip'])) == 4) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } else { $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } // generate the raw http request $command = sprintf("GET %s HTTP/1.1\r\n", $this->getUrl()); $command .= sprintf("Host: %s\r\n", $server['domain']); if ($server['basic']) { $command .= sprintf("Authorization: Basic %s\r\n", $server['basic']); } $command .= "Connection: Close\r\n\r\n"; // setup the default timeout (avoid max execution time) socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $this->timeout['SND']); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $this->timeout['RCV']); socket_connect($socket, $server['ip'], $server['port']); socket_write($socket, $command); $content = ''; do { $buffer = socket_read($socket, 1024); $content .= $buffer; } while (!empty($buffer)); if ($result) { $result = substr($content, -2) == 'ok'; } } return $result; } /** * {@inheritdoc} */ public function flush(array $keys = array()) { if ($this->currentOnly) { return apc_delete($this->computeCacheKeys($keys)); } return $this->flushAll(); } /** * {@inheritdoc} */ public function has(array $keys) { return apc_exists($this->computeCacheKeys($keys)); } /** * {@inheritdoc} */ public function set(array $keys, $data, $ttl = CacheElement::DAY, array $contextualKeys = array()) { $cacheElement = new CacheElement($keys, $data, $ttl); apc_store( $this->computeCacheKeys($keys), $cacheElement, $cacheElement->getTtl() ); return $cacheElement; } /** * {@inheritdoc} */ public function get(array $keys) { return $this->handleGet($keys, apc_fetch($this->computeCacheKeys($keys))); } /** * {@inheritdoc} */ public function isContextual() { return false; } /** * @return string */ protected function getUrl() { return $this->url; } /** * Computes the given cache keys. * * @param array $keys * * @return string */ private function computeCacheKeys($keys) { ksort($keys); return md5($this->prefix.serialize($keys)); } }
rmzamora/cache
lib/Adapter/Cache/ApcCache.php
PHP
mit
4,597
#include <string> template std::allocator<char>::allocator(); template std::allocator<char>::~allocator(); template std::basic_string<char, std::char_traits<char>, std::allocator<char>>::basic_string(const char*, const std::allocator<char>&); template std::basic_string<char, std::char_traits<char>, std::allocator<char>>::~basic_string(); template const char* std::basic_string<char, std::char_traits<char>, std::allocator<char>>::c_str() const noexcept;
mohtamohit/CppSharp
src/CppParser/Bindings/CSharp/x86_64-linux-gnu-cxx11abi/Std-symbols.cpp
C++
mit
458
<?php namespace Theme; class Bootstrap extends \Reborn\Module\AbstractBootstrap { public function boot() { \Translate::load('theme::theme'); \Translate::load('theme::editor'); } public function adminMenu(\Reborn\Util\Menu $menu, $modUri) { $menu->add('theme', t('theme::theme.menu'), $modUri, 'appearance', $order = 35); if (user_has_access('theme.editor')) { $menu->add('theme-editor', t('theme::editor.menu'), $modUri.'/editor', 'appearance', $order = 36); } } public function settings() { return array(); } public function moduleToolbar() { $uri = \Uri::segment(3); if ($uri == 'editor') { $mod_toolbar = array(); } else { $mod_toolbar = array( 'add' => array( 'url' => 'theme/upload', 'name' => t('theme::theme.modToolbar'), 'info' => t('theme::theme.modToolbar'), 'class' => 'add' ) ); } return $mod_toolbar; } public function register() {} }
reborncms/reborn
heart/modules/theme/Bootstrap.php
PHP
mit
1,158
version https://git-lfs.github.com/spec/v1 oid sha256:bd24e43ef20f9f9e3c711e3d54df98d049591993ab374dbc14fbe801ba528183 size 10061
yogeshsaroya/new-cdnjs
ajax/libs/rimg/1.5.0/rimg.min.js
JavaScript
mit
130
module.exports = { snowboy: { models: { file: "node_modules/snowboy/resources/snowboy.umdl", sensitivity: "0.5", hotwords: "snowboy" }, detector: { resource: "node_modules/snowboy/resources/common.res", audioGain: 2.0 } } };
joyarzun/speeech
src/defaultConfig.js
JavaScript
mit
275
// dear imgui, v1.69 // (widgets code) /* Index of this file: // [SECTION] Forward Declarations // [SECTION] Widgets: Text, etc. // [SECTION] Widgets: Main (Button, Image, Checkbox, RadioButton, ProgressBar, Bullet, etc.) // [SECTION] Widgets: Low-level Layout helpers (Spacing, Dummy, NewLine, Separator, etc.) // [SECTION] Widgets: ComboBox // [SECTION] Data Type and Data Formatting Helpers // [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. // [SECTION] Widgets: InputText, InputTextMultiline // [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. // [SECTION] Widgets: TreeNode, CollapsingHeader, etc. // [SECTION] Widgets: Selectable // [SECTION] Widgets: ListBox // [SECTION] Widgets: PlotLines, PlotHistogram // [SECTION] Widgets: Value helpers // [SECTION] Widgets: MenuItem, BeginMenu, EndMenu, etc. // [SECTION] Widgets: BeginTabBar, EndTabBar, etc. // [SECTION] Widgets: BeginTabItem, EndTabItem, etc. */ #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, isprint #if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier #include <stddef.h> // intptr_t #else #include <stdint.h> // intptr_t #endif // 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 "-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 "-Wsign-conversion" // warning : implicit conversion changes signedness // #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 "-Wformat-nonliteral" // warning: format not a string literal, format string not checked #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 //------------------------------------------------------------------------- // Data //------------------------------------------------------------------------- // Those MIN/MAX values are not define because we need to point to them static const signed char IM_S8_MIN = -128; static const signed char IM_S8_MAX = 127; static const unsigned char IM_U8_MIN = 0; static const unsigned char IM_U8_MAX = 0xFF; static const signed short IM_S16_MIN = -32768; static const signed short IM_S16_MAX = 32767; static const unsigned short IM_U16_MIN = 0; static const unsigned short IM_U16_MAX = 0xFFFF; static const ImS32 IM_S32_MIN = INT_MIN; // (-2147483647 - 1), (0x80000000); static const ImS32 IM_S32_MAX = INT_MAX; // (2147483647), (0x7FFFFFFF) static const ImU32 IM_U32_MIN = 0; static const ImU32 IM_U32_MAX = UINT_MAX; // (0xFFFFFFFF) #ifdef LLONG_MIN static const ImS64 IM_S64_MIN = LLONG_MIN; // (-9223372036854775807ll - 1ll); static const ImS64 IM_S64_MAX = LLONG_MAX; // (9223372036854775807ll); #else static const ImS64 IM_S64_MIN = -9223372036854775807LL - 1; static const ImS64 IM_S64_MAX = 9223372036854775807LL; #endif static const ImU64 IM_U64_MIN = 0; #ifdef ULLONG_MAX static const ImU64 IM_U64_MAX = ULLONG_MAX; // (0xFFFFFFFFFFFFFFFFull); #else static const ImU64 IM_U64_MAX = (2ULL * 9223372036854775807LL + 1); #endif //------------------------------------------------------------------------- // [SECTION] Forward Declarations //------------------------------------------------------------------------- // Data Type helpers static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format); static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2); static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format); // For InputTextEx() static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data); static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end); static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false); //------------------------------------------------------------------------- // [SECTION] Widgets: Text, etc. //------------------------------------------------------------------------- // - TextUnformatted() // - Text() // - TextV() // - TextColored() // - TextColoredV() // - TextDisabled() // - TextDisabledV() // - TextWrapped() // - TextWrappedV() // - LabelText() // - LabelTextV() // - BulletText() // - BulletTextV() //------------------------------------------------------------------------- void ImGui::TextEx(const char* text, const char* text_end, ImGuiTextFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) text_end = text + strlen(text); // FIXME-OPT const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset); const float wrap_pos_x = window->DC.TextWrapPos; const bool wrap_enabled = (wrap_pos_x >= 0.0f); if (text_end - text > 2000 && !wrap_enabled) { // Long text! // Perform manual coarse clipping to optimize for long multi-line text // - From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. // - We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. // - We use memchr(), pay attention that well optimized versions of those str/mem functions are much faster than a casually written loop. const char* line = text; const float line_height = GetTextLineHeight(); ImVec2 text_size(0,0); // Lines to skip (can't skip when logging text) ImVec2 pos = text_pos; if (!g.LogEnabled) { int lines_skippable = (int)((window->ClipRect.Min.y - text_pos.y) / line_height); if (lines_skippable > 0) { int lines_skipped = 0; while (line < text_end && lines_skipped < lines_skippable) { const char* line_end = (const char*)memchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } } // Lines to render if (line < text_end) { ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height)); while (line < text_end) { if (IsClippedEx(line_rect, 0, false)) break; const char* line_end = (const char*)memchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); RenderText(pos, line, line_end, false); line = line_end + 1; line_rect.Min.y += line_height; line_rect.Max.y += line_height; pos.y += line_height; } // Count remaining lines int lines_skipped = 0; while (line < text_end) { const char* line_end = (const char*)memchr(line, '\n', text_end - line); if (!line_end) line_end = text_end; if ((flags & ImGuiTextFlags_NoWidthForLargeClippedText) == 0) text_size.x = ImMax(text_size.x, CalcTextSize(line, line_end).x); line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } text_size.y = (pos - text_pos).y; ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); ItemAdd(bb, 0); } else { const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); ImRect bb(text_pos, text_pos + text_size); ItemSize(text_size); if (!ItemAdd(bb, 0)) return; // Render (we don't hide text after ## in this end-user function) RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); } } void ImGui::TextUnformatted(const char* text, const char* text_end) { TextEx(text, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); } void ImGui::Text(const char* fmt, ...) { va_list args; va_start(args, fmt); TextV(fmt, args); va_end(args); } void ImGui::TextV(const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); TextEx(g.TempBuffer, text_end, ImGuiTextFlags_NoWidthForLargeClippedText); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) { va_list args; va_start(args, fmt); TextColoredV(col, fmt, args); va_end(args); } void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, col); TextV(fmt, args); PopStyleColor(); } void ImGui::TextDisabled(const char* fmt, ...) { va_list args; va_start(args, fmt); TextDisabledV(fmt, args); va_end(args); } void ImGui::TextDisabledV(const char* fmt, va_list args) { PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]); TextV(fmt, args); PopStyleColor(); } void ImGui::TextWrapped(const char* fmt, ...) { va_list args; va_start(args, fmt); TextWrappedV(fmt, args); va_end(args); } void ImGui::TextWrappedV(const char* fmt, va_list args) { bool need_backup = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position if one is already set if (need_backup) PushTextWrapPos(0.0f); TextV(fmt, args); if (need_backup) PopTextWrapPos(); } void ImGui::LabelText(const char* label, const char* fmt, ...) { va_list args; va_start(args, fmt); LabelTextV(label, fmt, args); va_end(args); } // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2)); const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, 0)) return; // Render const char* value_text_begin = &g.TempBuffer[0]; const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } void ImGui::BulletText(const char* fmt, ...) { va_list args; va_start(args, fmt); BulletTextV(fmt, args); va_end(args); } // Text with a little bullet aligned to the typical tree node. void ImGui::BulletTextV(const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const char* text_begin = g.TempBuffer; const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); const ImVec2 label_size = CalcTextSize(text_begin, text_end, false); const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding ItemSize(bb); if (!ItemAdd(bb, 0)) return; // Render RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false); } //------------------------------------------------------------------------- // [SECTION] Widgets: Main //------------------------------------------------------------------------- // - ButtonBehavior() [Internal] // - Button() // - SmallButton() // - InvisibleButton() // - ArrowButton() // - CloseButton() [Internal] // - CollapseButton() [Internal] // - Scrollbar() [Internal] // - Image() // - ImageButton() // - Checkbox() // - CheckboxFlags() // - RadioButton() // - ProgressBar() // - Bullet() //------------------------------------------------------------------------- bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (flags & ImGuiButtonFlags_Disabled) { if (out_hovered) *out_hovered = false; if (out_held) *out_held = false; if (g.ActiveId == id) ClearActiveID(); return false; } // Default behavior requires click+release on same spot if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0) flags |= ImGuiButtonFlags_PressedOnClickRelease; ImGuiWindow* backup_hovered_window = g.HoveredWindow; if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) g.HoveredWindow = window; #ifdef IMGUI_ENABLE_TEST_ENGINE if (id != 0 && window->DC.LastItemId != id) ImGuiTestEngineHook_ItemAdd(&g, bb, id); #endif bool pressed = false; bool hovered = ItemHoverable(bb, id); // Drag source doesn't report as hovered if (hovered && g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover)) hovered = false; // Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button if (g.DragDropActive && (flags & ImGuiButtonFlags_PressedOnDragDropHold) && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers)) if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) { hovered = true; SetHoveredID(id); if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy { pressed = true; FocusWindow(window); } } if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window) g.HoveredWindow = backup_hovered_window; // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one. if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0)) hovered = false; // Mouse if (hovered) { if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { // | CLICKING | HOLDING with ImGuiButtonFlags_Repeat // PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds // PressedOnClick | <on click> | <on click> <on repeat> <on repeat> .. // PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release) // PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> .. // FIXME-NAV: We don't honor those different behaviors. if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0]) { SetActiveID(id, window); if (!(flags & ImGuiButtonFlags_NoNavFocus)) SetFocusID(id, window); FocusWindow(window); } if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0])) { pressed = true; if (flags & ImGuiButtonFlags_NoHoldingActiveID) ClearActiveID(); else SetActiveID(id, window); // Hold on ID FocusWindow(window); } if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0]) { if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> pressed = true; ClearActiveID(); } // 'Repeat' mode acts when held regardless of _PressedOn flags (see table above). // Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings. if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true)) pressed = true; } if (pressed) g.NavDisableHighlight = true; } // Gamepad/Keyboard navigation // We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse. if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId)) hovered = true; if (g.NavActivateDownId == id) { bool nav_activated_by_code = (g.NavActivateId == id); bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed); if (nav_activated_by_code || nav_activated_by_inputs) pressed = true; if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id) { // Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button. g.NavActivateId = id; // This is so SetActiveId assign a Nav source SetActiveID(id, window); if ((nav_activated_by_code || nav_activated_by_inputs) && !(flags & ImGuiButtonFlags_NoNavFocus)) SetFocusID(id, window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); } } bool held = false; if (g.ActiveId == id) { if (pressed) g.ActiveIdHasBeenPressed = true; if (g.ActiveIdSource == ImGuiInputSource_Mouse) { if (g.ActiveIdIsJustActivated) g.ActiveIdClickOffset = g.IO.MousePos - bb.Min; if (g.IO.MouseDown[0]) { held = true; } else { if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease)) if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release> if (!g.DragDropActive) pressed = true; ClearActiveID(); } if (!(flags & ImGuiButtonFlags_NoNavFocus)) g.NavDisableHighlight = true; } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { if (g.NavActivateDownId != id) ClearActiveID(); } } if (out_hovered) *out_hovered = hovered; if (out_held) *out_held = held; return pressed; } bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 pos = window->DC.CursorPos; if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag) pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y; ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); const ImRect bb(pos, pos + size); ItemSize(size, style.FramePadding.y); if (!ItemAdd(bb, id)) return false; if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); if (pressed) MarkItemEdited(id); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); // Automatically close popups //if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // CloseCurrentPopup(); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); return pressed; } bool ImGui::Button(const char* label, const ImVec2& size_arg) { return ButtonEx(label, size_arg, 0); } // Small buttons fits within text without additional vertical spacing. bool ImGui::SmallButton(const char* label) { ImGuiContext& g = *GImGui; float backup_padding_y = g.Style.FramePadding.y; g.Style.FramePadding.y = 0.0f; bool pressed = ButtonEx(label, ImVec2(0, 0), ImGuiButtonFlags_AlignTextBaseLine); g.Style.FramePadding.y = backup_padding_y; return pressed; } // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; // Cannot use zero-size for InvisibleButton(). Unlike Button() there is not way to fallback using the label size. IM_ASSERT(size_arg.x != 0.0f && size_arg.y != 0.0f); const ImGuiID id = window->GetID(str_id); ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(size); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); return pressed; } bool ImGui::ArrowButtonEx(const char* str_id, ImGuiDir dir, ImVec2 size, ImGuiButtonFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiID id = window->GetID(str_id); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); const float default_size = GetFrameHeight(); ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); if (!ItemAdd(bb, id)) return false; if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat) flags |= ImGuiButtonFlags_Repeat; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding); RenderArrow(bb.Min + ImVec2(ImMax(0.0f, (size.x - g.FontSize) * 0.5f), ImMax(0.0f, (size.y - g.FontSize) * 0.5f)), dir); return pressed; } bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir) { float sz = GetFrameHeight(); return ArrowButtonEx(str_id, dir, ImVec2(sz, sz), 0); } // Button to close a window bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window. // (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible). const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius)); bool is_clipped = !ItemAdd(bb, id); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); if (is_clipped) return pressed; // Render ImVec2 center = bb.GetCenter(); if (hovered) window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), GetColorU32(held ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered), 9); float cross_extent = (radius * 0.7071f) - 1.0f; ImU32 cross_col = GetColorU32(ImGuiCol_Text); center -= ImVec2(0.5f, 0.5f); window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f); window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f); return pressed; } bool ImGui::CollapseButton(ImGuiID id, const ImVec2& pos) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImRect bb(pos, pos + ImVec2(g.FontSize, g.FontSize) + g.Style.FramePadding * 2.0f); ItemAdd(bb, id); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_None); ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); if (hovered || held) window->DrawList->AddCircleFilled(bb.GetCenter() + ImVec2(0.0f, -0.5f), g.FontSize * 0.5f + 1.0f, col, 9); RenderArrow(bb.Min + g.Style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f); // Switch to moving the window after mouse is moved beyond the initial drag threshold if (IsItemActive() && IsMouseDragging()) StartMouseMovingWindow(window); return pressed; } ImGuiID ImGui::GetScrollbarID(ImGuiWindow* window, ImGuiAxis axis) { return window->GetIDNoKeepAlive(axis == ImGuiAxis_X ? "#SCROLLX" : "#SCROLLY"); } // Vertical/Horizontal scrollbar // The entire piece of code below is rather confusing because: // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) // - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar // - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal. void ImGui::Scrollbar(ImGuiAxis axis) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const bool horizontal = (axis == ImGuiAxis_X); const ImGuiStyle& style = g.Style; const ImGuiID id = GetScrollbarID(window, axis); KeepAliveID(id); // Render background bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX); float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f; const ImRect window_rect = window->Rect(); const float border_size = window->WindowBorderSize; ImRect bb = horizontal ? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size) : ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size); if (!horizontal) bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f); const float bb_height = bb.GetHeight(); if (bb.GetWidth() <= 0.0f || bb_height <= 0.0f) return; // When we are too small, start hiding and disabling the grab (this reduce visual noise on very small window and facilitate using the resize grab) float alpha = 1.0f; if ((axis == ImGuiAxis_Y) && bb_height < g.FontSize + g.Style.FramePadding.y * 2.0f) { alpha = ImSaturate((bb_height - g.FontSize) / (g.Style.FramePadding.y * 2.0f)); if (alpha <= 0.0f) return; } const bool allow_interaction = (alpha >= 1.0f); int window_rounding_corners; if (horizontal) window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); else window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight); window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners); bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f))); // V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar) float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight(); float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y; float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w; float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y; // Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers. const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f); const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v); const float grab_h_norm = grab_h_pixels / scrollbar_size_v; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). bool held = false; bool hovered = false; const bool previously_held = (g.ActiveId == id); ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus); float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v); float scroll_ratio = ImSaturate(scroll_v / scroll_max); float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; if (held && allow_interaction && grab_h_norm < 1.0f) { float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y; float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y; // Click position in scrollbar normalized space (0.0f->1.0f) const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v); SetHoveredID(id); bool seek_absolute = false; if (!previously_held) { // On initial click calculate the distance between mouse and the center of the grab if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm) { *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } else { seek_absolute = true; *click_delta_to_grab_center_v = 0.0f; } } // Apply scroll // It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v)); if (horizontal) window->Scroll.x = scroll_v; else window->Scroll.y = scroll_v; // Update values for rendering scroll_ratio = ImSaturate(scroll_v / scroll_max); grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v; // Update distance to grab now that we have seeked and saturated if (seek_absolute) *click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f; } // Render grab const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab, alpha); ImRect grab_rect; if (horizontal) grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y); else grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y)); window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding); } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); if (border_col.w > 0.0f) bb.Max += ImVec2(2, 2); ItemSize(bb); if (!ItemAdd(bb, 0)) return; if (border_col.w > 0.0f) { window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f); window->DrawList->AddImage(user_texture_id, bb.Min + ImVec2(1, 1), bb.Max - ImVec2(1, 1), uv0, uv1, GetColorU32(tint_col)); } else { window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col)); } } // frame_padding < 0: uses FramePadding from style (default) // frame_padding = 0: no framing // frame_padding > 0: set framing size // The color used are the button colors. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; // Default to using texture ID as ID. User can still push string/integer prefixes. // We could hash the size/uv to create a unique ID but that would prevent the user from animating UV. PushID((void*)(intptr_t)user_texture_id); const ImGuiID id = window->GetID("#image"); PopID(); const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding * 2); const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderNavHighlight(bb, id); RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding)); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col)); window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col)); return pressed; } bool ImGui::Checkbox(const char* label, bool* v) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const float square_sz = GetFrameHeight(); const ImVec2 pos = window->DC.CursorPos; const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) { *v = !(*v); MarkItemEdited(id); } const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); RenderNavHighlight(total_bb, id); RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); if (*v) { const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f)); RenderCheckMark(check_bb.Min + ImVec2(pad, pad), GetColorU32(ImGuiCol_CheckMark), square_sz - pad*2.0f); } if (g.LogEnabled) LogRenderedText(&total_bb.Min, *v ? "[x]" : "[ ]"); if (label_size.x > 0.0f) RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (*v ? ImGuiItemStatusFlags_Checked : 0)); return pressed; } bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { bool v = ((*flags & flags_value) == flags_value); bool pressed = Checkbox(label, &v); if (pressed) { if (v) *flags |= flags_value; else *flags &= ~flags_value; } return pressed; } bool ImGui::RadioButton(const char* label, bool active) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const float square_sz = GetFrameHeight(); const ImVec2 pos = window->DC.CursorPos; const ImRect check_bb(pos, pos + ImVec2(square_sz, square_sz)); const ImRect total_bb(pos, pos + ImVec2(square_sz + (label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f), label_size.y + style.FramePadding.y * 2.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id)) return false; ImVec2 center = check_bb.GetCenter(); center.x = (float)(int)center.x + 0.5f; center.y = (float)(int)center.y + 0.5f; const float radius = (square_sz - 1.0f) * 0.5f; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held); if (pressed) MarkItemEdited(id); RenderNavHighlight(total_bb, id); window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); if (active) { const float pad = ImMax(1.0f, (float)(int)(square_sz / 6.0f)); window->DrawList->AddCircleFilled(center, radius - pad, GetColorU32(ImGuiCol_CheckMark), 16); } if (style.FrameBorderSize > 0.0f) { window->DrawList->AddCircle(center + ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize); window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize); } if (g.LogEnabled) LogRenderedText(&total_bb.Min, active ? "(x)" : "( )"); if (label_size.x > 0.0f) RenderText(ImVec2(check_bb.Max.x + style.ItemInnerSpacing.x, check_bb.Min.y + style.FramePadding.y), label); return pressed; } bool ImGui::RadioButton(const char* label, int* v, int v_button) { const bool pressed = RadioButton(label, *v == v_button); if (pressed) *v = v_button; return pressed; } // size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, 0)) return; // Render fraction = ImSaturate(fraction); RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize)); const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y); RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding); // Default displaying the fraction as percentage string, but user can override it char overlay_buf[32]; if (!overlay) { ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f); overlay = overlay_buf; } ImVec2 overlay_size = CalcTextSize(overlay, NULL); if (overlay_size.x > 0.0f) RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb); } void ImGui::Bullet() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float line_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y*2), g.FontSize); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height)); ItemSize(bb); if (!ItemAdd(bb, 0)) { SameLine(0, style.FramePadding.x*2); return; } // Render and stay on same line RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f)); SameLine(0, style.FramePadding.x*2); } //------------------------------------------------------------------------- // [SECTION] Widgets: Low-level Layout helpers //------------------------------------------------------------------------- // - Spacing() // - Dummy() // - NewLine() // - AlignTextToFramePadding() // - Separator() // - VerticalSeparator() [Internal] // - SplitterBehavior() [Internal] //------------------------------------------------------------------------- void ImGui::Spacing() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ItemSize(ImVec2(0,0)); } void ImGui::Dummy(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); ItemAdd(bb, 0); } void ImGui::NewLine() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiLayoutType backup_layout_type = window->DC.LayoutType; window->DC.LayoutType = ImGuiLayoutType_Vertical; if (window->DC.CurrentLineSize.y > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height. ItemSize(ImVec2(0,0)); else ItemSize(ImVec2(0.0f, g.FontSize)); window->DC.LayoutType = backup_layout_type; } void ImGui::AlignTextToFramePadding() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; window->DC.CurrentLineSize.y = ImMax(window->DC.CurrentLineSize.y, g.FontSize + g.Style.FramePadding.y * 2); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y); } // Horizontal/vertical separating line void ImGui::Separator() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; // Those flags should eventually be overridable by the user ImGuiSeparatorFlags flags = (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal; IM_ASSERT(ImIsPowerOfTwo(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical))); // Check that only 1 option is selected if (flags & ImGuiSeparatorFlags_Vertical) { VerticalSeparator(); return; } // Horizontal Separator if (window->DC.ColumnsSet) PopClipRect(); float x1 = window->Pos.x; float x2 = window->Pos.x + window->Size.x; if (!window->DC.GroupStack.empty()) x1 += window->DC.Indent.x; const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f)); ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout. if (!ItemAdd(bb, 0)) { if (window->DC.ColumnsSet) PushColumnClipRect(); return; } window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator)); if (g.LogEnabled) LogRenderedText(&bb.Min, "--------------------------------"); if (window->DC.ColumnsSet) { PushColumnClipRect(); window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; } } void ImGui::VerticalSeparator() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; float y1 = window->DC.CursorPos.y; float y2 = window->DC.CursorPos.y + window->DC.CurrentLineSize.y; const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2)); ItemSize(ImVec2(bb.GetWidth(), 0.0f)); if (!ItemAdd(bb, 0)) return; window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator)); if (g.LogEnabled) LogText(" |"); } // Using 'hover_visibility_delay' allows us to hide the highlight and mouse cursor for a short time, which can be convenient to reduce visual noise. bool ImGui::SplitterBehavior(const ImRect& bb, ImGuiID id, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend, float hover_visibility_delay) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus; bool item_add = ItemAdd(bb, id); window->DC.ItemFlags = item_flags_backup; if (!item_add) return false; bool hovered, held; ImRect bb_interact = bb; bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f)); ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap); if (g.ActiveId != id) SetItemAllowOverlap(); if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id && g.HoveredIdTimer >= hover_visibility_delay)) SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); ImRect bb_render = bb; if (held) { ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min; float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x; // Minimum pane size float size_1_maximum_delta = ImMax(0.0f, *size1 - min_size1); float size_2_maximum_delta = ImMax(0.0f, *size2 - min_size2); if (mouse_delta < -size_1_maximum_delta) mouse_delta = -size_1_maximum_delta; if (mouse_delta > size_2_maximum_delta) mouse_delta = size_2_maximum_delta; // Apply resize if (mouse_delta != 0.0f) { if (mouse_delta < 0.0f) IM_ASSERT(*size1 + mouse_delta >= min_size1); if (mouse_delta > 0.0f) IM_ASSERT(*size2 - mouse_delta >= min_size2); *size1 += mouse_delta; *size2 -= mouse_delta; bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta)); MarkItemEdited(id); } } // Render const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : (hovered && g.HoveredIdTimer >= hover_visibility_delay) ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator); window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding); return held; } //------------------------------------------------------------------------- // [SECTION] Widgets: ComboBox //------------------------------------------------------------------------- // - BeginCombo() // - EndCombo() // - Combo() //------------------------------------------------------------------------- static float CalcMaxPopupHeightFromItemCount(int items_count) { ImGuiContext& g = *GImGui; if (items_count <= 0) return FLT_MAX; return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2); } bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags) { // Always consume the SetNextWindowSizeConstraint() call in our early return paths ImGuiContext& g = *GImGui; ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond; g.NextWindowData.SizeConstraintCond = 0; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth(); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb)) return false; bool hovered, held; bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held); bool popup_open = IsPopupOpen(id); const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); if (!(flags & ImGuiComboFlags_NoPreview)) window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left); if (!(flags & ImGuiComboFlags_NoArrowButton)) { window->DrawList->AddRectFilled(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right); RenderArrow(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down); } RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding); if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview)) RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f)); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if ((pressed || g.NavActivateId == id) && !popup_open) { if (window->DC.NavLayerCurrent == 0) window->NavLastIds[0] = id; OpenPopupEx(id); popup_open = true; } if (!popup_open) return false; if (backup_next_window_size_constraint) { g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint; g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w); } else { if ((flags & ImGuiComboFlags_HeightMask_) == 0) flags |= ImGuiComboFlags_HeightRegular; IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one int popup_max_height_in_items = -1; if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8; else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4; else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20; SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); } char name[16]; ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth // Peak into expected window size so we can position it if (ImGuiWindow* popup_window = FindWindowByName(name)) if (popup_window->WasActive) { ImVec2 size_expected = CalcWindowExpectedSize(popup_window); if (flags & ImGuiComboFlags_PopupAlignLeft) popup_window->AutoPosLastDirection = ImGuiDir_Left; ImRect r_outer = GetWindowAllowedExtentRect(popup_window); ImVec2 pos = FindBestWindowPosForPopupEx(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, r_outer, frame_bb, ImGuiPopupPositionPolicy_ComboBox); SetNextWindowPos(pos); } // Horizontally align ourselves with the framed text ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings; PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(style.FramePadding.x, style.WindowPadding.y)); bool ret = Begin(name, NULL, window_flags); PopStyleVar(); if (!ret) { EndPopup(); IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above return false; } return true; } void ImGui::EndCombo() { EndPopup(); } // Getter for the old Combo() API: const char*[] static bool Items_ArrayGetter(void* data, int idx, const char** out_text) { const char* const* items = (const char* const*)data; if (out_text) *out_text = items[idx]; return true; } // Getter for the old Combo() API: "item1\0item2\0item3\0" static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) { // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. const char* items_separated_by_zeros = (const char*)data; int items_count = 0; const char* p = items_separated_by_zeros; while (*p) { if (idx == items_count) break; p += strlen(p) + 1; items_count++; } if (!*p) return false; if (out_text) *out_text = p; return true; } // Old API, prefer using BeginCombo() nowadays if you can. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items) { ImGuiContext& g = *GImGui; // Call the getter to obtain the preview string which is a parameter to BeginCombo() const char* preview_value = NULL; if (*current_item >= 0 && *current_item < items_count) items_getter(data, *current_item, &preview_value); // The old Combo() API exposed "popup_max_height_in_items". The new more general BeginCombo() API doesn't have/need it, but we emulate it here. if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond) SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items))); if (!BeginCombo(label, preview_value, ImGuiComboFlags_None)) return false; // Display items // FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed) bool value_changed = false; for (int i = 0; i < items_count; i++) { PushID((void*)(intptr_t)i); const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; if (Selectable(item_text, item_selected)) { value_changed = true; *current_item = i; } if (item_selected) SetItemDefaultFocus(); PopID(); } EndCombo(); return value_changed; } // Combo box helper allowing to pass an array of strings. bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items) { const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); return value_changed; } // Combo box helper allowing to pass all items in a single string literal holding multiple zero-terminated items "item1\0item2\0" bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) { int items_count = 0; const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open while (*p) { p += strlen(p) + 1; items_count++; } bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); return value_changed; } //------------------------------------------------------------------------- // [SECTION] Data Type and Data Formatting Helpers [Internal] //------------------------------------------------------------------------- // - PatchFormatStringFloatToInt() // - DataTypeFormatString() // - DataTypeApplyOp() // - DataTypeApplyOpFromText() // - GetMinimumStepAtDecimalPrecision // - RoundScalarWithFormat<>() //------------------------------------------------------------------------- struct ImGuiDataTypeInfo { size_t Size; const char* PrintFmt; // Unused const char* ScanFmt; }; static const ImGuiDataTypeInfo GDataTypeInfo[] = { { sizeof(char), "%d", "%d" }, // ImGuiDataType_S8 { sizeof(unsigned char), "%u", "%u" }, { sizeof(short), "%d", "%d" }, // ImGuiDataType_S16 { sizeof(unsigned short), "%u", "%u" }, { sizeof(int), "%d", "%d" }, // ImGuiDataType_S32 { sizeof(unsigned int), "%u", "%u" }, #ifdef _MSC_VER { sizeof(ImS64), "%I64d","%I64d" }, // ImGuiDataType_S64 { sizeof(ImU64), "%I64u","%I64u" }, #else { sizeof(ImS64), "%lld", "%lld" }, // ImGuiDataType_S64 { sizeof(ImU64), "%llu", "%llu" }, #endif { sizeof(float), "%f", "%f" }, // ImGuiDataType_Float (float are promoted to double in va_arg) { sizeof(double), "%f", "%lf" }, // ImGuiDataType_Double }; IM_STATIC_ASSERT(IM_ARRAYSIZE(GDataTypeInfo) == ImGuiDataType_COUNT); // FIXME-LEGACY: Prior to 1.61 our DragInt() function internally used floats and because of this the compile-time default value for format was "%.0f". // Even though we changed the compile-time default, we expect users to have carried %f around, which would break the display of DragInt() calls. // To honor backward compatibility we are rewriting the format string, unless IMGUI_DISABLE_OBSOLETE_FUNCTIONS is enabled. What could possibly go wrong?! static const char* PatchFormatStringFloatToInt(const char* fmt) { if (fmt[0] == '%' && fmt[1] == '.' && fmt[2] == '0' && fmt[3] == 'f' && fmt[4] == 0) // Fast legacy path for "%.0f" which is expected to be the most common case. return "%d"; const char* fmt_start = ImParseFormatFindStart(fmt); // Find % (if any, and ignore %%) const char* fmt_end = ImParseFormatFindEnd(fmt_start); // Find end of format specifier, which itself is an exercise of confidence/recklessness (because snprintf is dependent on libc or user). if (fmt_end > fmt_start && fmt_end[-1] == 'f') { #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS if (fmt_start == fmt && fmt_end[0] == 0) return "%d"; ImGuiContext& g = *GImGui; ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%.*s%%d%s", (int)(fmt_start - fmt), fmt, fmt_end); // Honor leading and trailing decorations, but lose alignment/precision. return g.TempBuffer; #else IM_ASSERT(0 && "DragInt(): Invalid format string!"); // Old versions used a default parameter of "%.0f", please replace with e.g. "%d" #endif } return fmt; } static inline int DataTypeFormatString(char* buf, int buf_size, ImGuiDataType data_type, const void* data_ptr, const char* format) { // Signedness doesn't matter when pushing integer arguments if (data_type == ImGuiDataType_S32 || data_type == ImGuiDataType_U32) return ImFormatString(buf, buf_size, format, *(const ImU32*)data_ptr); if (data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) return ImFormatString(buf, buf_size, format, *(const ImU64*)data_ptr); if (data_type == ImGuiDataType_Float) return ImFormatString(buf, buf_size, format, *(const float*)data_ptr); if (data_type == ImGuiDataType_Double) return ImFormatString(buf, buf_size, format, *(const double*)data_ptr); if (data_type == ImGuiDataType_S8) return ImFormatString(buf, buf_size, format, *(const ImS8*)data_ptr); if (data_type == ImGuiDataType_U8) return ImFormatString(buf, buf_size, format, *(const ImU8*)data_ptr); if (data_type == ImGuiDataType_S16) return ImFormatString(buf, buf_size, format, *(const ImS16*)data_ptr); if (data_type == ImGuiDataType_U16) return ImFormatString(buf, buf_size, format, *(const ImU16*)data_ptr); IM_ASSERT(0); return 0; } static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2) { IM_ASSERT(op == '+' || op == '-'); switch (data_type) { case ImGuiDataType_S8: if (op == '+') { *(ImS8*)output = ImAddClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } if (op == '-') { *(ImS8*)output = ImSubClampOverflow(*(const ImS8*)arg1, *(const ImS8*)arg2, IM_S8_MIN, IM_S8_MAX); } return; case ImGuiDataType_U8: if (op == '+') { *(ImU8*)output = ImAddClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } if (op == '-') { *(ImU8*)output = ImSubClampOverflow(*(const ImU8*)arg1, *(const ImU8*)arg2, IM_U8_MIN, IM_U8_MAX); } return; case ImGuiDataType_S16: if (op == '+') { *(ImS16*)output = ImAddClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } if (op == '-') { *(ImS16*)output = ImSubClampOverflow(*(const ImS16*)arg1, *(const ImS16*)arg2, IM_S16_MIN, IM_S16_MAX); } return; case ImGuiDataType_U16: if (op == '+') { *(ImU16*)output = ImAddClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } if (op == '-') { *(ImU16*)output = ImSubClampOverflow(*(const ImU16*)arg1, *(const ImU16*)arg2, IM_U16_MIN, IM_U16_MAX); } return; case ImGuiDataType_S32: if (op == '+') { *(ImS32*)output = ImAddClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } if (op == '-') { *(ImS32*)output = ImSubClampOverflow(*(const ImS32*)arg1, *(const ImS32*)arg2, IM_S32_MIN, IM_S32_MAX); } return; case ImGuiDataType_U32: if (op == '+') { *(ImU32*)output = ImAddClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } if (op == '-') { *(ImU32*)output = ImSubClampOverflow(*(const ImU32*)arg1, *(const ImU32*)arg2, IM_U32_MIN, IM_U32_MAX); } return; case ImGuiDataType_S64: if (op == '+') { *(ImS64*)output = ImAddClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } if (op == '-') { *(ImS64*)output = ImSubClampOverflow(*(const ImS64*)arg1, *(const ImS64*)arg2, IM_S64_MIN, IM_S64_MAX); } return; case ImGuiDataType_U64: if (op == '+') { *(ImU64*)output = ImAddClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } if (op == '-') { *(ImU64*)output = ImSubClampOverflow(*(const ImU64*)arg1, *(const ImU64*)arg2, IM_U64_MIN, IM_U64_MAX); } return; case ImGuiDataType_Float: if (op == '+') { *(float*)output = *(const float*)arg1 + *(const float*)arg2; } if (op == '-') { *(float*)output = *(const float*)arg1 - *(const float*)arg2; } return; case ImGuiDataType_Double: if (op == '+') { *(double*)output = *(const double*)arg1 + *(const double*)arg2; } if (op == '-') { *(double*)output = *(const double*)arg1 - *(const double*)arg2; } return; case ImGuiDataType_COUNT: break; } IM_ASSERT(0); } // User can input math operators (e.g. +100) to edit a numerical values. // NB: This is _not_ a full expression evaluator. We should probably add one and replace this dumb mess.. static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* format) { while (ImCharIsBlankA(*buf)) buf++; // We don't support '-' op because it would conflict with inputing negative value. // Instead you can use +-100 to subtract from an existing value char op = buf[0]; if (op == '+' || op == '*' || op == '/') { buf++; while (ImCharIsBlankA(*buf)) buf++; } else { op = 0; } if (!buf[0]) return false; // Copy the value in an opaque buffer so we can compare at the end of the function if it changed at all. IM_ASSERT(data_type < ImGuiDataType_COUNT); int data_backup[2]; IM_ASSERT(GDataTypeInfo[data_type].Size <= sizeof(data_backup)); memcpy(data_backup, data_ptr, GDataTypeInfo[data_type].Size); if (format == NULL) format = GDataTypeInfo[data_type].ScanFmt; // FIXME-LEGACY: The aim is to remove those operators and write a proper expression evaluator at some point.. int arg1i = 0; if (data_type == ImGuiDataType_S32) { int* v = (int*)data_ptr; int arg0i = *v; float arg1f = 0.0f; if (op && sscanf(initial_value_buf, format, &arg0i) < 1) return false; // Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision if (op == '+') { if (sscanf(buf, "%d", &arg1i)) *v = (int)(arg0i + arg1i); } // Add (use "+-" to subtract) else if (op == '*') { if (sscanf(buf, "%f", &arg1f)) *v = (int)(arg0i * arg1f); } // Multiply else if (op == '/') { if (sscanf(buf, "%f", &arg1f) && arg1f != 0.0f) *v = (int)(arg0i / arg1f); } // Divide else { if (sscanf(buf, format, &arg1i) == 1) *v = arg1i; } // Assign constant } else if (data_type == ImGuiDataType_Float) { // For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in format = "%f"; float* v = (float*)data_ptr; float arg0f = *v, arg1f = 0.0f; if (op && sscanf(initial_value_buf, format, &arg0f) < 1) return false; if (sscanf(buf, format, &arg1f) < 1) return false; if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract) else if (op == '*') { *v = arg0f * arg1f; } // Multiply else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide else { *v = arg1f; } // Assign constant } else if (data_type == ImGuiDataType_Double) { format = "%lf"; // scanf differentiate float/double unlike printf which forces everything to double because of ellipsis double* v = (double*)data_ptr; double arg0f = *v, arg1f = 0.0; if (op && sscanf(initial_value_buf, format, &arg0f) < 1) return false; if (sscanf(buf, format, &arg1f) < 1) return false; if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract) else if (op == '*') { *v = arg0f * arg1f; } // Multiply else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide else { *v = arg1f; } // Assign constant } else if (data_type == ImGuiDataType_U32 || data_type == ImGuiDataType_S64 || data_type == ImGuiDataType_U64) { // All other types assign constant // We don't bother handling support for legacy operators since they are a little too crappy. Instead we will later implement a proper expression evaluator in the future. sscanf(buf, format, data_ptr); } else { // Small types need a 32-bit buffer to receive the result from scanf() int v32; sscanf(buf, format, &v32); if (data_type == ImGuiDataType_S8) *(ImS8*)data_ptr = (ImS8)ImClamp(v32, (int)IM_S8_MIN, (int)IM_S8_MAX); else if (data_type == ImGuiDataType_U8) *(ImU8*)data_ptr = (ImU8)ImClamp(v32, (int)IM_U8_MIN, (int)IM_U8_MAX); else if (data_type == ImGuiDataType_S16) *(ImS16*)data_ptr = (ImS16)ImClamp(v32, (int)IM_S16_MIN, (int)IM_S16_MAX); else if (data_type == ImGuiDataType_U16) *(ImU16*)data_ptr = (ImU16)ImClamp(v32, (int)IM_U16_MIN, (int)IM_U16_MAX); else IM_ASSERT(0); } return memcmp(data_backup, data_ptr, GDataTypeInfo[data_type].Size) != 0; } static float GetMinimumStepAtDecimalPrecision(int decimal_precision) { static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f }; if (decimal_precision < 0) return FLT_MIN; return (decimal_precision < IM_ARRAYSIZE(min_steps)) ? min_steps[decimal_precision] : ImPow(10.0f, (float)-decimal_precision); } template<typename TYPE> static const char* ImAtoi(const char* src, TYPE* output) { int negative = 0; if (*src == '-') { negative = 1; src++; } if (*src == '+') { src++; } TYPE v = 0; while (*src >= '0' && *src <= '9') v = (v * 10) + (*src++ - '0'); *output = negative ? -v : v; return src; } template<typename TYPE, typename SIGNEDTYPE> TYPE ImGui::RoundScalarWithFormatT(const char* format, ImGuiDataType data_type, TYPE v) { const char* fmt_start = ImParseFormatFindStart(format); if (fmt_start[0] != '%' || fmt_start[1] == '%') // Don't apply if the value is not visible in the format string return v; char v_str[64]; ImFormatString(v_str, IM_ARRAYSIZE(v_str), fmt_start, v); const char* p = v_str; while (*p == ' ') p++; if (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) v = (TYPE)ImAtof(p); else ImAtoi(p, (SIGNEDTYPE*)&v); return v; } //------------------------------------------------------------------------- // [SECTION] Widgets: DragScalar, DragFloat, DragInt, etc. //------------------------------------------------------------------------- // - DragBehaviorT<>() [Internal] // - DragBehavior() [Internal] // - DragScalar() // - DragScalarN() // - DragFloat() // - DragFloat2() // - DragFloat3() // - DragFloat4() // - DragFloatRange2() // - DragInt() // - DragInt2() // - DragInt3() // - DragInt4() // - DragIntRange2() //------------------------------------------------------------------------- // This is called by DragBehavior() when the widget is active (held by mouse or being manipulated with Nav controls) template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE> bool ImGui::DragBehaviorT(ImGuiDataType data_type, TYPE* v, float v_speed, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiContext& g = *GImGui; const ImGuiAxis axis = (flags & ImGuiDragFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool has_min_max = (v_min != v_max); const bool is_power = (power != 1.0f && is_decimal && has_min_max && (v_max - v_min < FLT_MAX)); // Default tweak speed if (v_speed == 0.0f && has_min_max && (v_max - v_min < FLT_MAX)) v_speed = (float)((v_max - v_min) * g.DragSpeedDefaultRatio); // Inputs accumulates into g.DragCurrentAccum, which is flushed into the current value as soon as it makes a difference with our precision settings float adjust_delta = 0.0f; if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid() && g.IO.MouseDragMaxDistanceSqr[0] > 1.0f*1.0f) { adjust_delta = g.IO.MouseDelta[axis]; if (g.IO.KeyAlt) adjust_delta *= 1.0f / 100.0f; if (g.IO.KeyShift) adjust_delta *= 10.0f; } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f / 10.0f, 10.0f)[axis]; v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision)); } adjust_delta *= v_speed; // For vertical drag we currently assume that Up=higher value (like we do with vertical sliders). This may become a parameter. if (axis == ImGuiAxis_Y) adjust_delta = -adjust_delta; // Clear current value on activation // Avoid altering values and clamping when we are _already_ past the limits and heading in the same direction, so e.g. if range is 0..255, current value is 300 and we are pushing to the right side, keep the 300. bool is_just_activated = g.ActiveIdIsJustActivated; bool is_already_past_limits_and_pushing_outward = has_min_max && ((*v >= v_max && adjust_delta > 0.0f) || (*v <= v_min && adjust_delta < 0.0f)); bool is_drag_direction_change_with_power = is_power && ((adjust_delta < 0 && g.DragCurrentAccum > 0) || (adjust_delta > 0 && g.DragCurrentAccum < 0)); if (is_just_activated || is_already_past_limits_and_pushing_outward || is_drag_direction_change_with_power) { g.DragCurrentAccum = 0.0f; g.DragCurrentAccumDirty = false; } else if (adjust_delta != 0.0f) { g.DragCurrentAccum += adjust_delta; g.DragCurrentAccumDirty = true; } if (!g.DragCurrentAccumDirty) return false; TYPE v_cur = *v; FLOATTYPE v_old_ref_for_accum_remainder = (FLOATTYPE)0.0f; if (is_power) { // Offset + round to user desired precision, with a curve on the v_min..v_max range to get more precision on one side of the range FLOATTYPE v_old_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); FLOATTYPE v_new_norm_curved = v_old_norm_curved + (g.DragCurrentAccum / (v_max - v_min)); v_cur = v_min + (TYPE)ImPow(ImSaturate((float)v_new_norm_curved), power) * (v_max - v_min); v_old_ref_for_accum_remainder = v_old_norm_curved; } else { v_cur += (TYPE)g.DragCurrentAccum; } // Round to user desired precision based on format string v_cur = RoundScalarWithFormatT<TYPE, SIGNEDTYPE>(format, data_type, v_cur); // Preserve remainder after rounding has been applied. This also allow slow tweaking of values. g.DragCurrentAccumDirty = false; if (is_power) { FLOATTYPE v_cur_norm_curved = ImPow((FLOATTYPE)(v_cur - v_min) / (FLOATTYPE)(v_max - v_min), (FLOATTYPE)1.0f / power); g.DragCurrentAccum -= (float)(v_cur_norm_curved - v_old_ref_for_accum_remainder); } else { g.DragCurrentAccum -= (float)((SIGNEDTYPE)v_cur - (SIGNEDTYPE)*v); } // Lose zero sign for float/double if (v_cur == (TYPE)-0) v_cur = (TYPE)0; // Clamp values (+ handle overflow/wrap-around for integer types) if (*v != v_cur && has_min_max) { if (v_cur < v_min || (v_cur > *v && adjust_delta < 0.0f && !is_decimal)) v_cur = v_min; if (v_cur > v_max || (v_cur < *v && adjust_delta > 0.0f && !is_decimal)) v_cur = v_max; } // Apply result if (*v == v_cur) return false; *v = v_cur; return true; } bool ImGui::DragBehavior(ImGuiID id, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power, ImGuiDragFlags flags) { ImGuiContext& g = *GImGui; if (g.ActiveId == id) { if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0]) ClearActiveID(); else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) ClearActiveID(); } if (g.ActiveId != id) return false; switch (data_type) { case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = DragBehaviorT<ImS32, ImS32, float >(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS8*) v_min : IM_S8_MIN, v_max ? *(const ImS8*)v_max : IM_S8_MAX, format, power, flags); if (r) *(ImS8*)v = (ImS8)v32; return r; } case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = DragBehaviorT<ImU32, ImS32, float >(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU8*) v_min : IM_U8_MIN, v_max ? *(const ImU8*)v_max : IM_U8_MAX, format, power, flags); if (r) *(ImU8*)v = (ImU8)v32; return r; } case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = DragBehaviorT<ImS32, ImS32, float >(ImGuiDataType_S32, &v32, v_speed, v_min ? *(const ImS16*)v_min : IM_S16_MIN, v_max ? *(const ImS16*)v_max : IM_S16_MAX, format, power, flags); if (r) *(ImS16*)v = (ImS16)v32; return r; } case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = DragBehaviorT<ImU32, ImS32, float >(ImGuiDataType_U32, &v32, v_speed, v_min ? *(const ImU16*)v_min : IM_U16_MIN, v_max ? *(const ImU16*)v_max : IM_U16_MAX, format, power, flags); if (r) *(ImU16*)v = (ImU16)v32; return r; } case ImGuiDataType_S32: return DragBehaviorT<ImS32, ImS32, float >(data_type, (ImS32*)v, v_speed, v_min ? *(const ImS32* )v_min : IM_S32_MIN, v_max ? *(const ImS32* )v_max : IM_S32_MAX, format, power, flags); case ImGuiDataType_U32: return DragBehaviorT<ImU32, ImS32, float >(data_type, (ImU32*)v, v_speed, v_min ? *(const ImU32* )v_min : IM_U32_MIN, v_max ? *(const ImU32* )v_max : IM_U32_MAX, format, power, flags); case ImGuiDataType_S64: return DragBehaviorT<ImS64, ImS64, double>(data_type, (ImS64*)v, v_speed, v_min ? *(const ImS64* )v_min : IM_S64_MIN, v_max ? *(const ImS64* )v_max : IM_S64_MAX, format, power, flags); case ImGuiDataType_U64: return DragBehaviorT<ImU64, ImS64, double>(data_type, (ImU64*)v, v_speed, v_min ? *(const ImU64* )v_min : IM_U64_MIN, v_max ? *(const ImU64* )v_max : IM_U64_MAX, format, power, flags); case ImGuiDataType_Float: return DragBehaviorT<float, float, float >(data_type, (float*)v, v_speed, v_min ? *(const float* )v_min : -FLT_MAX, v_max ? *(const float* )v_max : FLT_MAX, format, power, flags); case ImGuiDataType_Double: return DragBehaviorT<double,double,double>(data_type, (double*)v, v_speed, v_min ? *(const double*)v_min : -DBL_MAX, v_max ? *(const double*)v_max : DBL_MAX, format, power, flags); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); return false; } bool ImGui::DragScalar(const char* label, ImGuiDataType data_type, void* v, float v_speed, const void* v_min, const void* v_max, const char* format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (power != 1.0f) IM_ASSERT(v_min != NULL && v_max != NULL); // When using a power curve the drag needs to have known bounds ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb)) return false; const bool hovered = ItemHoverable(frame_bb, id); // Default format string when passing NULL // Patch old "%.0f" format string to use "%d", read function comments for more details. IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) format = GDataTypeInfo[data_type].PrintFmt; else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Drag turns it into an input box bool start_text_input = false; const bool focus_requested = FocusableItemRegister(window, id); if (focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); if (focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) { window->DC.CursorPos = frame_bb.Min; FocusableItemUnregister(window); return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); } // Actual drag behavior const bool value_changed = DragBehavior(id, data_type, v, v_speed, v_min, v_max, format, power, ImGuiDragFlags_None); if (value_changed) MarkItemEdited(id); // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f, 0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags); return value_changed; } bool ImGui::DragScalarN(const char* label, ImGuiDataType data_type, void* v, int components, float v_speed, const void* v_min, const void* v_max, const char* format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { PushID(i); value_changed |= DragScalar("", data_type, v, v_speed, v_min, v_max, format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); } PopID(); TextEx(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalar(label, ImGuiDataType_Float, v, v_speed, &v_min, &v_max, format, power); } bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 2, v_speed, &v_min, &v_max, format, power); } bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 3, v_speed, &v_min, &v_max, format, power); } bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* format, float power) { return DragScalarN(label, ImGuiDataType_Float, v, 4, v_speed, &v_min, &v_max, format, power); } bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* format, const char* format_max, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2); bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, format_max ? format_max : format, power); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); TextEx(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); return value_changed; } // NB: v_speed is float to allow adjusting the drag speed with more precision bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* format) { return DragScalar(label, ImGuiDataType_S32, v, v_speed, &v_min, &v_max, format); } bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* format) { return DragScalarN(label, ImGuiDataType_S32, v, 2, v_speed, &v_min, &v_max, format); } bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* format) { return DragScalarN(label, ImGuiDataType_S32, v, 3, v_speed, &v_min, &v_max, format); } bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* format) { return DragScalarN(label, ImGuiDataType_S32, v, 4, v_speed, &v_min, &v_max, format); } bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* format, const char* format_max) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; PushID(label); BeginGroup(); PushMultiItemsWidths(2); bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, format_max ? format_max : format); PopItemWidth(); SameLine(0, g.Style.ItemInnerSpacing.x); TextEx(label, FindRenderedTextEnd(label)); EndGroup(); PopID(); return value_changed; } //------------------------------------------------------------------------- // [SECTION] Widgets: SliderScalar, SliderFloat, SliderInt, etc. //------------------------------------------------------------------------- // - SliderBehaviorT<>() [Internal] // - SliderBehavior() [Internal] // - SliderScalar() // - SliderScalarN() // - SliderFloat() // - SliderFloat2() // - SliderFloat3() // - SliderFloat4() // - SliderAngle() // - SliderInt() // - SliderInt2() // - SliderInt3() // - SliderInt4() // - VSliderScalar() // - VSliderFloat() // - VSliderInt() //------------------------------------------------------------------------- template<typename TYPE, typename FLOATTYPE> float ImGui::SliderCalcRatioFromValueT(ImGuiDataType data_type, TYPE v, TYPE v_min, TYPE v_max, float power, float linear_zero_pos) { if (v_min == v_max) return 0.0f; const bool is_power = (power != 1.0f) && (data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double); const TYPE v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min); if (is_power) { if (v_clamped < 0.0f) { const float f = 1.0f - (float)((v_clamped - v_min) / (ImMin((TYPE)0, v_max) - v_min)); return (1.0f - ImPow(f, 1.0f/power)) * linear_zero_pos; } else { const float f = (float)((v_clamped - ImMax((TYPE)0, v_min)) / (v_max - ImMax((TYPE)0, v_min))); return linear_zero_pos + ImPow(f, 1.0f/power) * (1.0f - linear_zero_pos); } } // Linear slider return (float)((FLOATTYPE)(v_clamped - v_min) / (FLOATTYPE)(v_max - v_min)); } // FIXME: Move some of the code into SliderBehavior(). Current responsability is larger than what the equivalent DragBehaviorT<> does, we also do some rendering, etc. template<typename TYPE, typename SIGNEDTYPE, typename FLOATTYPE> bool ImGui::SliderBehaviorT(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, TYPE* v, const TYPE v_min, const TYPE v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiAxis axis = (flags & ImGuiSliderFlags_Vertical) ? ImGuiAxis_Y : ImGuiAxis_X; const bool is_decimal = (data_type == ImGuiDataType_Float) || (data_type == ImGuiDataType_Double); const bool is_power = (power != 1.0f) && is_decimal; const float grab_padding = 2.0f; const float slider_sz = (bb.Max[axis] - bb.Min[axis]) - grab_padding * 2.0f; float grab_sz = style.GrabMinSize; SIGNEDTYPE v_range = (v_min < v_max ? v_max - v_min : v_min - v_max); if (!is_decimal && v_range >= 0) // v_range < 0 may happen on integer overflows grab_sz = ImMax((float)(slider_sz / (v_range + 1)), style.GrabMinSize); // For integer sliders: if possible have the grab size represent 1 unit grab_sz = ImMin(grab_sz, slider_sz); const float slider_usable_sz = slider_sz - grab_sz; const float slider_usable_pos_min = bb.Min[axis] + grab_padding + grab_sz*0.5f; const float slider_usable_pos_max = bb.Max[axis] - grab_padding - grab_sz*0.5f; // For power curve sliders that cross over sign boundary we want the curve to be symmetric around 0.0f float linear_zero_pos; // 0.0->1.0f if (is_power && v_min * v_max < 0.0f) { // Different sign const FLOATTYPE linear_dist_min_to_0 = ImPow(v_min >= 0 ? (FLOATTYPE)v_min : -(FLOATTYPE)v_min, (FLOATTYPE)1.0f/power); const FLOATTYPE linear_dist_max_to_0 = ImPow(v_max >= 0 ? (FLOATTYPE)v_max : -(FLOATTYPE)v_max, (FLOATTYPE)1.0f/power); linear_zero_pos = (float)(linear_dist_min_to_0 / (linear_dist_min_to_0 + linear_dist_max_to_0)); } else { // Same sign linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; } // Process interacting with the slider bool value_changed = false; if (g.ActiveId == id) { bool set_new_value = false; float clicked_t = 0.0f; if (g.ActiveIdSource == ImGuiInputSource_Mouse) { if (!g.IO.MouseDown[0]) { ClearActiveID(); } else { const float mouse_abs_pos = g.IO.MousePos[axis]; clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f; if (axis == ImGuiAxis_Y) clicked_t = 1.0f - clicked_t; set_new_value = true; } } else if (g.ActiveIdSource == ImGuiInputSource_Nav) { const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f); float delta = (axis == ImGuiAxis_X) ? delta2.x : -delta2.y; if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated) { ClearActiveID(); } else if (delta != 0.0f) { clicked_t = SliderCalcRatioFromValueT<TYPE,FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos); const int decimal_precision = is_decimal ? ImParseFormatPrecision(format, 3) : 0; if ((decimal_precision > 0) || is_power) { delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds if (IsNavInputDown(ImGuiNavInput_TweakSlow)) delta /= 10.0f; } else { if ((v_range >= -100.0f && v_range <= 100.0f) || IsNavInputDown(ImGuiNavInput_TweakSlow)) delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (float)v_range; // Gamepad/keyboard tweak speeds in integer steps else delta /= 100.0f; } if (IsNavInputDown(ImGuiNavInput_TweakFast)) delta *= 10.0f; set_new_value = true; if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits set_new_value = false; else clicked_t = ImSaturate(clicked_t + delta); } } if (set_new_value) { TYPE v_new; if (is_power) { // Account for power curve scale on both sides of the zero if (clicked_t < linear_zero_pos) { // Negative: rescale to the negative range before powering float a = 1.0f - (clicked_t / linear_zero_pos); a = ImPow(a, power); v_new = ImLerp(ImMin(v_max, (TYPE)0), v_min, a); } else { // Positive: rescale to the positive range before powering float a; if (ImFabs(linear_zero_pos - 1.0f) > 1.e-6f) a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos); else a = clicked_t; a = ImPow(a, power); v_new = ImLerp(ImMax(v_min, (TYPE)0), v_max, a); } } else { // Linear slider if (is_decimal) { v_new = ImLerp(v_min, v_max, clicked_t); } else { // For integer values we want the clicking position to match the grab box so we round above // This code is carefully tuned to work with large values (e.g. high ranges of U64) while preserving this property.. FLOATTYPE v_new_off_f = (v_max - v_min) * clicked_t; TYPE v_new_off_floor = (TYPE)(v_new_off_f); TYPE v_new_off_round = (TYPE)(v_new_off_f + (FLOATTYPE)0.5); if (!is_decimal && v_new_off_floor < v_new_off_round) v_new = v_min + v_new_off_round; else v_new = v_min + v_new_off_floor; } } // Round to user desired precision based on format string v_new = RoundScalarWithFormatT<TYPE,SIGNEDTYPE>(format, data_type, v_new); // Apply result if (*v != v_new) { *v = v_new; value_changed = true; } } } // Output grab position so it can be displayed by the caller float grab_t = SliderCalcRatioFromValueT<TYPE,FLOATTYPE>(data_type, *v, v_min, v_max, power, linear_zero_pos); if (axis == ImGuiAxis_Y) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); if (axis == ImGuiAxis_X) *out_grab_bb = ImRect(grab_pos - grab_sz*0.5f, bb.Min.y + grab_padding, grab_pos + grab_sz*0.5f, bb.Max.y - grab_padding); else *out_grab_bb = ImRect(bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f, bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f); return value_changed; } // For 32-bits and larger types, slider bounds are limited to half the natural type range. // So e.g. an integer Slider between INT_MAX-10 and INT_MAX will fail, but an integer Slider between INT_MAX/2-10 and INT_MAX/2 will be ok. // It would be possible to lift that limitation with some work but it doesn't seem to be worth it for sliders. bool ImGui::SliderBehavior(const ImRect& bb, ImGuiID id, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power, ImGuiSliderFlags flags, ImRect* out_grab_bb) { switch (data_type) { case ImGuiDataType_S8: { ImS32 v32 = (ImS32)*(ImS8*)v; bool r = SliderBehaviorT<ImS32, ImS32, float >(bb, id, ImGuiDataType_S32, &v32, *(const ImS8*)v_min, *(const ImS8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS8*)v = (ImS8)v32; return r; } case ImGuiDataType_U8: { ImU32 v32 = (ImU32)*(ImU8*)v; bool r = SliderBehaviorT<ImU32, ImS32, float >(bb, id, ImGuiDataType_U32, &v32, *(const ImU8*)v_min, *(const ImU8*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU8*)v = (ImU8)v32; return r; } case ImGuiDataType_S16: { ImS32 v32 = (ImS32)*(ImS16*)v; bool r = SliderBehaviorT<ImS32, ImS32, float >(bb, id, ImGuiDataType_S32, &v32, *(const ImS16*)v_min, *(const ImS16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImS16*)v = (ImS16)v32; return r; } case ImGuiDataType_U16: { ImU32 v32 = (ImU32)*(ImU16*)v; bool r = SliderBehaviorT<ImU32, ImS32, float >(bb, id, ImGuiDataType_U32, &v32, *(const ImU16*)v_min, *(const ImU16*)v_max, format, power, flags, out_grab_bb); if (r) *(ImU16*)v = (ImU16)v32; return r; } case ImGuiDataType_S32: IM_ASSERT(*(const ImS32*)v_min >= IM_S32_MIN/2 && *(const ImS32*)v_max <= IM_S32_MAX/2); return SliderBehaviorT<ImS32, ImS32, float >(bb, id, data_type, (ImS32*)v, *(const ImS32*)v_min, *(const ImS32*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_U32: IM_ASSERT(*(const ImU32*)v_min <= IM_U32_MAX/2); return SliderBehaviorT<ImU32, ImS32, float >(bb, id, data_type, (ImU32*)v, *(const ImU32*)v_min, *(const ImU32*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_S64: IM_ASSERT(*(const ImS64*)v_min >= IM_S64_MIN/2 && *(const ImS64*)v_max <= IM_S64_MAX/2); return SliderBehaviorT<ImS64, ImS64, double>(bb, id, data_type, (ImS64*)v, *(const ImS64*)v_min, *(const ImS64*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_U64: IM_ASSERT(*(const ImU64*)v_min <= IM_U64_MAX/2); return SliderBehaviorT<ImU64, ImS64, double>(bb, id, data_type, (ImU64*)v, *(const ImU64*)v_min, *(const ImU64*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_Float: IM_ASSERT(*(const float*)v_min >= -FLT_MAX/2.0f && *(const float*)v_max <= FLT_MAX/2.0f); return SliderBehaviorT<float, float, float >(bb, id, data_type, (float*)v, *(const float*)v_min, *(const float*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_Double: IM_ASSERT(*(const double*)v_min >= -DBL_MAX/2.0f && *(const double*)v_max <= DBL_MAX/2.0f); return SliderBehaviorT<double,double,double>(bb, id, data_type, (double*)v, *(const double*)v_min, *(const double*)v_max, format, power, flags, out_grab_bb); case ImGuiDataType_COUNT: break; } IM_ASSERT(0); return false; } bool ImGui::SliderScalar(const char* label, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f)); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb)) return false; // Default format string when passing NULL // Patch old "%.0f" format string to use "%d", read function comments for more details. IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) format = GDataTypeInfo[data_type].PrintFmt; else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) format = PatchFormatStringFloatToInt(format); // Tabbing or CTRL-clicking on Slider turns it into an input box bool start_text_input = false; const bool focus_requested = FocusableItemRegister(window, id); const bool hovered = ItemHoverable(frame_bb, id); if (focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id)) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down); if (focus_requested || g.IO.KeyCtrl || g.NavInputId == id) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) { window->DC.CursorPos = frame_bb.Min; FocusableItemUnregister(window); return InputScalarAsWidgetReplacement(frame_bb, id, label, data_type, v, format); } // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); // Slider behavior ImRect grab_bb; const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_None, &grab_bb); if (value_changed) MarkItemEdited(id); // Render grab window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format); RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags); return value_changed; } // Add multiple sliders on 1 line for compact edition of multiple components bool ImGui::SliderScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* v_min, const void* v_max, const char* format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { PushID(i); value_changed |= SliderScalar("", data_type, v, v_min, v_max, format, power); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); } PopID(); TextEx(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format, float power) { return SliderScalar(label, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 2, &v_min, &v_max, format, power); } bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 3, &v_min, &v_max, format, power); } bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format, float power) { return SliderScalarN(label, ImGuiDataType_Float, v, 4, &v_min, &v_max, format, power); } bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max, const char* format) { if (format == NULL) format = "%.0f deg"; float v_deg = (*v_rad) * 360.0f / (2*IM_PI); bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, format, 1.0f); *v_rad = v_deg * (2*IM_PI) / 360.0f; return value_changed; } bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* format) { return SliderScalar(label, ImGuiDataType_S32, v, &v_min, &v_max, format); } bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format) { return SliderScalarN(label, ImGuiDataType_S32, v, 2, &v_min, &v_max, format); } bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format) { return SliderScalarN(label, ImGuiDataType_S32, v, 3, &v_min, &v_max, format); } bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format) { return SliderScalarN(label, ImGuiDataType_S32, v, 4, &v_min, &v_max, format); } bool ImGui::VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* v, const void* v_min, const void* v_max, const char* format, float power) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(frame_bb, id)) return false; // Default format string when passing NULL // Patch old "%.0f" format string to use "%d", read function comments for more details. IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) format = GDataTypeInfo[data_type].PrintFmt; else if (data_type == ImGuiDataType_S32 && strcmp(format, "%d") != 0) format = PatchFormatStringFloatToInt(format); const bool hovered = ItemHoverable(frame_bb, id); if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id) { SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); } // Draw frame const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, g.Style.FrameRounding); // Slider behavior ImRect grab_bb; const bool value_changed = SliderBehavior(frame_bb, id, data_type, v, v_min, v_max, format, power, ImGuiSliderFlags_Vertical, &grab_bb); if (value_changed) MarkItemEdited(id); // Render grab window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; const char* value_buf_end = value_buf + DataTypeFormatString(value_buf, IM_ARRAYSIZE(value_buf), data_type, v, format); RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format, float power) { return VSliderScalar(label, size, ImGuiDataType_Float, v, &v_min, &v_max, format, power); } bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format) { return VSliderScalar(label, size, ImGuiDataType_S32, v, &v_min, &v_max, format); } //------------------------------------------------------------------------- // [SECTION] Widgets: InputScalar, InputFloat, InputInt, etc. //------------------------------------------------------------------------- // - ImParseFormatFindStart() [Internal] // - ImParseFormatFindEnd() [Internal] // - ImParseFormatTrimDecorations() [Internal] // - ImParseFormatPrecision() [Internal] // - InputScalarAsWidgetReplacement() [Internal] // - InputScalar() // - InputScalarN() // - InputFloat() // - InputFloat2() // - InputFloat3() // - InputFloat4() // - InputInt() // - InputInt2() // - InputInt3() // - InputInt4() // - InputDouble() //------------------------------------------------------------------------- // We don't use strchr() because our strings are usually very short and often start with '%' const char* ImParseFormatFindStart(const char* fmt) { while (char c = fmt[0]) { if (c == '%' && fmt[1] != '%') return fmt; else if (c == '%') fmt++; fmt++; } return fmt; } const char* ImParseFormatFindEnd(const char* fmt) { // Printf/scanf types modifiers: I/L/h/j/l/t/w/z. Other uppercase letters qualify as types aka end of the format. if (fmt[0] != '%') return fmt; const unsigned int ignored_uppercase_mask = (1 << ('I'-'A')) | (1 << ('L'-'A')); const unsigned int ignored_lowercase_mask = (1 << ('h'-'a')) | (1 << ('j'-'a')) | (1 << ('l'-'a')) | (1 << ('t'-'a')) | (1 << ('w'-'a')) | (1 << ('z'-'a')); for (char c; (c = *fmt) != 0; fmt++) { if (c >= 'A' && c <= 'Z' && ((1 << (c - 'A')) & ignored_uppercase_mask) == 0) return fmt + 1; if (c >= 'a' && c <= 'z' && ((1 << (c - 'a')) & ignored_lowercase_mask) == 0) return fmt + 1; } return fmt; } // Extract the format out of a format string with leading or trailing decorations // fmt = "blah blah" -> return fmt // fmt = "%.3f" -> return fmt // fmt = "hello %.3f" -> return fmt + 6 // fmt = "%.3f hello" -> return buf written with "%.3f" const char* ImParseFormatTrimDecorations(const char* fmt, char* buf, size_t buf_size) { const char* fmt_start = ImParseFormatFindStart(fmt); if (fmt_start[0] != '%') return fmt; const char* fmt_end = ImParseFormatFindEnd(fmt_start); if (fmt_end[0] == 0) // If we only have leading decoration, we don't need to copy the data. return fmt_start; ImStrncpy(buf, fmt_start, ImMin((size_t)(fmt_end - fmt_start) + 1, buf_size)); return buf; } // Parse display precision back from the display format string // FIXME: This is still used by some navigation code path to infer a minimum tweak step, but we should aim to rework widgets so it isn't needed. int ImParseFormatPrecision(const char* fmt, int default_precision) { fmt = ImParseFormatFindStart(fmt); if (fmt[0] != '%') return default_precision; fmt++; while (*fmt >= '0' && *fmt <= '9') fmt++; int precision = INT_MAX; if (*fmt == '.') { fmt = ImAtoi<int>(fmt + 1, &precision); if (precision < 0 || precision > 99) precision = default_precision; } if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation precision = -1; if ((*fmt == 'g' || *fmt == 'G') && precision == INT_MAX) precision = -1; return (precision == INT_MAX) ? default_precision : precision; } // Create text input in place of an active drag/slider (used when doing a CTRL+Click on drag/slider widgets) // FIXME: Facilitate using this in variety of other situations. bool ImGui::InputScalarAsWidgetReplacement(const ImRect& bb, ImGuiID id, const char* label, ImGuiDataType data_type, void* data_ptr, const char* format) { IM_UNUSED(id); ImGuiContext& g = *GImGui; // On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id. // We clear ActiveID on the first frame to allow the InputText() taking it back. if (g.ScalarAsInputTextId == 0) ClearActiveID(); char fmt_buf[32]; char data_buf[32]; format = ImParseFormatTrimDecorations(format, fmt_buf, IM_ARRAYSIZE(fmt_buf)); DataTypeFormatString(data_buf, IM_ARRAYSIZE(data_buf), data_type, data_ptr, format); ImStrTrimBlanks(data_buf); ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll | ((data_type == ImGuiDataType_Float || data_type == ImGuiDataType_Double) ? ImGuiInputTextFlags_CharsScientific : ImGuiInputTextFlags_CharsDecimal); bool value_changed = InputTextEx(label, NULL, data_buf, IM_ARRAYSIZE(data_buf), bb.GetSize(), flags); if (g.ScalarAsInputTextId == 0) { // First frame we started displaying the InputText widget, we expect it to take the active id. IM_ASSERT(g.ActiveId == id); g.ScalarAsInputTextId = g.ActiveId; } if (value_changed) return DataTypeApplyOpFromText(data_buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, NULL); return false; } bool ImGui::InputScalar(const char* label, ImGuiDataType data_type, void* data_ptr, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; IM_ASSERT(data_type >= 0 && data_type < ImGuiDataType_COUNT); if (format == NULL) format = GDataTypeInfo[data_type].PrintFmt; char buf[64]; DataTypeFormatString(buf, IM_ARRAYSIZE(buf), data_type, data_ptr, format); bool value_changed = false; if ((flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0) flags |= ImGuiInputTextFlags_CharsDecimal; flags |= ImGuiInputTextFlags_AutoSelectAll; if (step != NULL) { const float button_size = GetFrameHeight(); BeginGroup(); // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() PushID(label); PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_size + style.ItemInnerSpacing.x) * 2)); if (InputText("", buf, IM_ARRAYSIZE(buf), flags)) // PushId(label) + "" gives us the expected ID from outside point of view value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format); PopItemWidth(); // Step buttons const ImVec2 backup_frame_padding = style.FramePadding; style.FramePadding.x = style.FramePadding.y; ImGuiButtonFlags button_flags = ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups; if (flags & ImGuiInputTextFlags_ReadOnly) button_flags |= ImGuiButtonFlags_Disabled; SameLine(0, style.ItemInnerSpacing.x); if (ButtonEx("-", ImVec2(button_size, button_size), button_flags)) { DataTypeApplyOp(data_type, '-', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step); value_changed = true; } SameLine(0, style.ItemInnerSpacing.x); if (ButtonEx("+", ImVec2(button_size, button_size), button_flags)) { DataTypeApplyOp(data_type, '+', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast ? step_fast : step); value_changed = true; } SameLine(0, style.ItemInnerSpacing.x); TextEx(label, FindRenderedTextEnd(label)); style.FramePadding = backup_frame_padding; PopID(); EndGroup(); } else { if (InputText(label, buf, IM_ARRAYSIZE(buf), flags)) value_changed = DataTypeApplyOpFromText(buf, g.InputTextState.InitialTextA.Data, data_type, data_ptr, format); } return value_changed; } bool ImGui::InputScalarN(const char* label, ImGuiDataType data_type, void* v, int components, const void* step, const void* step_fast, const char* format, ImGuiInputTextFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; bool value_changed = false; BeginGroup(); PushID(label); PushMultiItemsWidths(components); size_t type_size = GDataTypeInfo[data_type].Size; for (int i = 0; i < components; i++) { PushID(i); value_changed |= InputScalar("", data_type, v, step, step_fast, format, flags); SameLine(0, g.Style.ItemInnerSpacing.x); PopID(); PopItemWidth(); v = (void*)((char*)v + type_size); } PopID(); TextEx(label, FindRenderedTextEnd(label)); EndGroup(); return value_changed; } bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, const char* format, ImGuiInputTextFlags flags) { flags |= ImGuiInputTextFlags_CharsScientific; return InputScalar(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), format, flags); } bool ImGui::InputFloat2(const char* label, float v[2], const char* format, ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags); } bool ImGui::InputFloat3(const char* label, float v[3], const char* format, ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags); } bool ImGui::InputFloat4(const char* label, float v[4], const char* format, ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags); } // Prefer using "const char* format" directly, which is more flexible and consistent with other API. #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags flags) { char format[16] = "%f"; if (decimal_precision >= 0) ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); return InputFloat(label, v, step, step_fast, format, flags); } bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags flags) { char format[16] = "%f"; if (decimal_precision >= 0) ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); return InputScalarN(label, ImGuiDataType_Float, v, 2, NULL, NULL, format, flags); } bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags flags) { char format[16] = "%f"; if (decimal_precision >= 0) ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); return InputScalarN(label, ImGuiDataType_Float, v, 3, NULL, NULL, format, flags); } bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags flags) { char format[16] = "%f"; if (decimal_precision >= 0) ImFormatString(format, IM_ARRAYSIZE(format), "%%.%df", decimal_precision); return InputScalarN(label, ImGuiDataType_Float, v, 4, NULL, NULL, format, flags); } #endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags flags) { // Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes. const char* format = (flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d"; return InputScalar(label, ImGuiDataType_S32, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), format, flags); } bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_S32, v, 2, NULL, NULL, "%d", flags); } bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_S32, v, 3, NULL, NULL, "%d", flags); } bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags) { return InputScalarN(label, ImGuiDataType_S32, v, 4, NULL, NULL, "%d", flags); } bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* format, ImGuiInputTextFlags flags) { flags |= ImGuiInputTextFlags_CharsScientific; return InputScalar(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), format, flags); } //------------------------------------------------------------------------- // [SECTION] Widgets: InputText, InputTextMultiline, InputTextWithHint //------------------------------------------------------------------------- // - InputText() // - InputTextWithHint() // - InputTextMultiline() // - InputTextEx() [Internal] //------------------------------------------------------------------------- bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() return InputTextEx(label, NULL, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data); } bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { return InputTextEx(label, NULL, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data); } bool ImGui::InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline() return InputTextEx(label, hint, buf, (int)buf_size, ImVec2(0, 0), flags, callback, user_data); } static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end) { int line_count = 0; const char* s = text_begin; while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding if (c == '\n') line_count++; s--; if (s[0] != '\n' && s[0] != '\r') line_count++; *out_text_end = s; return line_count; } static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line) { ImGuiContext& g = *GImGui; ImFont* font = g.Font; const float line_height = g.FontSize; const float scale = line_height / font->FontSize; ImVec2 text_size = ImVec2(0,0); float line_width = 0.0f; const ImWchar* s = text_begin; while (s < text_end) { unsigned int c = (unsigned int)(*s++); if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; if (stop_on_new_line) break; continue; } if (c == '\r') continue; const float char_width = font->GetCharAdvance((ImWchar)c) * scale; line_width += char_width; } if (text_size.x < line_width) text_size.x = line_width; if (out_offset) *out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n text_size.y += line_height; if (remaining) *remaining = s; return text_size; } // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) namespace ImStb { static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->TextW[idx]; } static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->TextW[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) { const ImWchar* text = obj->TextW.Data; const ImWchar* text_remaining = NULL; const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; r->ymin = 0.0f; r->ymax = size.y; r->num_chars = (int)(text_remaining - (text + line_start_idx)); } static bool is_separator(unsigned int c) { return ImCharIsBlankW(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->TextW[idx-1] ) && !is_separator( obj->TextW[idx] ) ) : 1; } static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; } #ifdef __APPLE__ // FIXME: Move setting to IO structure static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->TextW[idx-1] ) && is_separator( obj->TextW[idx] ) ) : 1; } static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; } #else static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; } #endif #define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h #define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) { ImWchar* dst = obj->TextW.Data + pos; // We maintain our buffer length in both UTF-8 and wchar formats obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; // Offset remaining text (FIXME-OPT: Use memmove) const ImWchar* src = obj->TextW.Data + pos + n; while (ImWchar c = *src++) *dst++ = c; *dst = '\0'; } static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) { const bool is_resizable = (obj->UserFlags & ImGuiInputTextFlags_CallbackResize) != 0; const int text_len = obj->CurLenW; IM_ASSERT(pos <= text_len); const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); if (!is_resizable && (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufCapacityA)) return false; // Grow internal buffer if needed if (new_text_len + text_len + 1 > obj->TextW.Size) { if (!is_resizable) return false; IM_ASSERT(text_len < obj->TextW.Size); obj->TextW.resize(text_len + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1); } ImWchar* text = obj->TextW.Data; if (pos != text_len) memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar)); memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; obj->TextW[obj->CurLenW] = '\0'; return true; } // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word #define STB_TEXTEDIT_K_SHIFT 0x20000 #define STB_TEXTEDIT_IMPLEMENTATION #include "imstb_textedit.h" } void ImGuiInputTextState::OnKeyPressed(int key) { stb_textedit_key(this, &Stb, key); CursorFollow = true; CursorAnimReset(); } ImGuiInputTextCallbackData::ImGuiInputTextCallbackData() { memset(this, 0, sizeof(*this)); } // Public API to manipulate UTF-8 text // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) // FIXME: The existence of this rarely exercised code path is a bit of a nuisance. void ImGuiInputTextCallbackData::DeleteChars(int pos, int bytes_count) { IM_ASSERT(pos + bytes_count <= BufTextLen); char* dst = Buf + pos; const char* src = Buf + pos + bytes_count; while (char c = *src++) *dst++ = c; *dst = '\0'; if (CursorPos + bytes_count >= pos) CursorPos -= bytes_count; else if (CursorPos >= pos) CursorPos = pos; SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen -= bytes_count; } void ImGuiInputTextCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) { const bool is_resizable = (Flags & ImGuiInputTextFlags_CallbackResize) != 0; const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text); if (new_text_len + BufTextLen >= BufSize) { if (!is_resizable) return; // Contrary to STB_TEXTEDIT_INSERTCHARS() this is working in the UTF8 buffer, hence the midly similar code (until we remove the U16 buffer alltogether!) ImGuiContext& g = *GImGui; ImGuiInputTextState* edit_state = &g.InputTextState; IM_ASSERT(edit_state->ID != 0 && g.ActiveId == edit_state->ID); IM_ASSERT(Buf == edit_state->TextA.Data); int new_buf_size = BufTextLen + ImClamp(new_text_len * 4, 32, ImMax(256, new_text_len)) + 1; edit_state->TextA.reserve(new_buf_size + 1); Buf = edit_state->TextA.Data; BufSize = edit_state->BufCapacityA = new_buf_size; } if (BufTextLen != pos) memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos)); memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char)); Buf[BufTextLen + new_text_len] = '\0'; if (CursorPos >= pos) CursorPos += new_text_len; SelectionStart = SelectionEnd = CursorPos; BufDirty = true; BufTextLen += new_text_len; } // Return false to discard a character. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* user_data) { unsigned int c = *p_char; if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) { bool pass = false; pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline)); pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput)); if (!pass) return false; } if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. return false; if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific)) { if (flags & ImGuiInputTextFlags_CharsDecimal) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; if (flags & ImGuiInputTextFlags_CharsScientific) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E')) return false; if (flags & ImGuiInputTextFlags_CharsHexadecimal) if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return false; if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') *p_char = (c += (unsigned int)('A'-'a')); if (flags & ImGuiInputTextFlags_CharsNoBlank) if (ImCharIsBlankW(c)) return false; } if (flags & ImGuiInputTextFlags_CallbackCharFilter) { ImGuiInputTextCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData)); callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; callback_data.Flags = flags; callback_data.UserData = user_data; if (callback(&callback_data) != 0) return false; *p_char = callback_data.EventChar; if (!callback_data.EventChar) return false; } return true; } // Edit a string of text // - buf_size account for the zero-terminator, so a buf_size of 6 can hold "Hello" but not "Hello!". // This is so we can easily call InputText() on static arrays using ARRAYSIZE() and to match // Note that in std::string world, capacity() would omit 1 byte used by the zero-terminator. // - When active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while the InputText is active has no effect. // - If you want to use ImGui::InputText() with std::string, see misc/cpp/imgui_stdlib.h // (FIXME: Rather confusing and messy function, among the worse part of our codebase, expecting to rewrite a V2 at some point.. Partly because we are // doing UTF8 > U16 > UTF8 conversions on the go to easily interface with stb_textedit. Ideally should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188) bool ImGui::InputTextEx(const char* label, const char* hint, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* callback_user_data) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys) IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key) ImGuiContext& g = *GImGui; ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; const bool RENDER_SELECTION_WHEN_INACTIVE = false; const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0; const bool is_readonly = (flags & ImGuiInputTextFlags_ReadOnly) != 0; const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0; const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0; const bool is_resizable = (flags & ImGuiInputTextFlags_CallbackResize) != 0; if (is_resizable) IM_ASSERT(callback != NULL); // Must provide a callback if you set the ImGuiInputTextFlags_CallbackResize flag! if (is_multiline) // Open group before calling GetID() because groups tracks id created within their scope, BeginGroup(); const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); ImGuiWindow* draw_window = window; if (is_multiline) { if (!ItemAdd(total_bb, id, &frame_bb)) { ItemSize(total_bb, style.FramePadding.y); EndGroup(); return false; } if (!BeginChildFrame(id, frame_bb.GetSize())) { EndChildFrame(); EndGroup(); return false; } draw_window = GetCurrentWindow(); draw_window->DC.NavLayerActiveMaskNext |= draw_window->DC.NavLayerCurrentMask; // This is to ensure that EndChild() will display a navigation highlight size.x -= draw_window->ScrollbarSizes.x; } else { ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, id, &frame_bb)) return false; } const bool hovered = ItemHoverable(frame_bb, id); if (hovered) g.MouseCursor = ImGuiMouseCursor_TextInput; // NB: we are only allowed to access 'edit_state' if we are the active widget. ImGuiInputTextState* state = NULL; if (g.InputTextState.ID == id) state = &g.InputTextState; const bool focus_requested = FocusableItemRegister(window, id); const bool focus_requested_by_code = focus_requested && (g.FocusRequestCurrWindow == window && g.FocusRequestCurrCounterAll == window->DC.FocusCounterAll); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool user_clicked = hovered && io.MouseClicked[0]; const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard)); const bool user_scroll_finish = is_multiline && state != NULL && g.ActiveId == 0 && g.ActiveIdPreviousFrame == GetScrollbarID(draw_window, ImGuiAxis_Y); const bool user_scroll_active = is_multiline && state != NULL && g.ActiveId == GetScrollbarID(draw_window, ImGuiAxis_Y); bool clear_active_id = false; bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline); const bool init_make_active = (focus_requested || user_clicked || user_scroll_finish || user_nav_input_start); const bool init_state = (init_make_active || user_scroll_active); if (init_state && g.ActiveId != id) { // Access state even if we don't own it yet. state = &g.InputTextState; state->CursorAnimReset(); // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) // From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode) const int buf_len = (int)strlen(buf); state->InitialTextA.resize(buf_len + 1); // UTF-8. we use +1 to make sure that .Data is always pointing to at least an empty string. memcpy(state->InitialTextA.Data, buf, buf_len + 1); // Start edition const char* buf_end = NULL; state->TextW.resize(buf_size + 1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data is always pointing to at least an empty string. state->TextA.resize(0); state->TextAIsValid = false; // TextA is not valid yet (we will display buf until then) state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, buf_size, buf, NULL, &buf_end); state->CurLenA = (int)(buf_end - buf); // We can't get the result from ImStrncpy() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. // Preserve cursor position and undo/redo stack if we come back to same widget // FIXME: For non-readonly widgets we might be able to require that TextAIsValid && TextA == buf ? (untested) and discard undo stack if user buffer has changed. const bool recycle_state = (state->ID == id); if (recycle_state) { // Recycle existing cursor/selection/undo stack but clamp position // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. state->CursorClamp(); } else { state->ID = id; state->ScrollX = 0.0f; stb_textedit_initialize_state(&state->Stb, !is_multiline); if (!is_multiline && focus_requested_by_code) select_all = true; } if (flags & ImGuiInputTextFlags_AlwaysInsertMode) state->Stb.insert_mode = 1; if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl))) select_all = true; } if (g.ActiveId != id && init_make_active) { IM_ASSERT(state && state->ID == id); SetActiveID(id, window); SetFocusID(id, window); FocusWindow(window); IM_ASSERT(ImGuiNavInput_COUNT < 32); g.ActiveIdBlockNavInputFlags = (1 << ImGuiNavInput_Cancel); if (flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_AllowTabInput)) // Disable keyboard tabbing out g.ActiveIdBlockNavInputFlags |= (1 << ImGuiNavInput_KeyTab_); if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory)) g.ActiveIdAllowNavDirFlags = ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down)); } // We have an edge case if ActiveId was set through another widget (e.g. widget being swapped), clear id immediately (don't wait until the end of the function) if (g.ActiveId == id && state == NULL) ClearActiveID(); // Release focus when we click outside if (g.ActiveId == id && io.MouseClicked[0] && !init_state && !init_make_active) //-V560 clear_active_id = true; // When read-only we always use the live data passed to the function // FIXME-OPT: Because our selection/cursor code currently needs the wide text we need to convert it when active, which is not ideal :( if (is_readonly && state != NULL) { const bool will_render_cursor = (g.ActiveId == id) || (user_scroll_active); const bool will_render_selection = state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || will_render_cursor); if (will_render_cursor || will_render_selection) { const char* buf_end = NULL; state->TextW.resize(buf_size + 1); state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, buf, NULL, &buf_end); state->CurLenA = (int)(buf_end - buf); state->CursorClamp(); } } // Lock the decision of whether we are going to take the path displaying the cursor or selection const bool render_cursor = (g.ActiveId == id) || (state && user_scroll_active); const bool render_selection = state && state->HasSelection() && (RENDER_SELECTION_WHEN_INACTIVE || render_cursor); bool value_changed = false; bool enter_pressed = false; // Select the buffer to render. const bool buf_display_from_state = (render_cursor || render_selection || g.ActiveId == id) && !is_readonly && state && state->TextAIsValid; const bool is_displaying_hint = (hint != NULL && (buf_display_from_state ? state->TextA.Data : buf)[0] == 0); // Password pushes a temporary font with only a fallback glyph if (is_password && !is_displaying_hint) { const ImFontGlyph* glyph = g.Font->FindGlyph('*'); ImFont* password_font = &g.InputTextPasswordFont; password_font->FontSize = g.Font->FontSize; password_font->Scale = g.Font->Scale; password_font->DisplayOffset = g.Font->DisplayOffset; password_font->Ascent = g.Font->Ascent; password_font->Descent = g.Font->Descent; password_font->ContainerAtlas = g.Font->ContainerAtlas; password_font->FallbackGlyph = glyph; password_font->FallbackAdvanceX = glyph->AdvanceX; IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty()); PushFont(password_font); } // Process mouse inputs and character inputs int backup_current_text_length = 0; if (g.ActiveId == id) { IM_ASSERT(state != NULL); backup_current_text_length = state->CurLenA; state->BufCapacityA = buf_size; state->UserFlags = flags; state->UserCallback = callback; state->UserCallbackData = callback_user_data; // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. // Down the line we should have a cleaner library-wide concept of Selected vs Active. g.ActiveIdAllowOverlap = !io.MouseDown[0]; g.WantTextInputNextFrame = 1; // Edit in progress const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + state->ScrollX; const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f)); const bool is_osx = io.ConfigMacOSXBehaviors; if (select_all || (hovered && !is_osx && io.MouseDoubleClicked[0])) { state->SelectAll(); state->SelectedAllMouseLock = true; } else if (hovered && is_osx && io.MouseDoubleClicked[0]) { // Double-click select a word only, OS X style (by simulating keystrokes) state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT); state->OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT); } else if (io.MouseClicked[0] && !state->SelectedAllMouseLock) { if (hovered) { stb_textedit_click(state, &state->Stb, mouse_x, mouse_y); state->CursorAnimReset(); } } else if (io.MouseDown[0] && !state->SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) { stb_textedit_drag(state, &state->Stb, mouse_x, mouse_y); state->CursorAnimReset(); state->CursorFollow = true; } if (state->SelectedAllMouseLock && !io.MouseDown[0]) state->SelectedAllMouseLock = false; if (io.InputQueueCharacters.Size > 0) { // Process text input (before we check for Return because using some IME will effectively send a Return?) // We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters. bool ignore_inputs = (io.KeyCtrl && !io.KeyAlt) || (is_osx && io.KeySuper); if (!ignore_inputs && !is_readonly && !user_nav_input_start) for (int n = 0; n < io.InputQueueCharacters.Size; n++) { // Insert character if they pass filtering unsigned int c = (unsigned int)io.InputQueueCharacters[n]; if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) state->OnKeyPressed((int)c); } // Consume characters io.InputQueueCharacters.resize(0); } } // Process other shortcuts/key-presses bool cancel_edit = false; if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id) { IM_ASSERT(state != NULL); const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0); const bool is_osx = io.ConfigMacOSXBehaviors; const bool is_shortcut_key = (is_osx ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl const bool is_osx_shift_shortcut = is_osx && io.KeySuper && io.KeyShift && !io.KeyCtrl && !io.KeyAlt; const bool is_wordmove_key_down = is_osx ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl const bool is_startend_key_down = is_osx && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper; const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper; const bool is_cut = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && !is_readonly && !is_password && (!is_multiline || state->HasSelection()); const bool is_copy = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || state->HasSelection()); const bool is_paste = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_readonly; const bool is_undo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Z)) && !is_readonly && is_undoable); const bool is_redo = ((is_shortcut_key && IsKeyPressedMap(ImGuiKey_Y)) || (is_osx_shift_shortcut && IsKeyPressedMap(ImGuiKey_Z))) && !is_readonly && is_undoable; if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else state->OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Home)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } else if (IsKeyPressedMap(ImGuiKey_End)) { state->OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Delete) && !is_readonly) { state->OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Backspace) && !is_readonly) { if (!state->HasSelection()) { if (is_wordmove_key_down) state->OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT); else if (is_osx && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) state->OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT); } state->OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Enter)) { bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0; if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl)) { enter_pressed = clear_active_id = true; } else if (!is_readonly) { unsigned int c = '\n'; // Insert new line if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) state->OnKeyPressed((int)c); } } else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !is_readonly) { unsigned int c = '\t'; // Insert TAB if (InputTextFilterCharacter(&c, flags, callback, callback_user_data)) state->OnKeyPressed((int)c); } else if (IsKeyPressedMap(ImGuiKey_Escape)) { clear_active_id = cancel_edit = true; } else if (is_undo || is_redo) { state->OnKeyPressed(is_undo ? STB_TEXTEDIT_K_UNDO : STB_TEXTEDIT_K_REDO); state->ClearSelection(); } else if (is_shortcut_key && IsKeyPressedMap(ImGuiKey_A)) { state->SelectAll(); state->CursorFollow = true; } else if (is_cut || is_copy) { // Cut, Copy if (io.SetClipboardTextFn) { const int ib = state->HasSelection() ? ImMin(state->Stb.select_start, state->Stb.select_end) : 0; const int ie = state->HasSelection() ? ImMax(state->Stb.select_start, state->Stb.select_end) : state->CurLenW; const int clipboard_data_len = ImTextCountUtf8BytesFromStr(state->TextW.Data + ib, state->TextW.Data + ie) + 1; char* clipboard_data = (char*)MemAlloc(clipboard_data_len * sizeof(char)); ImTextStrToUtf8(clipboard_data, clipboard_data_len, state->TextW.Data + ib, state->TextW.Data + ie); SetClipboardText(clipboard_data); MemFree(clipboard_data); } if (is_cut) { if (!state->HasSelection()) state->SelectAll(); state->CursorFollow = true; stb_textedit_cut(state, &state->Stb); } } else if (is_paste) { if (const char* clipboard = GetClipboardText()) { // Filter pasted buffer const int clipboard_len = (int)strlen(clipboard); ImWchar* clipboard_filtered = (ImWchar*)MemAlloc((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) { unsigned int c; s += ImTextCharFromUtf8(&c, s, NULL); if (c == 0) break; if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, callback_user_data)) continue; clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; } clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation { stb_textedit_paste(state, &state->Stb, clipboard_filtered, clipboard_filtered_len); state->CursorFollow = true; } MemFree(clipboard_filtered); } } } // Process callbacks and apply result back to user's buffer. if (g.ActiveId == id) { IM_ASSERT(state != NULL); const char* apply_new_text = NULL; int apply_new_text_length = 0; if (cancel_edit) { // Restore initial value. Only return true if restoring to the initial value changes the current buffer contents. if (!is_readonly && strcmp(buf, state->InitialTextA.Data) != 0) { apply_new_text = state->InitialTextA.Data; apply_new_text_length = state->InitialTextA.Size - 1; } } // When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame. // If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage. bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0); if (apply_edit_back_to_user_buffer) { // Apply new value immediately - copy modified buffer back // Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer // FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect. // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks. if (!is_readonly) { state->TextAIsValid = true; state->TextA.resize(state->TextW.Size * 4 + 1); ImTextStrToUtf8(state->TextA.Data, state->TextA.Size, state->TextW.Data, NULL); } // User callback if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) { IM_ASSERT(callback != NULL); // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. ImGuiInputTextFlags event_flag = 0; ImGuiKey event_key = ImGuiKey_COUNT; if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) { event_flag = ImGuiInputTextFlags_CallbackCompletion; event_key = ImGuiKey_Tab; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_UpArrow; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } else if (flags & ImGuiInputTextFlags_CallbackAlways) event_flag = ImGuiInputTextFlags_CallbackAlways; if (event_flag) { ImGuiInputTextCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiInputTextCallbackData)); callback_data.EventFlag = event_flag; callback_data.Flags = flags; callback_data.UserData = callback_user_data; callback_data.EventKey = event_key; callback_data.Buf = state->TextA.Data; callback_data.BufTextLen = state->CurLenA; callback_data.BufSize = state->BufCapacityA; callback_data.BufDirty = false; // We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188) ImWchar* text = state->TextW.Data; const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + state->Stb.cursor); const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_start); const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + state->Stb.select_end); // Call user code callback(&callback_data); // Read back what user may have modified IM_ASSERT(callback_data.Buf == state->TextA.Data); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == state->BufCapacityA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) { state->Stb.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); state->CursorFollow = true; } if (callback_data.SelectionStart != utf8_selection_start) { state->Stb.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); } if (callback_data.SelectionEnd != utf8_selection_end) { state->Stb.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); } if (callback_data.BufDirty) { IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text! if (callback_data.BufTextLen > backup_current_text_length && is_resizable) state->TextW.resize(state->TextW.Size + (callback_data.BufTextLen - backup_current_text_length)); state->CurLenW = ImTextStrFromUtf8(state->TextW.Data, state->TextW.Size, callback_data.Buf, NULL); state->CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen() state->CursorAnimReset(); } } } // Will copy result string if modified if (!is_readonly && strcmp(state->TextA.Data, buf) != 0) { apply_new_text = state->TextA.Data; apply_new_text_length = state->CurLenA; } } // Copy result to user buffer if (apply_new_text) { IM_ASSERT(apply_new_text_length >= 0); if (backup_current_text_length != apply_new_text_length && is_resizable) { ImGuiInputTextCallbackData callback_data; callback_data.EventFlag = ImGuiInputTextFlags_CallbackResize; callback_data.Flags = flags; callback_data.Buf = buf; callback_data.BufTextLen = apply_new_text_length; callback_data.BufSize = ImMax(buf_size, apply_new_text_length + 1); callback_data.UserData = callback_user_data; callback(&callback_data); buf = callback_data.Buf; buf_size = callback_data.BufSize; apply_new_text_length = ImMin(callback_data.BufTextLen, buf_size - 1); IM_ASSERT(apply_new_text_length <= buf_size); } // If the underlying buffer resize was denied or not carried to the next frame, apply_new_text_length+1 may be >= buf_size. ImStrncpy(buf, apply_new_text, ImMin(apply_new_text_length + 1, buf_size)); value_changed = true; } // Clear temporary user storage state->UserFlags = 0; state->UserCallback = NULL; state->UserCallbackData = NULL; } // Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value) if (clear_active_id && g.ActiveId == id) ClearActiveID(); // Render frame if (!is_multiline) { RenderNavHighlight(frame_bb, id); RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); } const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size ImVec2 draw_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding; ImVec2 text_size(0.0f, 0.0f); // Set upper limit of single-line InputTextEx() at 2 million characters strings. The current pathological worst case is a long line // without any carriage return, which would makes ImFont::RenderText() reserve too many vertices and probably crash. Avoid it altogether. // Note that we only use this limit on single-line InputText(), so a pathologically large line on a InputTextMultiline() would still crash. const int buf_display_max_length = 2 * 1024 * 1024; const char* buf_display = buf_display_from_state ? state->TextA.Data : buf; //-V595 const char* buf_display_end = NULL; // We have specialized paths below for setting the length if (is_displaying_hint) { buf_display = hint; buf_display_end = hint + strlen(hint); } // Render text. We currently only render selection when the widget is active or while scrolling. // FIXME: We could remove the '&& render_cursor' to keep rendering selection when inactive. if (render_cursor || render_selection) { IM_ASSERT(state != NULL); if (!is_displaying_hint) buf_display_end = buf_display + state->CurLenA; // Render text (with cursor and selection) // This is going to be messy. We need to: // - Display the text (this alone can be more easily clipped) // - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation) // - Measure text height (for scrollbar) // We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort) // FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8. const ImWchar* text_begin = state->TextW.Data; ImVec2 cursor_offset, select_start_offset; { // Find lines numbers straddling 'cursor' (slot 0) and 'select_start' (slot 1) positions. const ImWchar* searches_input_ptr[2] = { NULL, NULL }; int searches_result_line_no[2] = { -1000, -1000 }; int searches_remaining = 0; if (render_cursor) { searches_input_ptr[0] = text_begin + state->Stb.cursor; searches_result_line_no[0] = -1; searches_remaining++; } if (render_selection) { searches_input_ptr[1] = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); searches_result_line_no[1] = -1; searches_remaining++; } // Iterate all lines to find our line numbers // In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter. searches_remaining += is_multiline ? 1 : 0; int line_count = 0; //for (const ImWchar* s = text_begin; (s = (const ImWchar*)wcschr((const wchar_t*)s, (wchar_t)'\n')) != NULL; s++) // FIXME-OPT: Could use this when wchar_t are 16-bits for (const ImWchar* s = text_begin; *s != 0; s++) if (*s == '\n') { line_count++; if (searches_result_line_no[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_no[0] = line_count; if (--searches_remaining <= 0) break; } if (searches_result_line_no[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_no[1] = line_count; if (--searches_remaining <= 0) break; } } line_count++; if (searches_result_line_no[0] == -1) searches_result_line_no[0] = line_count; if (searches_result_line_no[1] == -1) searches_result_line_no[1] = line_count; // Calculate 2d position by finding the beginning of the line and measuring distance cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x; cursor_offset.y = searches_result_line_no[0] * g.FontSize; if (searches_result_line_no[1] >= 0) { select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x; select_start_offset.y = searches_result_line_no[1] * g.FontSize; } // Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224) if (is_multiline) text_size = ImVec2(size.x, line_count * g.FontSize); } // Scroll if (render_cursor && state->CursorFollow) { // Horizontal scroll in chunks of quarter width if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll)) { const float scroll_increment_x = size.x * 0.25f; if (cursor_offset.x < state->ScrollX) state->ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x); else if (cursor_offset.x - size.x >= state->ScrollX) state->ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x); } else { state->ScrollX = 0.0f; } // Vertical scroll if (is_multiline) { float scroll_y = draw_window->Scroll.y; if (cursor_offset.y - g.FontSize < scroll_y) scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize); else if (cursor_offset.y - size.y >= scroll_y) scroll_y = cursor_offset.y - size.y; draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // Manipulate cursor pos immediately avoid a frame of lag draw_window->Scroll.y = scroll_y; draw_pos.y = draw_window->DC.CursorPos.y; } state->CursorFollow = false; } // Draw selection const ImVec2 draw_scroll = ImVec2(state->ScrollX, 0.0f); if (render_selection) { const ImWchar* text_selected_begin = text_begin + ImMin(state->Stb.select_start, state->Stb.select_end); const ImWchar* text_selected_end = text_begin + ImMax(state->Stb.select_start, state->Stb.select_end); ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg, render_cursor ? 1.0f : 0.6f); // FIXME: current code flow mandate that render_cursor is always true here, we are leaving the transparent one for tests. float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection. float bg_offy_dn = is_multiline ? 0.0f : 2.0f; ImVec2 rect_pos = draw_pos + select_start_offset - draw_scroll; for (const ImWchar* p = text_selected_begin; p < text_selected_end; ) { if (rect_pos.y > clip_rect.w + g.FontSize) break; if (rect_pos.y < clip_rect.y) { //p = (const ImWchar*)wmemchr((const wchar_t*)p, '\n', text_selected_end - p); // FIXME-OPT: Could use this when wchar_t are 16-bits //p = p ? p + 1 : text_selected_end; while (p < text_selected_end) if (*p++ == '\n') break; } else { ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true); if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((ImWchar)' ') * 0.50f); // So we can see selected empty lines ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn)); rect.ClipWith(clip_rect); if (rect.Overlaps(clip_rect)) draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color); } rect_pos.x = draw_pos.x - draw_scroll.x; rect_pos.y += g.FontSize; } } // We test for 'buf_display_max_length' as a way to avoid some pathological cases (e.g. single-line 1 MB string) which would make ImDrawList crash. if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos - draw_scroll, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); } // Draw blinking cursor if (render_cursor) { state->CursorAnim += io.DeltaTime; bool cursor_is_visible = (!g.IO.ConfigInputTextCursorBlink) || (state->CursorAnim <= 0.0f) || ImFmod(state->CursorAnim, 1.20f) <= 0.80f; ImVec2 cursor_screen_pos = draw_pos + cursor_offset - draw_scroll; ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y - g.FontSize + 0.5f, cursor_screen_pos.x + 1.0f, cursor_screen_pos.y - 1.5f); if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect)) draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text)); // Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.) if (!is_readonly) g.PlatformImePos = ImVec2(cursor_screen_pos.x - 1.0f, cursor_screen_pos.y - g.FontSize); } } else { // Render text only (no selection, no cursor) if (is_multiline) text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_display_end) * g.FontSize); // We don't need width else if (!is_displaying_hint && g.ActiveId == id) buf_display_end = buf_display + state->CurLenA; else if (!is_displaying_hint) buf_display_end = buf_display + strlen(buf_display); if (is_multiline || (buf_display_end - buf_display) < buf_display_max_length) { ImU32 col = GetColorU32(is_displaying_hint ? ImGuiCol_TextDisabled : ImGuiCol_Text); draw_window->DrawList->AddText(g.Font, g.FontSize, draw_pos, col, buf_display, buf_display_end, 0.0f, is_multiline ? NULL : &clip_rect); } } if (is_multiline) { Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line EndChildFrame(); EndGroup(); } if (is_password && !is_displaying_hint) PopFont(); // Log as text if (g.LogEnabled && !(is_password && !is_displaying_hint)) LogRenderedText(&draw_pos, buf_display, buf_display_end); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if (value_changed) MarkItemEdited(id); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags); if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) return enter_pressed; else return value_changed; } //------------------------------------------------------------------------- // [SECTION] Widgets: ColorEdit, ColorPicker, ColorButton, etc. //------------------------------------------------------------------------- // - ColorEdit3() // - ColorEdit4() // - ColorPicker3() // - RenderColorRectWithAlphaCheckerboard() [Internal] // - ColorPicker4() // - ColorButton() // - SetColorEditOptions() // - ColorTooltip() [Internal] // - ColorEditOptionsPopup() [Internal] // - ColorPickerOptionsPopup() [Internal] //------------------------------------------------------------------------- bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags) { return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha); } // Edit colors components (each component in 0.0f..1.0f range). // See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. // With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const float square_sz = GetFrameHeight(); const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x); const float w_items_all = CalcItemWidth() - w_extra; const char* label_display_end = FindRenderedTextEnd(label); BeginGroup(); PushID(label); // If we're not showing any slider there's no point in doing any HSV conversions const ImGuiColorEditFlags flags_untouched = flags; if (flags & ImGuiColorEditFlags_NoInputs) flags = (flags & (~ImGuiColorEditFlags__DisplayMask)) | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_NoOptions; // Context menu: display and modify options (before defaults are applied) if (!(flags & ImGuiColorEditFlags_NoOptions)) ColorEditOptionsPopup(col, flags); // Read stored options if (!(flags & ImGuiColorEditFlags__DisplayMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DisplayMask); if (!(flags & ImGuiColorEditFlags__DataTypeMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask); if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask); if (!(flags & ImGuiColorEditFlags__InputMask)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputMask); flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__DisplayMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask)); IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check that only 1 is selected IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0; const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0; const int components = alpha ? 4 : 3; // Convert to the formats we need float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f }; if ((flags & ImGuiColorEditFlags_InputHSV) && (flags & ImGuiColorEditFlags_DisplayRGB)) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); else if ((flags & ImGuiColorEditFlags_InputRGB) && (flags & ImGuiColorEditFlags_DisplayHSV)) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) }; bool value_changed = false; bool value_changed_as_float = false; if ((flags & (ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_DisplayHSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB/HSV 0..255 Sliders const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x); static const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; static const char* fmt_table_int[3][4] = { { "%3d", "%3d", "%3d", "%3d" }, // Short display { "R:%3d", "G:%3d", "B:%3d", "A:%3d" }, // Long display for RGBA { "H:%3d", "S:%3d", "V:%3d", "A:%3d" } // Long display for HSVA }; static const char* fmt_table_float[3][4] = { { "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display { "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA { "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA }; const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_DisplayHSV) ? 2 : 1; PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) SameLine(0, style.ItemInnerSpacing.x); if (n + 1 == components) PushItemWidth(w_item_last); if (flags & ImGuiColorEditFlags_Float) { value_changed |= DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]); value_changed_as_float |= value_changed; } else { value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); } PopItemWidth(); PopItemWidth(); } else if ((flags & ImGuiColorEditFlags_DisplayHex) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0) { // RGB Hexadecimal Input char buf[64]; if (alpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255)); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255)); PushItemWidth(w_items_all); if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase)) { value_changed = true; char* p = buf; while (*p == '#' || ImCharIsBlankA(*p)) p++; i[0] = i[1] = i[2] = i[3] = 0; if (alpha) sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned) else sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); PopItemWidth(); } ImGuiWindow* picker_active_window = NULL; if (!(flags & ImGuiColorEditFlags_NoSmallPreview)) { if (!(flags & ImGuiColorEditFlags_NoInputs)) SameLine(0, style.ItemInnerSpacing.x); const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f); if (ColorButton("##ColorButton", col_v4, flags)) { if (!(flags & ImGuiColorEditFlags_NoPicker)) { // Store current color and open a picker g.ColorPickerRef = col_v4; OpenPopup("picker"); SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y)); } } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); if (BeginPopup("picker")) { picker_active_window = g.CurrentWindow; if (label != label_display_end) { TextEx(label, label_display_end); Spacing(); } ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar; ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf; PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes? value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x); PopItemWidth(); EndPopup(); } } if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel)) { SameLine(0, style.ItemInnerSpacing.x); TextEx(label, label_display_end); } // Convert back if (value_changed && picker_active_window == NULL) { if (!value_changed_as_float) for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if ((flags & ImGuiColorEditFlags_DisplayHSV) && (flags & ImGuiColorEditFlags_InputRGB)) ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if ((flags & ImGuiColorEditFlags_DisplayRGB) && (flags & ImGuiColorEditFlags_InputHSV)) ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); col[0] = f[0]; col[1] = f[1]; col[2] = f[2]; if (alpha) col[3] = f[3]; } PopID(); EndGroup(); // Drag and Drop Target // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test. if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropTarget()) { bool accepted_drag_drop = false; if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F)) { memcpy((float*)col, payload->Data, sizeof(float) * 3); // Preserve alpha if any //-V512 value_changed = accepted_drag_drop = true; } if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F)) { memcpy((float*)col, payload->Data, sizeof(float) * components); value_changed = accepted_drag_drop = true; } // Drag-drop payloads are always RGB if (accepted_drag_drop && (flags & ImGuiColorEditFlags_InputHSV)) ColorConvertRGBtoHSV(col[0], col[1], col[2], col[0], col[1], col[2]); EndDragDropTarget(); } // When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4(). if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window) window->DC.LastItemId = g.ActiveId; if (value_changed) MarkItemEdited(window->DC.LastItemId); return value_changed; } bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags) { float col4[4] = { col[0], col[1], col[2], 1.0f }; if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha)) return false; col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; return true; } static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b) { float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f; int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t); int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t); int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t); return IM_COL32(r, g, b, 0xFF); } // Helper for ColorPicker4() // NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that. // I spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding alltogether. void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags) { ImGuiWindow* window = GetCurrentWindow(); if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF) { ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col)); ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col)); window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_flags); int yi = 0; for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++) { float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y); if (y2 <= y1) continue; for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f) { float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x); if (x2 <= x1) continue; int rounding_corners_flags_cell = 0; if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; } if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; } rounding_corners_flags_cell &= rounding_corners_flags; window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell); } } } else { window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags); } } // Helper for ColorPicker4() static void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w) { ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK); ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE); ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK); ImGui::RenderArrowPointingAt(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE); } // Note: ColorPicker4() only accesses 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. // (In C++ the 'float col[4]' notation for a function argument is equivalent to 'float* col', we only specify a size to facilitate understanding of the code.) // FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..) bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col) { ImGuiContext& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImDrawList* draw_list = window->DrawList; ImGuiStyle& style = g.Style; ImGuiIO& io = g.IO; PushID(label); BeginGroup(); if (!(flags & ImGuiColorEditFlags_NoSidePreview)) flags |= ImGuiColorEditFlags_NoSmallPreview; // Context menu: display and store options. if (!(flags & ImGuiColorEditFlags_NoOptions)) ColorPickerOptionsPopup(col, flags); // Read stored options if (!(flags & ImGuiColorEditFlags__PickerMask)) flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask; if (!(flags & ImGuiColorEditFlags__InputMask)) flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__InputMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__InputMask; IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check that only 1 is selected IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check that only 1 is selected if (!(flags & ImGuiColorEditFlags_NoOptions)) flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar); // Setup int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4; bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha); ImVec2 picker_pos = window->DC.CursorPos; float square_sz = GetFrameHeight(); float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x; float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x; float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f); float backup_initial_col[4]; memcpy(backup_initial_col, col, components * sizeof(float)); float wheel_thickness = sv_picker_size * 0.08f; float wheel_r_outer = sv_picker_size * 0.50f; float wheel_r_inner = wheel_r_outer - wheel_thickness; ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f); // Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic. float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f); ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point. ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point. ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point. float H = col[0], S = col[1], V = col[2]; float R = col[0], G = col[1], B = col[2]; if (flags & ImGuiColorEditFlags_InputRGB) ColorConvertRGBtoHSV(R, G, B, H, S, V); else if (flags & ImGuiColorEditFlags_InputHSV) ColorConvertHSVtoRGB(H, S, V, R, G, B); bool value_changed = false, value_changed_h = false, value_changed_sv = false; PushItemFlag(ImGuiItemFlags_NoNav, true); if (flags & ImGuiColorEditFlags_PickerHueWheel) { // Hue wheel + SV triangle logic InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size)); if (IsItemActive()) { ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center; ImVec2 current_off = g.IO.MousePos - wheel_center; float initial_dist2 = ImLengthSqr(initial_off); if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1)) { // Interactive with Hue wheel H = ImAtan2(current_off.y, current_off.x) / IM_PI*0.5f; if (H < 0.0f) H += 1.0f; value_changed = value_changed_h = true; } float cos_hue_angle = ImCos(-H * 2.0f * IM_PI); float sin_hue_angle = ImSin(-H * 2.0f * IM_PI); if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle))) { // Interacting with SV triangle ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle); if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated)) current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated); float uu, vv, ww; ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww); V = ImClamp(1.0f - vv, 0.0001f, 1.0f); S = ImClamp(uu / V, 0.0001f, 1.0f); value_changed = value_changed_sv = true; } } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { // SV rectangle logic InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size)); if (IsItemActive()) { S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1)); V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); value_changed = value_changed_sv = true; } if (!(flags & ImGuiColorEditFlags_NoOptions)) OpenPopupOnItemClick("context"); // Hue bar logic SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y)); InvisibleButton("hue", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); value_changed = value_changed_h = true; } } // Alpha bar logic if (alpha_bar) { SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y)); InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size)); if (IsItemActive()) { col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1)); value_changed = true; } } PopItemFlag(); // ImGuiItemFlags_NoNav if (!(flags & ImGuiColorEditFlags_NoSidePreview)) { SameLine(0, style.ItemInnerSpacing.x); BeginGroup(); } if (!(flags & ImGuiColorEditFlags_NoLabel)) { const char* label_display_end = FindRenderedTextEnd(label); if (label != label_display_end) { if ((flags & ImGuiColorEditFlags_NoSidePreview)) SameLine(0, style.ItemInnerSpacing.x); TextEx(label, label_display_end); } } if (!(flags & ImGuiColorEditFlags_NoSidePreview)) { PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true); ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); if ((flags & ImGuiColorEditFlags_NoLabel)) Text("Current"); ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf | ImGuiColorEditFlags_NoTooltip; ColorButton("##current", col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2)); if (ref_col != NULL) { Text("Original"); ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]); if (ColorButton("##original", ref_col_v4, (flags & sub_flags_to_forward), ImVec2(square_sz * 3, square_sz * 2))) { memcpy(col, ref_col, components * sizeof(float)); value_changed = true; } } PopItemFlag(); EndGroup(); } // Convert back color to RGB if (value_changed_h || value_changed_sv) { if (flags & ImGuiColorEditFlags_InputRGB) { ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]); } else if (flags & ImGuiColorEditFlags_InputHSV) { col[0] = H; col[1] = S; col[2] = V; } } // R,G,B and H,S,V slider color editor bool value_changed_fix_hue_wrap = false; if ((flags & ImGuiColorEditFlags_NoInputs) == 0) { PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x); ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf; ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker; if (flags & ImGuiColorEditFlags_DisplayRGB || (flags & ImGuiColorEditFlags__DisplayMask) == 0) if (ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_DisplayRGB)) { // FIXME: Hackily differenciating using the DragInt (ActiveId != 0 && !ActiveIdAllowOverlap) vs. using the InputText or DropTarget. // For the later we don't want to run the hue-wrap canceling code. If you are well versed in HSV picker please provide your input! (See #2050) value_changed_fix_hue_wrap = (g.ActiveId != 0 && !g.ActiveIdAllowOverlap); value_changed = true; } if (flags & ImGuiColorEditFlags_DisplayHSV || (flags & ImGuiColorEditFlags__DisplayMask) == 0) value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_DisplayHSV); if (flags & ImGuiColorEditFlags_DisplayHex || (flags & ImGuiColorEditFlags__DisplayMask) == 0) value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_DisplayHex); PopItemWidth(); } // Try to cancel hue wrap (after ColorEdit4 call), if any if (value_changed_fix_hue_wrap && (flags & ImGuiColorEditFlags_InputRGB)) { float new_H, new_S, new_V; ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V); if (new_H <= 0 && H > 0) { if (new_V <= 0 && V != new_V) ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]); else if (new_S <= 0) ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]); } } if (value_changed) { if (flags & ImGuiColorEditFlags_InputRGB) { R = col[0]; G = col[1]; B = col[2]; ColorConvertRGBtoHSV(R, G, B, H, S, V); } else if (flags & ImGuiColorEditFlags_InputHSV) { H = col[0]; S = col[1]; V = col[2]; ColorConvertHSVtoRGB(H, S, V, R, G, B); } } ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z); ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f); ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(R, G, B, 1.0f)); const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) }; ImVec2 sv_cursor_pos; if (flags & ImGuiColorEditFlags_PickerHueWheel) { // Render Hue Wheel const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out). const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12); for (int n = 0; n < 6; n++) { const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps; const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps; const int vert_start_idx = draw_list->VtxBuffer.Size; draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc); draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness); const int vert_end_idx = draw_list->VtxBuffer.Size; // Paint colors over existing vertices ImVec2 gradient_p0(wheel_center.x + ImCos(a0) * wheel_r_inner, wheel_center.y + ImSin(a0) * wheel_r_inner); ImVec2 gradient_p1(wheel_center.x + ImCos(a1) * wheel_r_inner, wheel_center.y + ImSin(a1) * wheel_r_inner); ShadeVertsLinearColorGradientKeepAlpha(draw_list, vert_start_idx, vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]); } // Render Cursor + preview on Hue Wheel float cos_hue_angle = ImCos(H * 2.0f * IM_PI); float sin_hue_angle = ImSin(H * 2.0f * IM_PI); ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f); float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f; int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32); draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments); draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments); draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments); // Render SV triangle (rotated according to hue) ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle); ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle); ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle); ImVec2 uv_white = GetFontTexUvWhitePixel(); draw_list->PrimReserve(6, 6); draw_list->PrimVtx(tra, uv_white, hue_color32); draw_list->PrimVtx(trb, uv_white, hue_color32); draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE); draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS); draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK); draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS); draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f); sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V)); } else if (flags & ImGuiColorEditFlags_PickerHueBar) { // Render SV Square draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE); draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK); RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f); sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2); // Render Hue Bar for (int i = 0; i < 6; ++i) draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]); float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f); RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f); RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); } // Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range) float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f; draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12); draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12); draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12); // Render alpha bar if (alpha_bar) { float alpha = ImSaturate(col[3]); ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size); RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f)); draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK); float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f); RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f); RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f); } EndGroup(); if (value_changed && memcmp(backup_initial_col, col, components * sizeof(float)) == 0) value_changed = false; if (value_changed) MarkItemEdited(window->DC.LastItemId); PopID(); return value_changed; } // A little colored square. Return true when clicked. // FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip. // 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip. // Note that 'col' may be encoded in HSV if ImGuiColorEditFlags_InputHSV is set. bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiID id = window->GetID(desc_id); float default_size = GetFrameHeight(); if (size.x == 0.0f) size.x = default_size; if (size.y == 0.0f) size.y = default_size; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f); if (!ItemAdd(bb, id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held); if (flags & ImGuiColorEditFlags_NoAlpha) flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf); ImVec4 col_rgb = col; if (flags & ImGuiColorEditFlags_InputHSV) ColorConvertHSVtoRGB(col_rgb.x, col_rgb.y, col_rgb.z, col_rgb.x, col_rgb.y, col_rgb.z); ImVec4 col_rgb_without_alpha(col_rgb.x, col_rgb.y, col_rgb.z, 1.0f); float grid_step = ImMin(size.x, size.y) / 2.99f; float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f); ImRect bb_inner = bb; float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts. bb_inner.Expand(off); if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col_rgb.w < 1.0f) { float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f); RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col_rgb), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight); window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_rgb_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft); } else { // Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col_rgb : col_rgb_without_alpha; if (col_source.w < 1.0f) RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding); else window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All); } RenderNavHighlight(bb, id); if (g.Style.FrameBorderSize > 0.0f) RenderFrameBorder(bb.Min, bb.Max, rounding); else window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border // Drag and Drop Source // NB: The ActiveId test is merely an optional micro-optimization, BeginDragDropSource() does the same test. if (g.ActiveId == id && !(flags & ImGuiColorEditFlags_NoDragDrop) && BeginDragDropSource()) { if (flags & ImGuiColorEditFlags_NoAlpha) SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col_rgb, sizeof(float) * 3, ImGuiCond_Once); else SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col_rgb, sizeof(float) * 4, ImGuiCond_Once); ColorButton(desc_id, col, flags); SameLine(); TextEx("Color"); EndDragDropSource(); } // Tooltip if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered) ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)); if (pressed) MarkItemEdited(id); return pressed; } // Initialize/override default color options void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; if ((flags & ImGuiColorEditFlags__DisplayMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DisplayMask; if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask; if ((flags & ImGuiColorEditFlags__PickerMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask; if ((flags & ImGuiColorEditFlags__InputMask) == 0) flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputMask; IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DisplayMask)); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__DataTypeMask)); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__PickerMask)); // Check only 1 option is selected IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiColorEditFlags__InputMask)); // Check only 1 option is selected g.ColorEditOptions = flags; } // Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set. void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags) { ImGuiContext& g = *GImGui; BeginTooltipEx(0, true); const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text; if (text_end > text) { TextEx(text, text_end); Separator(); } ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2); ImVec4 cf(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); ColorButton("##preview", cf, (flags & (ImGuiColorEditFlags__InputMask | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz); SameLine(); if ((flags & ImGuiColorEditFlags_InputRGB) || !(flags & ImGuiColorEditFlags__InputMask)) { if (flags & ImGuiColorEditFlags_NoAlpha) Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]); else Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]); } else if (flags & ImGuiColorEditFlags_InputHSV) { if (flags & ImGuiColorEditFlags_NoAlpha) Text("H: %.3f, S: %.3f, V: %.3f", col[0], col[1], col[2]); else Text("H: %.3f, S: %.3f, V: %.3f, A: %.3f", col[0], col[1], col[2], col[3]); } EndTooltip(); } void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags) { bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__DisplayMask); bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask); if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context")) return; ImGuiContext& g = *GImGui; ImGuiColorEditFlags opts = g.ColorEditOptions; if (allow_opt_inputs) { if (RadioButton("RGB", (opts & ImGuiColorEditFlags_DisplayRGB) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayRGB; if (RadioButton("HSV", (opts & ImGuiColorEditFlags_DisplayHSV) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHSV; if (RadioButton("Hex", (opts & ImGuiColorEditFlags_DisplayHex) != 0)) opts = (opts & ~ImGuiColorEditFlags__DisplayMask) | ImGuiColorEditFlags_DisplayHex; } if (allow_opt_datatype) { if (allow_opt_inputs) Separator(); if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8; if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) != 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float; } if (allow_opt_inputs || allow_opt_datatype) Separator(); if (Button("Copy as..", ImVec2(-1,0))) OpenPopup("Copy"); if (BeginPopup("Copy")) { int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]); char buf[64]; ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]); if (Selectable(buf)) SetClipboardText(buf); ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca); if (Selectable(buf)) SetClipboardText(buf); if (flags & ImGuiColorEditFlags_NoAlpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb); else ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca); if (Selectable(buf)) SetClipboardText(buf); EndPopup(); } g.ColorEditOptions = opts; EndPopup(); } void ImGui::ColorPickerOptionsPopup(const float* ref_col, ImGuiColorEditFlags flags) { bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask); bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar); if ((!allow_opt_picker && !allow_opt_alpha_bar) || !BeginPopup("context")) return; ImGuiContext& g = *GImGui; if (allow_opt_picker) { ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function PushItemWidth(picker_size.x); for (int picker_type = 0; picker_type < 2; picker_type++) { // Draw small/thumbnail version of each picker type (over an invisible button for selection) if (picker_type > 0) Separator(); PushID(picker_type); ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha); if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar; if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel; ImVec2 backup_pos = GetCursorScreenPos(); if (Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask); SetCursorScreenPos(backup_pos); ImVec4 dummy_ref_col; memcpy(&dummy_ref_col, ref_col, sizeof(float) * ((picker_flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4)); ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags); PopID(); } PopItemWidth(); } if (allow_opt_alpha_bar) { if (allow_opt_picker) Separator(); CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar); } EndPopup(); } //------------------------------------------------------------------------- // [SECTION] Widgets: TreeNode, CollapsingHeader, etc. //------------------------------------------------------------------------- // - TreeNode() // - TreeNodeV() // - TreeNodeEx() // - TreeNodeExV() // - TreeNodeBehavior() [Internal] // - TreePush() // - TreePop() // - TreeAdvanceToLabelPos() // - GetTreeNodeToLabelSpacing() // - SetNextTreeNodeOpen() // - CollapsingHeader() //------------------------------------------------------------------------- bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(str_id, 0, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(ptr_id, 0, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNode(const char* label) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), 0, label, NULL); } bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) { return TreeNodeExV(str_id, 0, fmt, args); } bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) { return TreeNodeExV(ptr_id, 0, fmt, args); } bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags, label, NULL); } bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(str_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) { va_list args; va_start(args, fmt); bool is_open = TreeNodeExV(ptr_id, flags, fmt, args); va_end(args); return is_open; } bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end); } bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end); } bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags) { if (flags & ImGuiTreeNodeFlags_Leaf) return true; // We only write to the tree storage if the user clicks (or explicitly use SetNextTreeNode*** functions) ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGuiStorage* storage = window->DC.StateStorage; bool is_open; if (g.NextTreeNodeOpenCond != 0) { if (g.NextTreeNodeOpenCond & ImGuiCond_Always) { is_open = g.NextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { // We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently. const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { is_open = g.NextTreeNodeOpenVal; storage->SetInt(id, is_open); } else { is_open = stored_value != 0; } } g.NextTreeNodeOpenCond = 0; } else { is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0; } // When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). // NB- If we are above max depth we still allow manually opened nodes to be logged. if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && (window->DC.TreeDepth - g.LogDepthRef) < g.LogDepthToExpand) is_open = true; return is_open; } bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0; const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f); if (!label_end) label_end = FindRenderedTextEnd(label); const ImVec2 label_size = CalcTextSize(label, label_end, false); // We vertically grow up to current line height up the typical widget height. const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it const float frame_height = ImMax(ImMin(window->DC.CurrentLineSize.y, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2); ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height)); if (display_frame) { // Framed header expand a little outside the default padding frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1; frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1; } const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser ItemSize(ImVec2(text_width, frame_height), text_base_offset_y); // For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing // (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not) const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y); bool is_open = TreeNodeBehaviorIsOpen(id, flags); bool is_leaf = (flags & ImGuiTreeNodeFlags_Leaf) != 0; // Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child. // For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop(). // This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero. if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth); bool item_add = ItemAdd(interact_bb, id); window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect; window->DC.LastItemDisplayRect = frame_bb; if (!item_add) { if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open; } // Flags that affects opening behavior: // - 0 (default) .................... single-click anywhere to open // - OpenOnDoubleClick .............. double-click anywhere to open // - OpenOnArrow .................... single-click on arrow to open // - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers; if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) button_flags |= ImGuiButtonFlags_AllowItemOverlap; if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0); if (!is_leaf) button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; bool selected = (flags & ImGuiTreeNodeFlags_Selected) != 0; bool hovered, held; bool pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags); bool toggled = false; if (!is_leaf) { if (pressed) { toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id); if (flags & ImGuiTreeNodeFlags_OpenOnArrow) toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover); if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) toggled |= g.IO.MouseDoubleClicked[0]; if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again. toggled = false; } if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open) { toggled = true; NavMoveRequestCancel(); } if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority? { toggled = true; NavMoveRequestCancel(); } if (toggled) { is_open = !is_open; window->DC.StateStorage->SetInt(id, is_open); } } if (flags & ImGuiTreeNodeFlags_AllowItemOverlap) SetItemAllowOverlap(); // Render const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y); ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin; if (display_frame) { // Framed type RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding); RenderNavHighlight(frame_bb, id, nav_highlight_flags); RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f); if (g.LogEnabled) { // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. const char log_prefix[] = "\n##"; const char log_suffix[] = "##"; LogRenderedText(&text_pos, log_prefix, log_prefix+3); RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); LogRenderedText(&text_pos, log_suffix, log_suffix+2); } else { RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size); } } else { // Unframed typed for tree nodes if (hovered || selected) { RenderFrame(frame_bb.Min, frame_bb.Max, col, false); RenderNavHighlight(frame_bb, id, nav_highlight_flags); } if (flags & ImGuiTreeNodeFlags_Bullet) RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y)); else if (!is_leaf) RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f); if (g.LogEnabled) LogRenderedText(&text_pos, ">"); RenderText(text_pos, label, label_end, false); } if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen)) TreePushRawID(id); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | (is_leaf ? 0 : ImGuiItemStatusFlags_Openable) | (is_open ? ImGuiItemStatusFlags_Opened : 0)); return is_open; } void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; PushID(str_id ? str_id : "#TreePush"); } void ImGui::TreePush(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); } void ImGui::TreePushRawID(ImGuiID id) { ImGuiWindow* window = GetCurrentWindow(); Indent(); window->DC.TreeDepth++; window->IDStack.push_back(id); } void ImGui::TreePop() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; Unindent(); window->DC.TreeDepth--; if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet()) if (g.NavIdIsAlive && (window->DC.TreeDepthMayJumpToParentOnPop & (1 << window->DC.TreeDepth))) { SetNavID(window->IDStack.back(), g.NavLayer); NavMoveRequestCancel(); } window->DC.TreeDepthMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1; IM_ASSERT(window->IDStack.Size > 1); // There should always be 1 element in the IDStack (pushed during window creation). If this triggers you called TreePop/PopID too much. PopID(); } void ImGui::TreeAdvanceToLabelPos() { ImGuiContext& g = *GImGui; g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing(); } // Horizontal distance preceding label when using TreeNode() or Bullet() float ImGui::GetTreeNodeToLabelSpacing() { ImGuiContext& g = *GImGui; return g.FontSize + (g.Style.FramePadding.x * 2.0f); } void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond) { ImGuiContext& g = *GImGui; if (g.CurrentWindow->SkipItems) return; g.NextTreeNodeOpenVal = is_open; g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always; } // CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag). // This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode(). bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader, label); } bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (p_open && !*p_open) return false; ImGuiID id = window->GetID(label); bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label); if (p_open) { // Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc. ImGuiContext& g = *GImGui; ImGuiItemHoveredDataBackup last_item_backup; float button_radius = g.FontSize * 0.5f; ImVec2 button_center = ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_radius, window->DC.LastItemRect.GetCenter().y); if (CloseButton(window->GetID((void*)((intptr_t)id+1)), button_center, button_radius)) *p_open = false; last_item_backup.Restore(); } return is_open; } //------------------------------------------------------------------------- // [SECTION] Widgets: Selectable //------------------------------------------------------------------------- // - Selectable() //------------------------------------------------------------------------- // Tip: pass a non-visible label (e.g. "##dummy") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID or use ##unique_id. bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped. PopClipRect(); ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y); ImVec2 pos = window->DC.CursorPos; pos.y += window->DC.CurrentLineTextBaseOffset; ImRect bb_inner(pos, pos + size); ItemSize(bb_inner); // Fill horizontal space. ImVec2 window_padding = window->WindowPadding; float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x; float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - pos.x); ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y); ImRect bb(pos, pos + size_draw); if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth)) bb.Max.x += window_padding.x; // Selectables are tightly packed together, we extend the box to cover spacing between selectable. float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); float spacing_R = style.ItemSpacing.x - spacing_L; float spacing_D = style.ItemSpacing.y - spacing_U; bb.Min.x -= spacing_L; bb.Min.y -= spacing_U; bb.Max.x += spacing_R; bb.Max.y += spacing_D; bool item_add; if (flags & ImGuiSelectableFlags_Disabled) { ImGuiItemFlags backup_item_flags = window->DC.ItemFlags; window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus; item_add = ItemAdd(bb, id); window->DC.ItemFlags = backup_item_flags; } else { item_add = ItemAdd(bb, id); } if (!item_add) { if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) PushColumnClipRect(); return false; } // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries ImGuiButtonFlags button_flags = 0; if (flags & ImGuiSelectableFlags_NoHoldingActiveID) button_flags |= ImGuiButtonFlags_NoHoldingActiveID; if (flags & ImGuiSelectableFlags_PressedOnClick) button_flags |= ImGuiButtonFlags_PressedOnClick; if (flags & ImGuiSelectableFlags_PressedOnRelease) button_flags |= ImGuiButtonFlags_PressedOnRelease; if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled; if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; if (flags & ImGuiSelectableFlags_Disabled) selected = false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); // Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets) if (pressed || hovered) if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent) { g.NavDisableHighlight = true; SetNavID(id, window->DC.NavLayerCurrent); } if (pressed) MarkItemEdited(id); // Render if (hovered || selected) { const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(bb.Min, bb.Max, col, false, 0.0f); RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding); } if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) { PushColumnClipRect(); bb.Max.x -= (GetContentRegionMax().x - max_x); } if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderTextClipped(bb_inner.Min, bb_inner.Max, label, NULL, &label_size, style.SelectableTextAlign, &bb); if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor(); // Automatically close popups if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup)) CloseCurrentPopup(); return pressed; } bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg) { if (Selectable(label, *p_selected, flags, size_arg)) { *p_selected = !*p_selected; return true; } return false; } //------------------------------------------------------------------------- // [SECTION] Widgets: ListBox //------------------------------------------------------------------------- // - ListBox() // - ListBoxHeader() // - ListBoxFooter() //------------------------------------------------------------------------- // FIXME: In principle this function should be called BeginListBox(). We should rename it after re-evaluating if we want to keep the same signature. // Helper to calculate the size of a listbox and display a label on the right. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty" bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = GetStyle(); const ImGuiID id = GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y); ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy. if (!IsRectVisible(bb.Min, bb.Max)) { ItemSize(bb.GetSize(), style.FramePadding.y); ItemAdd(bb, 0, &frame_bb); return false; } BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); BeginChildFrame(id, frame_bb.GetSize()); return true; } // FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature. bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) { // Size default to hold ~7.25 items. // We add +25% worth of item height to allow the user to see at a glance if there are more items up/down, without looking at the scrollbar. // We don't add this extra bit if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. if (height_in_items < 0) height_in_items = ImMin(items_count, 7); const ImGuiStyle& style = GetStyle(); float height_in_items_f = (height_in_items < items_count) ? (height_in_items + 0.25f) : (height_in_items + 0.00f); // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). ImVec2 size; size.x = 0.0f; size.y = GetTextLineHeightWithSpacing() * height_in_items_f + style.FramePadding.y * 2.0f; return ListBoxHeader(label, size); } // FIXME: In principle this function should be called EndListBox(). We should rename it after re-evaluating if we want to keep the same signature. void ImGui::ListBoxFooter() { ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow; const ImRect bb = parent_window->DC.LastItemRect; const ImGuiStyle& style = GetStyle(); EndChildFrame(); // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) // We call SameLine() to restore DC.CurrentLine* data SameLine(); parent_window->DC.CursorPos = bb.Min; ItemSize(bb, style.FramePadding.y); EndGroup(); } bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items) { const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); return value_changed; } bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { if (!ListBoxHeader(label, items_count, height_in_items)) return false; // Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper. ImGuiContext& g = *GImGui; bool value_changed = false; ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to. while (clipper.Step()) for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) { const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; PushID(i); if (Selectable(item_text, item_selected)) { *current_item = i; value_changed = true; } if (item_selected) SetItemDefaultFocus(); PopID(); } ListBoxFooter(); if (value_changed) MarkItemEdited(g.CurrentWindow->DC.LastItemId); return value_changed; } //------------------------------------------------------------------------- // [SECTION] Widgets: PlotLines, PlotHistogram //------------------------------------------------------------------------- // - PlotEx() [Internal] // - PlotLines() // - PlotHistogram() //------------------------------------------------------------------------- void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 frame_size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); if (frame_size.x == 0.0f) frame_size.x = CalcItemWidth(); if (frame_size.y == 0.0f) frame_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, 0, &frame_bb)) return; const bool hovered = ItemHoverable(frame_bb, id); // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { float v_min = FLT_MAX; float v_max = -FLT_MAX; for (int i = 0; i < values_count; i++) { const float v = values_getter(data, i); v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } if (scale_min == FLT_MAX) scale_min = v_min; if (scale_max == FLT_MAX) scale_max = v_max; } RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); const int values_count_min = (plot_type == ImGuiPlotType_Lines) ? 2 : 1; if (values_count >= values_count_min) { int res_w = ImMin((int)frame_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0); // Tooltip on hover int v_hovered = -1; if (hovered && inner_bb.Contains(g.IO.MousePos)) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); const int v_idx = (int)(t * item_count); IM_ASSERT(v_idx >= 0 && v_idx < values_count); const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } const float t_step = 1.0f / (float)res_w; const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min)); float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; const int v1_idx = (int)(t0 * item_count + 0.5f); IM_ASSERT(v1_idx >= 0 && v1_idx < values_count); const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count); const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) ); // NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU. ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0); ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t)); if (plot_type == ImGuiPlotType_Lines) { window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); } else if (plot_type == ImGuiPlotType_Histogram) { if (pos1.x >= pos0.x + 2.0f) pos1.x -= 1.0f; window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base); } t0 = t1; tp0 = tp1; } } // Text overlay if (overlay_text) RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f)); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); } struct ImGuiPlotArrayGetterData { const float* Values; int Stride; ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) { ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; const float v = *(const float*)(const void*)((const unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); return v; } void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride) { ImGuiPlotArrayGetterData data(values, stride); PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } //------------------------------------------------------------------------- // [SECTION] Widgets: Value helpers // Those is not very useful, legacy API. //------------------------------------------------------------------------- // - Value() //------------------------------------------------------------------------- void ImGui::Value(const char* prefix, bool b) { Text("%s: %s", prefix, (b ? "true" : "false")); } void ImGui::Value(const char* prefix, int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, unsigned int v) { Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, float v, const char* float_format) { if (float_format) { char fmt[64]; ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); Text(fmt, prefix, v); } else { Text("%s: %.3f", prefix, v); } } //------------------------------------------------------------------------- // [SECTION] MenuItem, BeginMenu, EndMenu, etc. //------------------------------------------------------------------------- // - ImGuiMenuColumns [Internal] // - BeginMainMenuBar() // - EndMainMenuBar() // - BeginMenuBar() // - EndMenuBar() // - BeginMenu() // - EndMenu() // - MenuItem() //------------------------------------------------------------------------- // Helpers for internal use ImGuiMenuColumns::ImGuiMenuColumns() { Spacing = Width = NextWidth = 0.0f; memset(Pos, 0, sizeof(Pos)); memset(NextWidths, 0, sizeof(NextWidths)); } void ImGuiMenuColumns::Update(int count, float spacing, bool clear) { IM_ASSERT(count == IM_ARRAYSIZE(Pos)); Width = NextWidth = 0.0f; Spacing = spacing; if (clear) memset(NextWidths, 0, sizeof(NextWidths)); for (int i = 0; i < IM_ARRAYSIZE(Pos); i++) { if (i > 0 && NextWidths[i] > 0.0f) Width += Spacing; Pos[i] = (float)(int)Width; Width += NextWidths[i]; NextWidths[i] = 0.0f; } } float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double { NextWidth = 0.0f; NextWidths[0] = ImMax(NextWidths[0], w0); NextWidths[1] = ImMax(NextWidths[1], w1); NextWidths[2] = ImMax(NextWidths[2], w2); for (int i = 0; i < IM_ARRAYSIZE(Pos); i++) NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f); return ImMax(Width, NextWidth); } float ImGuiMenuColumns::CalcExtraSpace(float avail_w) { return ImMax(0.0f, avail_w - Width); } // For the main menu bar, which cannot be moved, we honor g.Style.DisplaySafeAreaPadding to ensure text can be visible on a TV set. bool ImGui::BeginMainMenuBar() { ImGuiContext& g = *GImGui; g.NextWindowData.MenuBarOffsetMinVal = ImVec2(g.Style.DisplaySafeAreaPadding.x, ImMax(g.Style.DisplaySafeAreaPadding.y - g.Style.FramePadding.y, 0.0f)); SetNextWindowPos(ImVec2(0.0f, 0.0f)); SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.NextWindowData.MenuBarOffsetMinVal.y + g.FontBaseSize + g.Style.FramePadding.y)); PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0)); ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_MenuBar; bool is_open = Begin("##MainMenuBar", NULL, window_flags) && BeginMenuBar(); PopStyleVar(2); g.NextWindowData.MenuBarOffsetMinVal = ImVec2(0.0f, 0.0f); if (!is_open) { End(); return false; } return true; //-V1020 } void ImGui::EndMainMenuBar() { EndMenuBar(); // When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window ImGuiContext& g = *GImGui; if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0) FocusPreviousWindowIgnoringOne(g.NavWindow); End(); } bool ImGui::BeginMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (!(window->Flags & ImGuiWindowFlags_MenuBar)) return false; IM_ASSERT(!window->DC.MenuBarAppending); BeginGroup(); // Backup position on layer 0 PushID("##menubar"); // We don't clip with current window clipping rectangle as it is already set to the area below. However we clip with window full rect. // We remove 1 worth of rounding to Max.x to that text in long menus and small windows don't tend to display over the lower-right rounded area, which looks particularly glitchy. ImRect bar_rect = window->MenuBarRect(); ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f)); clip_rect.ClipWith(window->OuterRectClipped); PushClipRect(clip_rect.Min, clip_rect.Max, false); window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffset.x, bar_rect.Min.y + window->DC.MenuBarOffset.y); window->DC.LayoutType = ImGuiLayoutType_Horizontal; window->DC.NavLayerCurrent = ImGuiNavLayer_Menu; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu); window->DC.MenuBarAppending = true; AlignTextToFramePadding(); return true; } void ImGui::EndMenuBar() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImGuiContext& g = *GImGui; // Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings. if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu)) { ImGuiWindow* nav_earliest_child = g.NavWindow; while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu)) nav_earliest_child = nav_earliest_child->ParentWindow; if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None) { // To do so we claim focus back, restore NavId and then process the movement request for yet another frame. // This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost) IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check FocusWindow(window); SetNavIDWithRectRel(window->NavLastIds[1], 1, window->NavRectRel[1]); g.NavLayer = ImGuiNavLayer_Menu; g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection. g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued; NavMoveRequestCancel(); } } IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar); IM_ASSERT(window->DC.MenuBarAppending); PopClipRect(); PopID(); window->DC.MenuBarOffset.x = window->DC.CursorPos.x - window->MenuBarRect().Min.x; // Save horizontal position so next append can reuse it. This is kinda equivalent to a per-layer CursorPos. window->DC.GroupStack.back().AdvanceCursor = false; EndGroup(); // Restore position on layer 0 window->DC.LayoutType = ImGuiLayoutType_Vertical; window->DC.NavLayerCurrent = ImGuiNavLayer_Main; window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main); window->DC.MenuBarAppending = false; } bool ImGui::BeginMenu(const char* label, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); ImVec2 label_size = CalcTextSize(label, NULL, true); bool pressed; bool menu_is_open = IsPopupOpen(id); bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].OpenParentId == window->IDStack.back()); ImGuiWindow* backed_nav_window = g.NavWindow; if (menuset_is_open) g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent) // The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu, // However the final position is going to be different! It is choosen by FindBestWindowPosForPopup(). // e.g. Menus tend to overlap each other horizontally to amplify relative Z-ordering. ImVec2 popup_pos, pos = window->DC.CursorPos; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { // Menu inside an horizontal menu bar // Selectable extend their highlight by half ItemSpacing in each direction. // For ChildMenu, the popup position will be overwritten by the call to FindBestWindowPosForPopup() in Begin() popup_pos = ImVec2(pos.x - 1.0f - (float)(int)(style.ItemSpacing.x * 0.5f), pos.y - style.FramePadding.y + window->MenuBarHeight()); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); float w = label_size.x; pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); PopStyleVar(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). } else { // Menu inside a menu popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y); float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_NoHoldingActiveID | ImGuiSelectableFlags_PressedOnClick | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f)); if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderArrow(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right); if (!enabled) PopStyleColor(); } const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id); if (menuset_is_open) g.NavWindow = backed_nav_window; bool want_open = false, want_close = false; if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) { // Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive. bool moving_within_opened_triangle = false; if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].ParentWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar)) { if (ImGuiWindow* next_window = g.OpenPopupStack[g.BeginPopupStack.Size].Window) { // FIXME-DPI: Values should be derived from a master "scale" factor. ImRect next_window_rect = next_window->Rect(); ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta; ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR(); ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR(); float extra = ImClamp(ImFabs(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack. ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale? tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f); moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos); //window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug } } want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle); want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed); if (g.NavActivateId == id) { want_close = menu_is_open; want_open = !menu_is_open; } if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open { want_open = true; NavMoveRequestCancel(); } } else { // Menu bar if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it { want_close = true; want_open = menu_is_open = false; } else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others { want_open = true; } else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open { want_open = true; NavMoveRequestCancel(); } } if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }' want_close = true; if (want_close && IsPopupOpen(id)) ClosePopupToLevel(g.BeginPopupStack.Size, true); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0)); if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size) { // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame. OpenPopup(label); return false; } menu_is_open |= want_open; if (want_open) OpenPopup(label); if (menu_is_open) { // Sub-menus are ChildWindow so that mouse can be hovering across them (otherwise top-most popup menu would steal focus and not allow hovering on parent menu) SetNextWindowPos(popup_pos, ImGuiCond_Always); ImGuiWindowFlags flags = ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus; if (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) flags |= ImGuiWindowFlags_ChildWindow; menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display) } return menu_is_open; } void ImGui::EndMenu() { // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu). // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs. // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction. ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical) { ClosePopupToLevel(g.BeginPopupStack.Size, true); NavMoveRequestCancel(); } EndPopup(); } bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImGuiContext& g = *GImGui; ImGuiStyle& style = g.Style; ImVec2 pos = window->DC.CursorPos; ImVec2 label_size = CalcTextSize(label, NULL, true); ImGuiSelectableFlags flags = ImGuiSelectableFlags_PressedOnRelease | (enabled ? 0 : ImGuiSelectableFlags_Disabled); bool pressed; if (window->DC.LayoutType == ImGuiLayoutType_Horizontal) { // Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful // Note that in this situation we render neither the shortcut neither the selected tick mark float w = label_size.x; window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f); PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f); pressed = Selectable(label, false, flags, ImVec2(w, 0.0f)); PopStyleVar(); window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar(). } else { ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f); float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w); pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f)); if (shortcut_size.x > 0.0f) { PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]); RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false); PopStyleColor(); } if (selected) RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f); } IMGUI_TEST_ENGINE_ITEM_INFO(window->DC.LastItemId, label, window->DC.ItemFlags | ImGuiItemStatusFlags_Checkable | (selected ? ImGuiItemStatusFlags_Checked : 0)); return pressed; } bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled) { if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled)) { if (p_selected) *p_selected = !*p_selected; return true; } return false; } //------------------------------------------------------------------------- // [SECTION] Widgets: BeginTabBar, EndTabBar, etc. //------------------------------------------------------------------------- // [BETA API] API may evolve! This code has been extracted out of the Docking branch, // and some of the construct which are not used in Master may be left here to facilitate merging. //------------------------------------------------------------------------- // - BeginTabBar() // - BeginTabBarEx() [Internal] // - EndTabBar() // - TabBarLayout() [Internal] // - TabBarCalcTabID() [Internal] // - TabBarCalcMaxTabWidth() [Internal] // - TabBarFindTabById() [Internal] // - TabBarRemoveTab() [Internal] // - TabBarCloseTab() [Internal] // - TabBarScrollClamp()v // - TabBarScrollToTab() [Internal] // - TabBarQueueChangeTabOrder() [Internal] // - TabBarScrollingButtons() [Internal] // - TabBarTabListPopupButton() [Internal] //------------------------------------------------------------------------- namespace ImGui { static void TabBarLayout(ImGuiTabBar* tab_bar); static ImU32 TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label); static float TabBarCalcMaxTabWidth(); static float TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling); static void TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab); static ImGuiTabItem* TabBarScrollingButtons(ImGuiTabBar* tab_bar); static ImGuiTabItem* TabBarTabListPopupButton(ImGuiTabBar* tab_bar); } ImGuiTabBar::ImGuiTabBar() { ID = 0; SelectedTabId = NextSelectedTabId = VisibleTabId = 0; CurrFrameVisible = PrevFrameVisible = -1; ContentsHeight = 0.0f; OffsetMax = OffsetNextTab = 0.0f; ScrollingAnim = ScrollingTarget = ScrollingTargetDistToVisibility = ScrollingSpeed = 0.0f; Flags = ImGuiTabBarFlags_None; ReorderRequestTabId = 0; ReorderRequestDir = 0; WantLayout = VisibleTabWasSubmitted = false; LastTabItemIdx = -1; } static int IMGUI_CDECL TabItemComparerByVisibleOffset(const void* lhs, const void* rhs) { const ImGuiTabItem* a = (const ImGuiTabItem*)lhs; const ImGuiTabItem* b = (const ImGuiTabItem*)rhs; return (int)(a->Offset - b->Offset); } static int IMGUI_CDECL TabBarSortItemComparer(const void* lhs, const void* rhs) { const ImGuiTabBarSortItem* a = (const ImGuiTabBarSortItem*)lhs; const ImGuiTabBarSortItem* b = (const ImGuiTabBarSortItem*)rhs; if (int d = (int)(b->Width - a->Width)) return d; return (b->Index - a->Index); } static ImGuiTabBar* GetTabBarFromTabBarRef(const ImGuiTabBarRef& ref) { ImGuiContext& g = *GImGui; return ref.Ptr ? ref.Ptr : g.TabBars.GetByIndex(ref.IndexInMainPool); } static ImGuiTabBarRef GetTabBarRefFromTabBar(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; if (g.TabBars.Contains(tab_bar)) return ImGuiTabBarRef(g.TabBars.GetIndex(tab_bar)); return ImGuiTabBarRef(tab_bar); } bool ImGui::BeginTabBar(const char* str_id, ImGuiTabBarFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; ImGuiID id = window->GetID(str_id); ImGuiTabBar* tab_bar = g.TabBars.GetOrAddByKey(id); ImRect tab_bar_bb = ImRect(window->DC.CursorPos.x, window->DC.CursorPos.y, window->InnerClipRect.Max.x, window->DC.CursorPos.y + g.FontSize + g.Style.FramePadding.y * 2); tab_bar->ID = id; return BeginTabBarEx(tab_bar, tab_bar_bb, flags | ImGuiTabBarFlags_IsFocused); } bool ImGui::BeginTabBarEx(ImGuiTabBar* tab_bar, const ImRect& tab_bar_bb, ImGuiTabBarFlags flags) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; if ((flags & ImGuiTabBarFlags_DockNode) == 0) window->IDStack.push_back(tab_bar->ID); // Add to stack g.CurrentTabBarStack.push_back(GetTabBarRefFromTabBar(tab_bar)); g.CurrentTabBar = tab_bar; if (tab_bar->CurrFrameVisible == g.FrameCount) { //IMGUI_DEBUG_LOG("BeginTabBarEx already called this frame\n", g.FrameCount); IM_ASSERT(0); return true; } // When toggling back from ordered to manually-reorderable, shuffle tabs to enforce the last visible order. // Otherwise, the most recently inserted tabs would move at the end of visible list which can be a little too confusing or magic for the user. if ((flags & ImGuiTabBarFlags_Reorderable) && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable) && tab_bar->Tabs.Size > 1 && tab_bar->PrevFrameVisible != -1) ImQsort(tab_bar->Tabs.Data, tab_bar->Tabs.Size, sizeof(ImGuiTabItem), TabItemComparerByVisibleOffset); // Flags if ((flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0) flags |= ImGuiTabBarFlags_FittingPolicyDefault_; tab_bar->Flags = flags; tab_bar->BarRect = tab_bar_bb; tab_bar->WantLayout = true; // Layout will be done on the first call to ItemTab() tab_bar->PrevFrameVisible = tab_bar->CurrFrameVisible; tab_bar->CurrFrameVisible = g.FrameCount; tab_bar->FramePadding = g.Style.FramePadding; // Layout ItemSize(ImVec2(tab_bar->OffsetMax, tab_bar->BarRect.GetHeight())); window->DC.CursorPos.x = tab_bar->BarRect.Min.x; // Draw separator const ImU32 col = GetColorU32((flags & ImGuiTabBarFlags_IsFocused) ? ImGuiCol_TabActive : ImGuiCol_Tab); const float y = tab_bar->BarRect.Max.y - 1.0f; { const float separator_min_x = tab_bar->BarRect.Min.x - window->WindowPadding.x; const float separator_max_x = tab_bar->BarRect.Max.x + window->WindowPadding.x; window->DrawList->AddLine(ImVec2(separator_min_x, y), ImVec2(separator_max_x, y), col, 1.0f); } return true; } void ImGui::EndTabBar() { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return; ImGuiTabBar* tab_bar = g.CurrentTabBar; if (tab_bar == NULL) { IM_ASSERT(tab_bar != NULL && "Mismatched BeginTabBar()/EndTabBar()!"); return; // FIXME-ERRORHANDLING } if (tab_bar->WantLayout) TabBarLayout(tab_bar); // Restore the last visible height if no tab is visible, this reduce vertical flicker/movement when a tabs gets removed without calling SetTabItemClosed(). const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); if (tab_bar->VisibleTabWasSubmitted || tab_bar->VisibleTabId == 0 || tab_bar_appearing) tab_bar->ContentsHeight = ImMax(window->DC.CursorPos.y - tab_bar->BarRect.Max.y, 0.0f); else window->DC.CursorPos.y = tab_bar->BarRect.Max.y + tab_bar->ContentsHeight; if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) PopID(); g.CurrentTabBarStack.pop_back(); g.CurrentTabBar = g.CurrentTabBarStack.empty() ? NULL : GetTabBarFromTabBarRef(g.CurrentTabBarStack.back()); } // This is called only once a frame before by the first call to ItemTab() // The reason we're not calling it in BeginTabBar() is to leave a chance to the user to call the SetTabItemClosed() functions. static void ImGui::TabBarLayout(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; tab_bar->WantLayout = false; // Garbage collect int tab_dst_n = 0; for (int tab_src_n = 0; tab_src_n < tab_bar->Tabs.Size; tab_src_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_src_n]; if (tab->LastFrameVisible < tab_bar->PrevFrameVisible) { if (tab->ID == tab_bar->SelectedTabId) tab_bar->SelectedTabId = 0; continue; } if (tab_dst_n != tab_src_n) tab_bar->Tabs[tab_dst_n] = tab_bar->Tabs[tab_src_n]; tab_dst_n++; } if (tab_bar->Tabs.Size != tab_dst_n) tab_bar->Tabs.resize(tab_dst_n); // Setup next selected tab ImGuiID scroll_track_selected_tab_id = 0; if (tab_bar->NextSelectedTabId) { tab_bar->SelectedTabId = tab_bar->NextSelectedTabId; tab_bar->NextSelectedTabId = 0; scroll_track_selected_tab_id = tab_bar->SelectedTabId; } // Process order change request (we could probably process it when requested but it's just saner to do it in a single spot). if (tab_bar->ReorderRequestTabId != 0) { if (ImGuiTabItem* tab1 = TabBarFindTabByID(tab_bar, tab_bar->ReorderRequestTabId)) { //IM_ASSERT(tab_bar->Flags & ImGuiTabBarFlags_Reorderable); // <- this may happen when using debug tools int tab2_order = tab_bar->GetTabOrder(tab1) + tab_bar->ReorderRequestDir; if (tab2_order >= 0 && tab2_order < tab_bar->Tabs.Size) { ImGuiTabItem* tab2 = &tab_bar->Tabs[tab2_order]; ImGuiTabItem item_tmp = *tab1; *tab1 = *tab2; *tab2 = item_tmp; if (tab2->ID == tab_bar->SelectedTabId) scroll_track_selected_tab_id = tab2->ID; tab1 = tab2 = NULL; } if (tab_bar->Flags & ImGuiTabBarFlags_SaveSettings) MarkIniSettingsDirty(); } tab_bar->ReorderRequestTabId = 0; } // Tab List Popup (will alter tab_bar->BarRect and therefore the available width!) const bool tab_list_popup_button = (tab_bar->Flags & ImGuiTabBarFlags_TabListPopupButton) != 0; if (tab_list_popup_button) if (ImGuiTabItem* tab_to_select = TabBarTabListPopupButton(tab_bar)) // NB: Will alter BarRect.Max.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; ImVector<ImGuiTabBarSortItem>& width_sort_buffer = g.TabSortByWidthBuffer; width_sort_buffer.resize(tab_bar->Tabs.Size); // Compute ideal widths float width_total_contents = 0.0f; ImGuiTabItem* most_recently_selected_tab = NULL; bool found_selected_tab_id = false; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; IM_ASSERT(tab->LastFrameVisible >= tab_bar->PrevFrameVisible); if (most_recently_selected_tab == NULL || most_recently_selected_tab->LastFrameSelected < tab->LastFrameSelected) most_recently_selected_tab = tab; if (tab->ID == tab_bar->SelectedTabId) found_selected_tab_id = true; // Refresh tab width immediately, otherwise changes of style e.g. style.FramePadding.x would noticeably lag in the tab bar. // Additionally, when using TabBarAddTab() to manipulate tab bar order we occasionally insert new tabs that don't have a width yet, // and we cannot wait for the next BeginTabItem() call. We cannot compute this width within TabBarAddTab() because font size depends on the active window. const char* tab_name = tab_bar->GetTabName(tab); tab->WidthContents = TabItemCalcSize(tab_name, (tab->Flags & ImGuiTabItemFlags_NoCloseButton) ? false : true).x; width_total_contents += (tab_n > 0 ? g.Style.ItemInnerSpacing.x : 0.0f) + tab->WidthContents; // Store data so we can build an array sorted by width if we need to shrink tabs down width_sort_buffer[tab_n].Index = tab_n; width_sort_buffer[tab_n].Width = tab->WidthContents; } // Compute width const float width_avail = tab_bar->BarRect.GetWidth(); float width_excess = (width_avail < width_total_contents) ? (width_total_contents - width_avail) : 0.0f; if (width_excess > 0.0f && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyResizeDown)) { // If we don't have enough room, resize down the largest tabs first if (tab_bar->Tabs.Size > 1) ImQsort(width_sort_buffer.Data, (size_t)width_sort_buffer.Size, sizeof(ImGuiTabBarSortItem), TabBarSortItemComparer); int tab_count_same_width = 1; while (width_excess > 0.0f && tab_count_same_width < tab_bar->Tabs.Size) { while (tab_count_same_width < tab_bar->Tabs.Size && width_sort_buffer[0].Width == width_sort_buffer[tab_count_same_width].Width) tab_count_same_width++; float width_to_remove_per_tab_max = (tab_count_same_width < tab_bar->Tabs.Size) ? (width_sort_buffer[0].Width - width_sort_buffer[tab_count_same_width].Width) : (width_sort_buffer[0].Width - 1.0f); float width_to_remove_per_tab = ImMin(width_excess / tab_count_same_width, width_to_remove_per_tab_max); for (int tab_n = 0; tab_n < tab_count_same_width; tab_n++) width_sort_buffer[tab_n].Width -= width_to_remove_per_tab; width_excess -= width_to_remove_per_tab * tab_count_same_width; } for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) tab_bar->Tabs[width_sort_buffer[tab_n].Index].Width = (float)(int)width_sort_buffer[tab_n].Width; } else { const float tab_max_width = TabBarCalcMaxTabWidth(); for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; tab->Width = ImMin(tab->WidthContents, tab_max_width); } } // Layout all active tabs float offset_x = 0.0f; for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; tab->Offset = offset_x; if (scroll_track_selected_tab_id == 0 && g.NavJustMovedToId == tab->ID) scroll_track_selected_tab_id = tab->ID; offset_x += tab->Width + g.Style.ItemInnerSpacing.x; } tab_bar->OffsetMax = ImMax(offset_x - g.Style.ItemInnerSpacing.x, 0.0f); tab_bar->OffsetNextTab = 0.0f; // Horizontal scrolling buttons const bool scrolling_buttons = (tab_bar->OffsetMax > tab_bar->BarRect.GetWidth() && tab_bar->Tabs.Size > 1) && !(tab_bar->Flags & ImGuiTabBarFlags_NoTabListScrollingButtons) && (tab_bar->Flags & ImGuiTabBarFlags_FittingPolicyScroll); if (scrolling_buttons) if (ImGuiTabItem* tab_to_select = TabBarScrollingButtons(tab_bar)) // NB: Will alter BarRect.Max.x! scroll_track_selected_tab_id = tab_bar->SelectedTabId = tab_to_select->ID; // If we have lost the selected tab, select the next most recently active one if (found_selected_tab_id == false) tab_bar->SelectedTabId = 0; if (tab_bar->SelectedTabId == 0 && tab_bar->NextSelectedTabId == 0 && most_recently_selected_tab != NULL) scroll_track_selected_tab_id = tab_bar->SelectedTabId = most_recently_selected_tab->ID; // Lock in visible tab tab_bar->VisibleTabId = tab_bar->SelectedTabId; tab_bar->VisibleTabWasSubmitted = false; // Update scrolling if (scroll_track_selected_tab_id) if (ImGuiTabItem* scroll_track_selected_tab = TabBarFindTabByID(tab_bar, scroll_track_selected_tab_id)) TabBarScrollToTab(tab_bar, scroll_track_selected_tab); tab_bar->ScrollingAnim = TabBarScrollClamp(tab_bar, tab_bar->ScrollingAnim); tab_bar->ScrollingTarget = TabBarScrollClamp(tab_bar, tab_bar->ScrollingTarget); if (tab_bar->ScrollingAnim != tab_bar->ScrollingTarget) { // Scrolling speed adjust itself so we can always reach our target in 1/3 seconds. // Teleport if we are aiming far off the visible line tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, 70.0f * g.FontSize); tab_bar->ScrollingSpeed = ImMax(tab_bar->ScrollingSpeed, ImFabs(tab_bar->ScrollingTarget - tab_bar->ScrollingAnim) / 0.3f); const bool teleport = (tab_bar->PrevFrameVisible + 1 < g.FrameCount) || (tab_bar->ScrollingTargetDistToVisibility > 10.0f * g.FontSize); tab_bar->ScrollingAnim = teleport ? tab_bar->ScrollingTarget : ImLinearSweep(tab_bar->ScrollingAnim, tab_bar->ScrollingTarget, g.IO.DeltaTime * tab_bar->ScrollingSpeed); } else { tab_bar->ScrollingSpeed = 0.0f; } // Clear name buffers if ((tab_bar->Flags & ImGuiTabBarFlags_DockNode) == 0) tab_bar->TabsNames.Buf.resize(0); } // Dockables uses Name/ID in the global namespace. Non-dockable items use the ID stack. static ImU32 ImGui::TabBarCalcTabID(ImGuiTabBar* tab_bar, const char* label) { if (tab_bar->Flags & ImGuiTabBarFlags_DockNode) { ImGuiID id = ImHashStr(label, 0); KeepAliveID(id); return id; } else { ImGuiWindow* window = GImGui->CurrentWindow; return window->GetID(label); } } static float ImGui::TabBarCalcMaxTabWidth() { ImGuiContext& g = *GImGui; return g.FontSize * 20.0f; } ImGuiTabItem* ImGui::TabBarFindTabByID(ImGuiTabBar* tab_bar, ImGuiID tab_id) { if (tab_id != 0) for (int n = 0; n < tab_bar->Tabs.Size; n++) if (tab_bar->Tabs[n].ID == tab_id) return &tab_bar->Tabs[n]; return NULL; } // The *TabId fields be already set by the docking system _before_ the actual TabItem was created, so we clear them regardless. void ImGui::TabBarRemoveTab(ImGuiTabBar* tab_bar, ImGuiID tab_id) { if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_id)) tab_bar->Tabs.erase(tab); if (tab_bar->VisibleTabId == tab_id) { tab_bar->VisibleTabId = 0; } if (tab_bar->SelectedTabId == tab_id) { tab_bar->SelectedTabId = 0; } if (tab_bar->NextSelectedTabId == tab_id) { tab_bar->NextSelectedTabId = 0; } } // Called on manual closure attempt void ImGui::TabBarCloseTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { if ((tab_bar->VisibleTabId == tab->ID) && !(tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) { // This will remove a frame of lag for selecting another tab on closure. // However we don't run it in the case where the 'Unsaved' flag is set, so user gets a chance to fully undo the closure tab->LastFrameVisible = -1; tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = 0; } else if ((tab_bar->VisibleTabId != tab->ID) && (tab->Flags & ImGuiTabItemFlags_UnsavedDocument)) { // Actually select before expecting closure tab_bar->NextSelectedTabId = tab->ID; } } static float ImGui::TabBarScrollClamp(ImGuiTabBar* tab_bar, float scrolling) { scrolling = ImMin(scrolling, tab_bar->OffsetMax - tab_bar->BarRect.GetWidth()); return ImMax(scrolling, 0.0f); } static void ImGui::TabBarScrollToTab(ImGuiTabBar* tab_bar, ImGuiTabItem* tab) { ImGuiContext& g = *GImGui; float margin = g.FontSize * 1.0f; // When to scroll to make Tab N+1 visible always make a bit of N visible to suggest more scrolling area (since we don't have a scrollbar) int order = tab_bar->GetTabOrder(tab); float tab_x1 = tab->Offset + (order > 0 ? -margin : 0.0f); float tab_x2 = tab->Offset + tab->Width + (order + 1 < tab_bar->Tabs.Size ? margin : 1.0f); tab_bar->ScrollingTargetDistToVisibility = 0.0f; if (tab_bar->ScrollingTarget > tab_x1) { tab_bar->ScrollingTargetDistToVisibility = ImMax(tab_bar->ScrollingAnim - tab_x2, 0.0f); tab_bar->ScrollingTarget = tab_x1; } else if (tab_bar->ScrollingTarget < tab_x2 - tab_bar->BarRect.GetWidth()) { tab_bar->ScrollingTargetDistToVisibility = ImMax((tab_x1 - tab_bar->BarRect.GetWidth()) - tab_bar->ScrollingAnim, 0.0f); tab_bar->ScrollingTarget = tab_x2 - tab_bar->BarRect.GetWidth(); } } void ImGui::TabBarQueueChangeTabOrder(ImGuiTabBar* tab_bar, const ImGuiTabItem* tab, int dir) { IM_ASSERT(dir == -1 || dir == +1); IM_ASSERT(tab_bar->ReorderRequestTabId == 0); tab_bar->ReorderRequestTabId = tab->ID; tab_bar->ReorderRequestDir = dir; } static ImGuiTabItem* ImGui::TabBarScrollingButtons(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; const ImVec2 arrow_button_size(g.FontSize - 2.0f, g.FontSize + g.Style.FramePadding.y * 2.0f); const float scrolling_buttons_width = arrow_button_size.x * 2.0f; const ImVec2 backup_cursor_pos = window->DC.CursorPos; //window->DrawList->AddRect(ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y), ImVec2(tab_bar->BarRect.Max.x, tab_bar->BarRect.Max.y), IM_COL32(255,0,0,255)); const ImRect avail_bar_rect = tab_bar->BarRect; bool want_clip_rect = !avail_bar_rect.Contains(ImRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(scrolling_buttons_width, 0.0f))); if (want_clip_rect) PushClipRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max + ImVec2(g.Style.ItemInnerSpacing.x, 0.0f), true); ImGuiTabItem* tab_to_select = NULL; int select_dir = 0; ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; arrow_col.w *= 0.5f; PushStyleColor(ImGuiCol_Text, arrow_col); PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); const float backup_repeat_delay = g.IO.KeyRepeatDelay; const float backup_repeat_rate = g.IO.KeyRepeatRate; g.IO.KeyRepeatDelay = 0.250f; g.IO.KeyRepeatRate = 0.200f; window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width, tab_bar->BarRect.Min.y); if (ArrowButtonEx("##<", ImGuiDir_Left, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat)) select_dir = -1; window->DC.CursorPos = ImVec2(tab_bar->BarRect.Max.x - scrolling_buttons_width + arrow_button_size.x, tab_bar->BarRect.Min.y); if (ArrowButtonEx("##>", ImGuiDir_Right, arrow_button_size, ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_Repeat)) select_dir = +1; PopStyleColor(2); g.IO.KeyRepeatRate = backup_repeat_rate; g.IO.KeyRepeatDelay = backup_repeat_delay; if (want_clip_rect) PopClipRect(); if (select_dir != 0) if (ImGuiTabItem* tab_item = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId)) { int selected_order = tab_bar->GetTabOrder(tab_item); int target_order = selected_order + select_dir; tab_to_select = &tab_bar->Tabs[(target_order >= 0 && target_order < tab_bar->Tabs.Size) ? target_order : selected_order]; // If we are at the end of the list, still scroll to make our tab visible } window->DC.CursorPos = backup_cursor_pos; tab_bar->BarRect.Max.x -= scrolling_buttons_width + 1.0f; return tab_to_select; } static ImGuiTabItem* ImGui::TabBarTabListPopupButton(ImGuiTabBar* tab_bar) { ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; // We use g.Style.FramePadding.y to match the square ArrowButton size const float tab_list_popup_button_width = g.FontSize + g.Style.FramePadding.y; const ImVec2 backup_cursor_pos = window->DC.CursorPos; window->DC.CursorPos = ImVec2(tab_bar->BarRect.Min.x - g.Style.FramePadding.y, tab_bar->BarRect.Min.y); tab_bar->BarRect.Min.x += tab_list_popup_button_width; ImVec4 arrow_col = g.Style.Colors[ImGuiCol_Text]; arrow_col.w *= 0.5f; PushStyleColor(ImGuiCol_Text, arrow_col); PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0)); bool open = BeginCombo("##v", NULL, ImGuiComboFlags_NoPreview); PopStyleColor(2); ImGuiTabItem* tab_to_select = NULL; if (open) { for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_n]; const char* tab_name = tab_bar->GetTabName(tab); if (Selectable(tab_name, tab_bar->SelectedTabId == tab->ID)) tab_to_select = tab; } EndCombo(); } window->DC.CursorPos = backup_cursor_pos; return tab_to_select; } //------------------------------------------------------------------------- // [SECTION] Widgets: BeginTabItem, EndTabItem, etc. //------------------------------------------------------------------------- // [BETA API] API may evolve! This code has been extracted out of the Docking branch, // and some of the construct which are not used in Master may be left here to facilitate merging. //------------------------------------------------------------------------- // - BeginTabItem() // - EndTabItem() // - TabItemEx() [Internal] // - SetTabItemClosed() // - TabItemCalcSize() [Internal] // - TabItemBackground() [Internal] // - TabItemLabelAndCloseButton() [Internal] //------------------------------------------------------------------------- bool ImGui::BeginTabItem(const char* label, bool* p_open, ImGuiTabItemFlags flags) { ImGuiContext& g = *GImGui; if (g.CurrentWindow->SkipItems) return false; ImGuiTabBar* tab_bar = g.CurrentTabBar; if (tab_bar == NULL) { IM_ASSERT(tab_bar && "Needs to be called between BeginTabBar() and EndTabBar()!"); return false; // FIXME-ERRORHANDLING } bool ret = TabItemEx(tab_bar, label, p_open, flags); if (ret && !(flags & ImGuiTabItemFlags_NoPushId)) { ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; g.CurrentWindow->IDStack.push_back(tab->ID); // We already hashed 'label' so push into the ID stack directly instead of doing another hash through PushID(label) } return ret; } void ImGui::EndTabItem() { ImGuiContext& g = *GImGui; if (g.CurrentWindow->SkipItems) return; ImGuiTabBar* tab_bar = g.CurrentTabBar; if (tab_bar == NULL) { IM_ASSERT(tab_bar != NULL && "Needs to be called between BeginTabBar() and EndTabBar()!"); return; } IM_ASSERT(tab_bar->LastTabItemIdx >= 0); ImGuiTabItem* tab = &tab_bar->Tabs[tab_bar->LastTabItemIdx]; if (!(tab->Flags & ImGuiTabItemFlags_NoPushId)) g.CurrentWindow->IDStack.pop_back(); } bool ImGui::TabItemEx(ImGuiTabBar* tab_bar, const char* label, bool* p_open, ImGuiTabItemFlags flags) { // Layout whole tab bar if not already done if (tab_bar->WantLayout) TabBarLayout(tab_bar); ImGuiContext& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = TabBarCalcTabID(tab_bar, label); // If the user called us with *p_open == false, we early out and don't render. We make a dummy call to ItemAdd() so that attempts to use a contextual popup menu with an implicit ID won't use an older ID. if (p_open && !*p_open) { PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true); ItemAdd(ImRect(), id); PopItemFlag(); return false; } // Calculate tab contents size ImVec2 size = TabItemCalcSize(label, p_open != NULL); // Acquire tab data ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, id); bool tab_is_new = false; if (tab == NULL) { tab_bar->Tabs.push_back(ImGuiTabItem()); tab = &tab_bar->Tabs.back(); tab->ID = id; tab->Width = size.x; tab_is_new = true; } tab_bar->LastTabItemIdx = (short)tab_bar->Tabs.index_from_ptr(tab); tab->WidthContents = size.x; if (p_open == NULL) flags |= ImGuiTabItemFlags_NoCloseButton; const bool tab_bar_appearing = (tab_bar->PrevFrameVisible + 1 < g.FrameCount); const bool tab_bar_focused = (tab_bar->Flags & ImGuiTabBarFlags_IsFocused) != 0; const bool tab_appearing = (tab->LastFrameVisible + 1 < g.FrameCount); tab->LastFrameVisible = g.FrameCount; tab->Flags = flags; // Append name with zero-terminator tab->NameOffset = tab_bar->TabsNames.size(); tab_bar->TabsNames.append(label, label + strlen(label) + 1); // If we are not reorderable, always reset offset based on submission order. // (We already handled layout and sizing using the previous known order, but sizing is not affected by order!) if (!tab_appearing && !(tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) { tab->Offset = tab_bar->OffsetNextTab; tab_bar->OffsetNextTab += tab->Width + g.Style.ItemInnerSpacing.x; } // Update selected tab if (tab_appearing && (tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs) && tab_bar->NextSelectedTabId == 0) if (!tab_bar_appearing || tab_bar->SelectedTabId == 0) tab_bar->NextSelectedTabId = id; // New tabs gets activated if ((flags & ImGuiTabItemFlags_SetSelected) && (tab_bar->SelectedTabId != id)) // SetSelected can only be passed on explicit tab bar tab_bar->NextSelectedTabId = id; // Lock visibility bool tab_contents_visible = (tab_bar->VisibleTabId == id); if (tab_contents_visible) tab_bar->VisibleTabWasSubmitted = true; // On the very first frame of a tab bar we let first tab contents be visible to minimize appearing glitches if (!tab_contents_visible && tab_bar->SelectedTabId == 0 && tab_bar_appearing) if (tab_bar->Tabs.Size == 1 && !(tab_bar->Flags & ImGuiTabBarFlags_AutoSelectNewTabs)) tab_contents_visible = true; if (tab_appearing && !(tab_bar_appearing && !tab_is_new)) { PushItemFlag(ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus, true); ItemAdd(ImRect(), id); PopItemFlag(); return tab_contents_visible; } if (tab_bar->SelectedTabId == id) tab->LastFrameSelected = g.FrameCount; // Backup current layout position const ImVec2 backup_main_cursor_pos = window->DC.CursorPos; // Layout size.x = tab->Width; window->DC.CursorPos = tab_bar->BarRect.Min + ImVec2((float)(int)tab->Offset - tab_bar->ScrollingAnim, 0.0f); ImVec2 pos = window->DC.CursorPos; ImRect bb(pos, pos + size); // We don't have CPU clipping primitives to clip the CloseButton (until it becomes a texture), so need to add an extra draw call (temporary in the case of vertical animation) bool want_clip_rect = (bb.Min.x < tab_bar->BarRect.Min.x) || (bb.Max.x >= tab_bar->BarRect.Max.x); if (want_clip_rect) PushClipRect(ImVec2(ImMax(bb.Min.x, tab_bar->BarRect.Min.x), bb.Min.y - 1), ImVec2(tab_bar->BarRect.Max.x, bb.Max.y), true); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, id)) { if (want_clip_rect) PopClipRect(); window->DC.CursorPos = backup_main_cursor_pos; return tab_contents_visible; } // Click to Select a tab ImGuiButtonFlags button_flags = (ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_AllowItemOverlap); if (g.DragDropActive) button_flags |= ImGuiButtonFlags_PressedOnDragDropHold; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags); if (pressed) tab_bar->NextSelectedTabId = id; hovered |= (g.HoveredId == id); // Allow the close button to overlap unless we are dragging (in which case we don't want any overlapping tabs to be hovered) if (!held) SetItemAllowOverlap(); // Drag and drop: re-order tabs if (held && !tab_appearing && IsMouseDragging(0)) { if (!g.DragDropActive && (tab_bar->Flags & ImGuiTabBarFlags_Reorderable)) { // While moving a tab it will jump on the other side of the mouse, so we also test for MouseDelta.x if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < bb.Min.x) { if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) TabBarQueueChangeTabOrder(tab_bar, tab, -1); } else if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > bb.Max.x) { if (tab_bar->Flags & ImGuiTabBarFlags_Reorderable) TabBarQueueChangeTabOrder(tab_bar, tab, +1); } } } #if 0 if (hovered && g.HoveredIdNotActiveTimer > 0.50f && bb.GetWidth() < tab->WidthContents) { // Enlarge tab display when hovering bb.Max.x = bb.Min.x + (float)(int)ImLerp(bb.GetWidth(), tab->WidthContents, ImSaturate((g.HoveredIdNotActiveTimer - 0.40f) * 6.0f)); display_draw_list = GetForegroundDrawList(window); TabItemBackground(display_draw_list, bb, flags, GetColorU32(ImGuiCol_TitleBgActive)); } #endif // Render tab shape ImDrawList* display_draw_list = window->DrawList; const ImU32 tab_col = GetColorU32((held || hovered) ? ImGuiCol_TabHovered : tab_contents_visible ? (tab_bar_focused ? ImGuiCol_TabActive : ImGuiCol_TabUnfocusedActive) : (tab_bar_focused ? ImGuiCol_Tab : ImGuiCol_TabUnfocused)); TabItemBackground(display_draw_list, bb, flags, tab_col); RenderNavHighlight(bb, id); // Select with right mouse button. This is so the common idiom for context menu automatically highlight the current widget. const bool hovered_unblocked = IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup); if (hovered_unblocked && (IsMouseClicked(1) || IsMouseReleased(1))) tab_bar->NextSelectedTabId = id; if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton) flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton; // Render tab label, process close button const ImGuiID close_button_id = p_open ? window->GetID((void*)((intptr_t)id + 1)) : 0; bool just_closed = TabItemLabelAndCloseButton(display_draw_list, bb, flags, tab_bar->FramePadding, label, id, close_button_id); if (just_closed && p_open != NULL) { *p_open = false; TabBarCloseTab(tab_bar, tab); } // Restore main window position so user can draw there if (want_clip_rect) PopClipRect(); window->DC.CursorPos = backup_main_cursor_pos; // Tooltip (FIXME: Won't work over the close button because ItemOverlap systems messes up with HoveredIdTimer) // We test IsItemHovered() to discard e.g. when another item is active or drag and drop over the tab bar (which g.HoveredId ignores) if (g.HoveredId == id && !held && g.HoveredIdNotActiveTimer > 0.50f && IsItemHovered()) if (!(tab_bar->Flags & ImGuiTabBarFlags_NoTooltip)) SetTooltip("%.*s", (int)(FindRenderedTextEnd(label) - label), label); return tab_contents_visible; } // [Public] This is call is 100% optional but it allows to remove some one-frame glitches when a tab has been unexpectedly removed. // To use it to need to call the function SetTabItemClosed() after BeginTabBar() and before any call to BeginTabItem() void ImGui::SetTabItemClosed(const char* label) { ImGuiContext& g = *GImGui; bool is_within_manual_tab_bar = g.CurrentTabBar && !(g.CurrentTabBar->Flags & ImGuiTabBarFlags_DockNode); if (is_within_manual_tab_bar) { ImGuiTabBar* tab_bar = g.CurrentTabBar; IM_ASSERT(tab_bar->WantLayout); // Needs to be called AFTER BeginTabBar() and BEFORE the first call to BeginTabItem() ImGuiID tab_id = TabBarCalcTabID(tab_bar, label); TabBarRemoveTab(tab_bar, tab_id); } } ImVec2 ImGui::TabItemCalcSize(const char* label, bool has_close_button) { ImGuiContext& g = *GImGui; ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 size = ImVec2(label_size.x + g.Style.FramePadding.x, label_size.y + g.Style.FramePadding.y * 2.0f); if (has_close_button) size.x += g.Style.FramePadding.x + (g.Style.ItemInnerSpacing.x + g.FontSize); // We use Y intentionally to fit the close button circle. else size.x += g.Style.FramePadding.x + 1.0f; return ImVec2(ImMin(size.x, TabBarCalcMaxTabWidth()), size.y); } void ImGui::TabItemBackground(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImU32 col) { // While rendering tabs, we trim 1 pixel off the top of our bounding box so they can fit within a regular frame height while looking "detached" from it. ImGuiContext& g = *GImGui; const float width = bb.GetWidth(); IM_UNUSED(flags); IM_ASSERT(width > 0.0f); const float rounding = ImMax(0.0f, ImMin(g.Style.TabRounding, width * 0.5f - 1.0f)); const float y1 = bb.Min.y + 1.0f; const float y2 = bb.Max.y - 1.0f; draw_list->PathLineTo(ImVec2(bb.Min.x, y2)); draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding, y1 + rounding), rounding, 6, 9); draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding, y1 + rounding), rounding, 9, 12); draw_list->PathLineTo(ImVec2(bb.Max.x, y2)); draw_list->PathFillConvex(col); if (g.Style.TabBorderSize > 0.0f) { draw_list->PathLineTo(ImVec2(bb.Min.x + 0.5f, y2)); draw_list->PathArcToFast(ImVec2(bb.Min.x + rounding + 0.5f, y1 + rounding + 0.5f), rounding, 6, 9); draw_list->PathArcToFast(ImVec2(bb.Max.x - rounding - 0.5f, y1 + rounding + 0.5f), rounding, 9, 12); draw_list->PathLineTo(ImVec2(bb.Max.x - 0.5f, y2)); draw_list->PathStroke(GetColorU32(ImGuiCol_Border), false, g.Style.TabBorderSize); } } // Render text label (with custom clipping) + Unsaved Document marker + Close Button logic // We tend to lock style.FramePadding for a given tab-bar, hence the 'frame_padding' parameter. bool ImGui::TabItemLabelAndCloseButton(ImDrawList* draw_list, const ImRect& bb, ImGuiTabItemFlags flags, ImVec2 frame_padding, const char* label, ImGuiID tab_id, ImGuiID close_button_id) { ImGuiContext& g = *GImGui; ImVec2 label_size = CalcTextSize(label, NULL, true); if (bb.GetWidth() <= 1.0f) return false; // Render text label (with clipping + alpha gradient) + unsaved marker const char* TAB_UNSAVED_MARKER = "*"; ImRect text_pixel_clip_bb(bb.Min.x + frame_padding.x, bb.Min.y + frame_padding.y, bb.Max.x - frame_padding.x, bb.Max.y); if (flags & ImGuiTabItemFlags_UnsavedDocument) { text_pixel_clip_bb.Max.x -= CalcTextSize(TAB_UNSAVED_MARKER, NULL, false).x; ImVec2 unsaved_marker_pos(ImMin(bb.Min.x + frame_padding.x + label_size.x + 2, text_pixel_clip_bb.Max.x), bb.Min.y + frame_padding.y + (float)(int)(-g.FontSize * 0.25f)); RenderTextClippedEx(draw_list, unsaved_marker_pos, bb.Max - frame_padding, TAB_UNSAVED_MARKER, NULL, NULL); } ImRect text_ellipsis_clip_bb = text_pixel_clip_bb; // Close Button // We are relying on a subtle and confusing distinction between 'hovered' and 'g.HoveredId' which happens because we are using ImGuiButtonFlags_AllowOverlapMode + SetItemAllowOverlap() // 'hovered' will be true when hovering the Tab but NOT when hovering the close button // 'g.HoveredId==id' will be true when hovering the Tab including when hovering the close button // 'g.ActiveId==close_button_id' will be true when we are holding on the close button, in which case both hovered booleans are false bool close_button_pressed = false; bool close_button_visible = false; if (close_button_id != 0) if (g.HoveredId == tab_id || g.HoveredId == close_button_id || g.ActiveId == close_button_id) close_button_visible = true; if (close_button_visible) { ImGuiItemHoveredDataBackup last_item_backup; const float close_button_sz = g.FontSize * 0.5f; if (CloseButton(close_button_id, ImVec2(bb.Max.x - frame_padding.x - close_button_sz, bb.Min.y + frame_padding.y + close_button_sz), close_button_sz)) close_button_pressed = true; last_item_backup.Restore(); // Close with middle mouse button if (!(flags & ImGuiTabItemFlags_NoCloseWithMiddleMouseButton) && IsMouseClicked(2)) close_button_pressed = true; text_pixel_clip_bb.Max.x -= close_button_sz * 2.0f; } // Label with ellipsis // FIXME: This should be extracted into a helper but the use of text_pixel_clip_bb and !close_button_visible makes it tricky to abstract at the moment const char* label_display_end = FindRenderedTextEnd(label); if (label_size.x > text_ellipsis_clip_bb.GetWidth()) { const int ellipsis_dot_count = 3; const float ellipsis_width = (1.0f + 1.0f) * ellipsis_dot_count - 1.0f; const char* label_end = NULL; float label_size_clipped_x = g.Font->CalcTextSizeA(g.FontSize, text_ellipsis_clip_bb.GetWidth() - ellipsis_width + 1.0f, 0.0f, label, label_display_end, &label_end).x; if (label_end == label && label_end < label_display_end) // Always display at least 1 character if there's no room for character + ellipsis { label_end = label + ImTextCountUtf8BytesFromChar(label, label_display_end); label_size_clipped_x = g.Font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, label, label_end).x; } while (label_end > label && ImCharIsBlankA(label_end[-1])) // Trim trailing space { label_end--; label_size_clipped_x -= g.Font->CalcTextSizeA(g.FontSize, FLT_MAX, 0.0f, label_end, label_end + 1).x; // Ascii blanks are always 1 byte } RenderTextClippedEx(draw_list, text_pixel_clip_bb.Min, text_pixel_clip_bb.Max, label, label_end, &label_size, ImVec2(0.0f, 0.0f)); const float ellipsis_x = text_pixel_clip_bb.Min.x + label_size_clipped_x + 1.0f; if (!close_button_visible && ellipsis_x + ellipsis_width <= bb.Max.x) RenderPixelEllipsis(draw_list, ImVec2(ellipsis_x, text_pixel_clip_bb.Min.y), ellipsis_dot_count, GetColorU32(ImGuiCol_Text)); } else { RenderTextClippedEx(draw_list, text_pixel_clip_bb.Min, text_pixel_clip_bb.Max, label, label_display_end, &label_size, ImVec2(0.0f, 0.0f)); } return close_button_pressed; }
jing-interactive/Cinder-portfolio
blocks/yocto-gl/libs/yocto_gui/ext/imgui/imgui_widgets.cpp
C++
mit
326,003
var jshint = require('jshint').JSHINT, colors = require('colors'); module.exports = function(code) { var options = { devel: true, node: true, predef: ['expect', 'done'], undef: true }, isValid = jshint(code, options); if (!isValid) { var errorsByLineNumber = {}; jshint.errors.map(function(error) { errorsByLineNumber[error.line] = error.reason; }); code.split('\n').forEach(function(line, index) { var lineNumber = index + 1; if (errorsByLineNumber[lineNumber]) { line = line.yellow + '\t' + ('// ERROR: ' + errorsByLineNumber[lineNumber]).red } console.log(line); }); } return isValid; };
cymen/literate-jasmine
src/linter.js
JavaScript
mit
697
#region COPYRIGHT© 2009-2014 Phillip Clark. All rights reserved. // For licensing information see License.txt (MIT style licensing). #endregion using System.Configuration; using System.Reflection; using System.Text.RegularExpressions; namespace FlitBit.Wireup.Configuration { /// <summary> /// Determines how wireup ignore configuration elements are processed. /// </summary> public enum WireupIgnoreStrategy { /// <summary> /// Default behavior: matches. /// </summary> Default = 0, /// <summary> /// Indicates the assemby name should be matched using regex. /// </summary> Regex = 0, /// <summary> /// Indicates the assembly name is a match if it begins with the given value. /// </summary> StartsWith = 1, /// <summary> /// Indicates the assembly name is a match if it ends with the given value. /// </summary> EndsWith = 2, /// <summary> /// Indicates the assembly name must match exactly. /// </summary> Exact = 3 } /// <summary> /// Configuration element for assemblies to ignore during wireup. /// </summary> public class WireupIgnoreConfigurationElement : ConfigurationElement { const string PropertyNameAssembly = "match"; const string PropertyNameStrategy = "strategy"; /// <summary> /// Assembly match specification. /// </summary> [ConfigurationProperty(PropertyNameAssembly , IsKey = true , IsRequired = true)] public string AssemblyMatchSpec { get { return (string) this[PropertyNameAssembly]; } set { this[PropertyNameAssembly] = value; } } /// <summary> /// The strategy used when checking whether assemblies match /// </summary> [ConfigurationProperty(PropertyNameStrategy, DefaultValue = WireupIgnoreStrategy.Regex)] public WireupIgnoreStrategy Strategy { get { return (WireupIgnoreStrategy) this[PropertyNameStrategy]; } set { this[PropertyNameStrategy] = value; } } internal bool Matches(Assembly asm) { if (asm == null) { return false; } var name = asm.FullName; switch (Strategy) { case WireupIgnoreStrategy.StartsWith: return name.StartsWith(AssemblyMatchSpec); case WireupIgnoreStrategy.EndsWith: return name.EndsWith(AssemblyMatchSpec); default: var dmatch = Regex.Match(name, AssemblyMatchSpec, RegexOptions.IgnoreCase); return dmatch.Success; } } } }
flitbit-org/fbwireup
FlitBit.Wireup/Configuration/WireupIgnoreConfigurationElement.cs
C#
mit
2,356
package com.Android_UI; import java.util.ArrayList; import android.os.Handler; import android.os.Message; public class XliCppThreadHandler extends Handler { public static final int REPEATING_MESSAGE = 10; private int repeatCount = 0; private ArrayList<Integer> repeatingMessageIndex; private int xliCallbackIndex = -2; public XliCppThreadHandler() { super(); repeatingMessageIndex = new ArrayList<Integer>(); xliCallbackIndex = registerRepeating(50); } @Override public void handleMessage(Message msg) { switch (msg.what) { case REPEATING_MESSAGE: handleRepeating(msg); break; default: break; } } private void handleRepeating(Message msg) { if (msg.arg1 == xliCallbackIndex) { com.Android_UI.ActivityNativeEntryPoints.cppTimerCallback(msg.arg1); // {TODO} this should own callback Message newMsg = Message.obtain(); newMsg.what = msg.what; newMsg.arg1 = msg.arg1; newMsg.arg2 = msg.arg2; this.sendMessageDelayed(newMsg, msg.arg2); } else if (repeatingMessageIndex.contains((Integer)msg.arg1)) { com.Android_UI.ActivityNativeEntryPoints.cppTimerCallback(msg.arg1); this.sendMessageDelayed(msg, msg.arg2); } } public void unregisterRepeating(int repeater_id) { repeatingMessageIndex.remove((Integer)repeater_id); } public int registerRepeating(int millisecondsDelay) { int i = repeatCount+=1; repeatingMessageIndex.add(i); Message msg = Message.obtain(); msg.what = REPEATING_MESSAGE; msg.arg1 = i; msg.arg2 = millisecondsDelay; this.sendMessageDelayed(msg, millisecondsDelay); return i; } }
blyk/BlackCode-Fuse
AndroidUI/.build/Simulator/Android/src/com/Android_UI/XliCppThreadHandler.java
Java
mit
1,601
from setuptools import setup, find_packages setup( name="simple-crawler", version="0.1", url="https://github.com/shonenada/crawler", author="shonenada", author_email="shonenada@gmail.com", description="Simple crawler", zip_safe=True, platforms="any", packages=find_packages(), install_requires=["requests==2.2.1"], )
shonenada/crawler
setup.py
Python
mit
359
import org.apache.lucene.queryparser.classic.QueryParser; public class QueryParserEscape { public static void main(String[] args) { String input = "(1+1):2"; System.out.println(QueryParser.escape(input)); } }
kazuhira-r/lucene-examples
lucene-classic-query-parser/src/main/java/QueryParserEscape.java
Java
mit
233
<?php namespace Amber\Event\Parse; /** * Regex Parser * * Parses Regular Expressions * * @author Benjamin J. Anderson <andeb2804@gmail.com> * @package Amber\Event\Parse * @since Nov 4th, 2015 * @version v0.1 */ class Regex { protected $route; protected $regex; protected $matches; public function match( $route, $path ) { $this->route = $route; $this->regex = $this->route->path; $this->setRegexOptionalParams(); $this->setRegexParams(); $this->setRegexWildcard(); $this->regex = '#^' . $this->regex . '$#'; return preg_match($this->regex, $path, $this->matches); } public function getMatches() { return $this->matches; } protected function setRegexOptionalParams() { preg_match('#{/([a-z][a-zA-Z0-9_,]*)}#', $this->regex, $matches); if ($matches) { $repl = $this->getRegexOptionalParamsReplacement($matches[1]); $this->regex = str_replace($matches[0], $repl, $this->regex); } } protected function getRegexOptionalParamsReplacement( $list ) { $list = explode(',', $list); $head = $this->getRegexOptionalParamsReplacementHead($list); $tail = ''; foreach ($list as $name) { $head .= "(/{{$name}}"; $tail .= ')?'; } return $head . $tail; } protected function getRegexOptionalParamsReplacementHead( &$list ) { $head = ''; if (substr($this->regex, 0, 2) == '{/') { $name = array_shift($list); $head = "/({{$name}})?"; } return $head; } protected function setRegexParams() { $find = '#{([a-z][a-zA-Z0-9_]*)}#'; preg_match_all($find, $this->regex, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $name = $match[1]; $subpattern = $this->getSubpattern($name); $this->regex = str_replace("{{$name}}", $subpattern, $this->regex); if (! isset($this->route->values[$name])) { $this->route->addValues(array($name => null)); } } } protected function getSubpattern( $name ) { if (isset($this->route->tokens[$name])) { return "(?P<{$name}>{$this->route->tokens[$name]})"; } return "(?P<{$name}>[^/]+)"; } protected function setRegexWildcard() { if (! $this->route->wildcard) { return; } $this->regex = rtrim($this->regex, '/') . "(/(?P<{$this->route->wildcard}>.*))?"; } }
Vandise/Amber
amber/event/src/parse/regex.php
PHP
mit
2,433
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SiteMapDemo { public partial class About : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } } }
idoychinov/Telerik_Academy_Homework
ASP.NETWeb Forms/9.NavigationAndSitemaps/SiteMapDemo/About.aspx.cs
C#
mit
314
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | http://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'www'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE;
rick99856/loginnew
application/config/routes.php
PHP
mit
1,965
package com.thirtydays.pushservice.receiver; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.util.Log; import com.thirtydays.pushservice.PushManager; import com.thirtydays.pushservice.constant.PushConstant; import com.thirtydays.pushservice.entity.PushMessage; import com.xiaomi.mipush.sdk.ErrorCode; import com.xiaomi.mipush.sdk.MiPushClient; import com.xiaomi.mipush.sdk.MiPushCommandMessage; import com.xiaomi.mipush.sdk.MiPushMessage; import com.xiaomi.mipush.sdk.PushMessageReceiver; import com.xiaomi.push.service.XMJobService; import java.util.List; /** * Created by yanchengmeng on 2016/12/14. * 小米推送消息接收器 */ public class XMMessageReceiver extends PushMessageReceiver { private final static String TAG = XMMessageReceiver.class.getSimpleName(); @Override public void onNotificationMessageClicked(Context context, MiPushMessage miPushMessage) { Log.e(TAG, "onNotificationMessageClicked"); PushMessage pushMessage = new PushMessage(); pushMessage.setExtras(miPushMessage.getExtra()); pushMessage.setTitle(miPushMessage.getTitle()); // 传输数据从content取 pushMessage.setDesc(miPushMessage.getDescription()); pushMessage.setMsgId(miPushMessage.getMessageId()); if (PushManager.getInstance().getMessageHandler() != null) { PushManager.getInstance().getMessageHandler().setOriginalMessage(miPushMessage.toBundle().toString()); PushManager.getInstance().getMessageHandler().onNotificationClicked(context, pushMessage); } } /** * 推送消息收到后立即触发 * @param context * @param miPushMessage */ @Override public void onNotificationMessageArrived(Context context, MiPushMessage miPushMessage) { Log.e(TAG, "onNotificationMessageArrived."); super.onNotificationMessageArrived(context, miPushMessage); // PushMessage pushMessage = new PushMessage(); // pushMessage.setExtras(miPushMessage.getExtra()); // pushMessage.setTitle(miPushMessage.getTitle()); // // 传输数据从content取 // pushMessage.setDesc(miPushMessage.getDescription()); // pushMessage.setMsgId(miPushMessage.getMessageId()); // pushMessage.setNotifyId(miPushMessage.getNotifyId()); // // if (PushManager.getInstance().getMessageHandler() != null) { // PushManager.getInstance().getMessageHandler().setOriginalMessage(miPushMessage.toBundle().toString()); // PushManager.getInstance().getMessageHandler().onNotificationClicked(context, pushMessage); // } } @Override public void onReceiveRegisterResult(Context context, MiPushCommandMessage miPushCommandMessage) { String command = miPushCommandMessage.getCommand(); Log.e(TAG, "onReceiveRegisterResult:" + command); List<String> arguments = miPushCommandMessage.getCommandArguments(); String cmdArg1 = ((arguments != null && arguments.size() > 0) ? arguments.get(0) : null); String cmdArg2 = ((arguments != null && arguments.size() > 1) ? arguments.get(1) : null); if (MiPushClient.COMMAND_REGISTER.equals(command)) { if (miPushCommandMessage.getResultCode() == ErrorCode.SUCCESS) { Log.i(TAG, "Regist XIAOMI push token success. token:" + cmdArg1); // 通知推送token Intent intent = new Intent (PushConstant.PUSH_TOKEN_CHANGED); intent.putExtra(PushConstant.PUSH_TOKEN, cmdArg1); context.sendBroadcast(intent); } else { // 注册失败就用友盟推送:小米推送会因为系统时间错误导致注册失败 Intent intent = new Intent(PushConstant.PUSH_SERVICE_INIT_FAIL_ACTION); context.sendBroadcast(intent); // TODO 上报bugly // CrashReport.postCatchedException(new Exception(miPushCommandMessage.getReason())); } } } /** * 处理透传消息 * * @param context * @param miPushMessage */ @Override public void onReceivePassThroughMessage(Context context, MiPushMessage miPushMessage) { Log.e(TAG, "onReceivePassThroughMessage-----"); Log.e(TAG, "miPushMessage:" + miPushMessage.toString()); // 取自定义消息内容 PushMessage pushMessage = new PushMessage(); pushMessage.setMsgId(miPushMessage.getMessageId()); pushMessage.setDesc(miPushMessage.getDescription()); pushMessage.setCustom(miPushMessage.getContent()); pushMessage.setExtras(miPushMessage.getExtra()); // 处理消息 if (null != pushMessage && PushManager.getInstance().getMessageHandler() != null) { PushManager.getInstance().getMessageHandler().setOriginalMessage(miPushMessage.toBundle().toString()); PushManager.getInstance().getMessageHandler().onReceiveMessage(context, pushMessage); } pushMessage.setExtras(miPushMessage.getExtra()); } @Override public void onCommandResult(Context context, MiPushCommandMessage miPushCommandMessage) { String command = miPushCommandMessage.getCommand(); Log.e(TAG, "onCommandResult:" + command + ", resultCode:" + miPushCommandMessage.getResultCode() + ", reason:" + miPushCommandMessage.getReason()); } @Override public void onReceiveMessage(Context context, MiPushMessage miPushMessage) { Log.e(TAG, "onReceiveMessage"); super.onReceiveMessage(context, miPushMessage); } }
30days-tech/android
公共组件/pushservice/src/main/java/com/thirtydays/pushservice/receiver/XMMessageReceiver.java
Java
mit
5,685
package test.matcher; import static hu.interconnect.util.DateUtils.parseNap; import java.util.Date; import org.hamcrest.CoreMatchers; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.core.IsAnything; import hu.interconnect.hr.backend.api.dto.SzabadsagFelhasznalasResponseDTO; import hu.interconnect.hr.backend.api.enumeration.FelhasznaltSzabadnapJelleg; import test.matcher.AbstractTypeSafeDiagnosingMatcher; public class SzabadsagFelhasznalasResponseDTOMatcher extends AbstractTypeSafeDiagnosingMatcher<SzabadsagFelhasznalasResponseDTO> { private Matcher<Integer> tsz = new IsAnything<>(); private Matcher<Date> kezdet = new IsAnything<>(); private Matcher<Date> veg = new IsAnything<>(); private Matcher<FelhasznaltSzabadnapJelleg> jelleg = new IsAnything<>(); private Matcher<Integer> munkanapokSzama = new IsAnything<>(); public SzabadsagFelhasznalasResponseDTOMatcher tsz(Integer tsz) { this.tsz = CoreMatchers.is(tsz); return this; } public SzabadsagFelhasznalasResponseDTOMatcher kezdet(Matcher<Date> kezdet) { this.kezdet = kezdet; return this; } public SzabadsagFelhasznalasResponseDTOMatcher kezdet(String kezdetStr) { this.kezdet = CoreMatchers.is(parseNap(kezdetStr)); return this; } public SzabadsagFelhasznalasResponseDTOMatcher veg(Matcher<Date> veg) { this.veg = veg; return this; } public SzabadsagFelhasznalasResponseDTOMatcher veg(String vegStr) { this.veg = CoreMatchers.is(parseNap(vegStr)); return this; } public SzabadsagFelhasznalasResponseDTOMatcher jelleg(FelhasznaltSzabadnapJelleg jelleg) { this.jelleg = CoreMatchers.is(jelleg); return this; } public SzabadsagFelhasznalasResponseDTOMatcher munkanapokSzama(Integer munkanapokSzama) { this.munkanapokSzama = CoreMatchers.is(munkanapokSzama); return this; } @Override protected boolean matchesSafely(SzabadsagFelhasznalasResponseDTO item, Description mismatchDescription) { return matches(tsz, item.tsz, "tsz value: ", mismatchDescription) && matches(kezdet, item.kezdet, "kezdet value: ", mismatchDescription) && matches(veg, item.veg, "veg value: ", mismatchDescription) && matches(jelleg, item.jelleg, "jelleg value: ", mismatchDescription) && matches(munkanapokSzama, item.munkanapokSzama, "munkanapokSzama value: ", mismatchDescription); } @Override public void describeTo(Description description) { description.appendText(SzabadsagFelhasznalasResponseDTO.class.getSimpleName()) .appendText(", tsz: ").appendDescriptionOf(tsz) .appendText(", kezdet: ").appendDescriptionOf(kezdet) .appendText(", veg: ").appendDescriptionOf(veg) .appendText(", jelleg: ").appendDescriptionOf(jelleg) .appendText(", munkanapokSzama: ").appendDescriptionOf(munkanapokSzama); } }
tornaia/hr2
hr2-java-parent/hr2-backend-api/src/test/java/test/matcher/SzabadsagFelhasznalasResponseDTOMatcher.java
Java
mit
2,803
using Abp.Application.Services; using Abp.Authorization; using MyLearn.Common.Application.Roles.Dtos; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace MyLearn.Common.Application.Roles { public interface IPlmRoleAppService : IApplicationService { Task<PlmRoleCreateOutput> CreateRole(PlmRoleCreateInput input); } }
oceanho/aspnetboilerplate
samples/MyLearn.Common/Application/Roles/IPlmRoleAppService.cs
C#
mit
396
/** * ghostHunter - 0.4.0 * Copyright (C) 2014 Jamal Neufeld (jamal@i11u.me) * MIT Licensed * @license */ (function( $ ) { /* Include the Lunr library */ var lunr=require('./lunr.min.js'); //This is the main plugin definition $.fn.ghostHunter = function( options ) { //Here we use jQuery's extend to set default values if they weren't set by the user var opts = $.extend( {}, $.fn.ghostHunter.defaults, options ); if( opts.results ) { pluginMethods.init( this , opts ); return pluginMethods; } }; $.fn.ghostHunter.defaults = { resultsData : false, onPageLoad : true, onKeyUp : false, result_template : "<a href='{{link}}'><p><h2>{{title}}</h2><h4>{{prettyPubDate}}</h4></p></a>", info_template : "<p>Number of posts found: {{amount}}</p>", displaySearchInfo : true, zeroResultsInfo : true, before : false, onComplete : false, includepages : false, filterfields : false }; var prettyDate = function(date) { var d = new Date(date); var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; return d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear(); }; var pluginMethods = { isInit : false, init : function( target , opts ){ var that = this; this.target = target; this.results = opts.results; this.blogData = {}; this.result_template = opts.result_template; this.info_template = opts.info_template; this.zeroResultsInfo = opts.zeroResultsInfo; this.displaySearchInfo = opts.displaySearchInfo; this.before = opts.before; this.onComplete = opts.onComplete; this.includepages = opts.includepages; this.filterfields = opts.filterfields; //This is where we'll build the index for later searching. It's not a big deal to build it on every load as it takes almost no space without data this.index = lunr(function () { this.field('title', {boost: 10}) this.field('description') this.field('link') this.field('plaintext', {boost: 5}) this.field('pubDate') this.field('tag') this.ref('id') }); if ( opts.onPageLoad ) { function miam () { that.loadAPI(); } window.setTimeout(miam, 1); } else { target.focus(function(){ that.loadAPI(); }); } target.closest("form").submit(function(e){ e.preventDefault(); that.find(target.val()); }); if( opts.onKeyUp ) { target.keyup(function() { that.find(target.val()); }); } }, loadAPI : function(){ if(this.isInit) return false; /* Here we load all of the blog posts to the index. This function will not call on load to avoid unnecessary heavy operations on a page if a visitor never ends up searching anything. */ var index = this.index, blogData = this.blogData; obj = {limit: "all", include: "tags", formats:["plaintext"]}; if ( this.includepages ){ obj.filter="(page:true,page:false)"; } $.get(ghost.url.api('posts',obj)).done(function(data){ searchData = data.posts; searchData.forEach(function(arrayItem){ var tag_arr = arrayItem.tags.map(function(v) { return v.name; // `tag` object has an `name` property which is the value of tag. If you also want other info, check API and get that property }) if(arrayItem.meta_description == null) { arrayItem.meta_description = '' }; var category = tag_arr.join(", "); if (category.length < 1){ category = "undefined"; } var parsedData = { id : String(arrayItem.id), title : String(arrayItem.title), description : String(arrayItem.meta_description), plaintext : String(arrayItem.plaintext), pubDate : String(arrayItem.created_at), tag : category, featureImage : String(arrayItem.feature_image), link : String(arrayItem.url) } parsedData.prettyPubDate = prettyDate(parsedData.pubDate); var tempdate = prettyDate(parsedData.pubDate); index.add(parsedData) blogData[arrayItem.id] = { title: arrayItem.title, description: arrayItem.meta_description, pubDate: tempdate, featureImage: arrayItem.feature_image, link: arrayItem.url }; }); }); this.isInit = true; }, find : function(value){ var searchResult = this.index.search(value); var results = $(this.results); var resultsData = []; results.empty(); if(this.before) { this.before(); }; if(this.zeroResultsInfo || searchResult.length > 0) { if(this.displaySearchInfo) results.append(this.format(this.info_template,{"amount":searchResult.length})); } for (var i = 0; i < searchResult.length; i++) { var lunrref = searchResult[i].ref; var postData = this.blogData[lunrref]; results.append(this.format(this.result_template,postData)); resultsData.push(postData); } if(this.onComplete) { this.onComplete(resultsData); }; }, clear : function(){ $(this.results).empty(); this.target.val(""); }, format : function (t, d) { return t.replace(/{{([^{}]*)}}/g, function (a, b) { var r = d[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); } } })( jQuery );
rkalis/roscasper
assets/ghostHunter/src/ghosthunter-nodependency.js
JavaScript
mit
5,344
/** * @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 */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js function plural(n: number): number { if (n === 1) return 1; return 5; } export default [ 'so-KE', [ ['sn.', 'gn.'], , ], , [ ['A', 'I', 'T', 'A', 'Kh', 'J', 'S'], ['Axd', 'Isn', 'Tal', 'Arb', 'Kha', 'Jim', 'Sab'], ['Axad', 'Isniin', 'Talaado', 'Arbaco', 'Khamiis', 'Jimco', 'Sabti'], ['Axd', 'Isn', 'Tal', 'Arb', 'Kha', 'Jim', 'Sab'] ], , [ ['K', 'L', 'S', 'A', 'S', 'L', 'T', 'S', 'S', 'T', 'K', 'L'], ['Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT'], [ 'Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad' ] ], [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], ['Kob', 'Lab', 'Sad', 'Afr', 'Sha', 'Lix', 'Tod', 'Sid', 'Sag', 'Tob', 'KIT', 'LIT'], [ 'Bisha Koobaad', 'Bisha Labaad', 'Bisha Saddexaad', 'Bisha Afraad', 'Bisha Shanaad', 'Bisha Lixaad', 'Bisha Todobaad', 'Bisha Sideedaad', 'Bisha Sagaalaad', 'Bisha Tobnaad', 'Bisha Kow iyo Tobnaad', 'Bisha Laba iyo Tobnaad' ] ], [ ['CK', 'CD'], , ], 0, [6, 0], ['dd/MM/yy', 'dd-MMM-y', 'dd MMMM y', 'EEEE, MMMM dd, y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], [ '{1} {0}', , , ], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], 'Ksh', 'KES', plural ];
vsavkin/angular
packages/common/locales/so-KE.ts
TypeScript
mit
1,854
<?php /* * This file is part of the BootstrapPHP package. * * (c) Milos Danilov <milosdanilov@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace BootstrapPHP\Components\Dropdown; /** * Class DropdownItem * * @package BootstrapPHP\Components\Dropdown * @author Milos Danilov <milosdanilov@gmail.com> */ class DropdownItem { protected $content; protected $disabled = false; public function __construct($content, $disabled = false) { $this->content = $content; $this->disabled = $disabled; } protected function getDisabled() { return $this->disabled ? "class='disabled'" : ''; } public function __toString() { return "<li {$this->getDisabled()}>{$this->content}</li>"; } }
milosd92/BootstrapPHP
src/BootstrapPHP/Components/Dropdown/DropdownItem.php
PHP
mit
862
class HomeController < ApplicationController def index end def unstubed end end
tech-angels/jaganizer
spec/dummy/app/controllers/home_controller.rb
Ruby
mit
89
# Past examples are programmatically insecure # You require arguments to be passed in but what if the wrong arguments are provided? # Look at the timestable solution which changes numbers to text - what happens if you provide the number 30? # # One way of controlling these things uses conditions # These enable specific operations to be carried out "if" something is the case or "else" something else is the case a = 5 # first condition trial if a >= 5: print("Value is greater than 5") else: print("Value is less than 5") # second condition trial if a >= 5: print("Value is greater than 5") elif a < 5: print("Value is less than 5") else: print("Value is 5") # if and (2 conditions) a=3 b=5 if (a==3) and (b==5): print("a and b are as expected - great :)") else: print("a and b not as expected - not great :(")
Chris35Wills/Chris35Wills.github.io
courses/examples/Beginners_python/conditions.py
Python
mit
826
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Resources::Mgmt::V2019_10_01 module Models # # Defines values for DeploymentMode # module DeploymentMode Incremental = "Incremental" Complete = "Complete" end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_resources/lib/2019-10-01/generated/azure_mgmt_resources/models/deployment_mode.rb
Ruby
mit
381
package com.rsegismont.androlife.details; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.ViewPager; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.view.MenuItem; import com.rsegismont.androlife.R; import com.rsegismont.androlife.activities.ProgrammeAbstract; import com.rsegismont.androlife.common.Constantes; import com.rsegismont.androlife.common.SharedInformation; import com.rsegismont.androlife.common.SharedInformation.DatabaseColumn; import com.rsegismont.androlife.common.api.AndrolifeApi9; import com.rsegismont.androlife.common.utils.Utils; import com.rsegismont.androlife.core.utils.AndrolifeUtils; import com.rsegismont.androlife.home.HomeActivity; import java.util.Calendar; public class ProgrammesDetailActivity extends ProgrammeAbstract implements LoaderManager.LoaderCallbacks<Cursor> { @Override public int getActivityOrientation() { if(Utils.hasGingerbread()){ return AndrolifeApi9.getSensorPortraitAttribute(); } return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } public static final String commonDate = SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " BETWEEN ? AND ?"; private ViewPager myPager; public PagerTabStrip tabTitle; public boolean firstInit = true; private int getCurrentIndex() { if (this.mCursor == null) { return -1; } if (this.mCursor.getCount() <= 0) { return -1; } for (int position = Math.max(0, mCursor.getPosition()); position < mCursor.getCount(); position++) { if (mCursor.moveToPosition(position)) { long dateUtc = this.mCursor.getLong(this.mCursor .getColumnIndex(SharedInformation.DatabaseColumn.DATE_UTC.stringValue)); if (System.currentTimeMillis() - dateUtc >= 0) { return position; } } else { break; } } return -1; } private int getTonightIndex() { if (this.mCursor == null) { return -1; } if (this.mCursor.getCount() <= 0) { return -1; } final long currentDateUtc = this.mCursor.getLong(this.mCursor .getColumnIndex(SharedInformation.DatabaseColumn.DATE_UTC.stringValue)); final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(currentDateUtc); calendar.set(Calendar.HOUR_OF_DAY, 19); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); for (int position = Math.max(0, mCursor.getPosition()); position < mCursor.getCount(); position++) { if (mCursor.moveToPosition(position)) { long candidateDateUtc = this.mCursor.getLong(this.mCursor .getColumnIndex(SharedInformation.DatabaseColumn.DATE_UTC.stringValue)); if (calendar.getTime().getTime() - candidateDateUtc >= 0L) { return position; } } else { break; } } return -1; } public void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); final int type = getIntent().getIntExtra(Constantes.TYPE, Constantes.CURSOR_FULL); getSupportLoaderManager().initLoader(type, null, this); getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP); setContentView(R.layout.host_activity); setTitle(getResources().getString(R.string.app_name)); switch (type) { case Constantes.CURSOR_FULL: getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_all)); break; case Constantes.CURSOR_QUERY: getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_query)); break; case Constantes.CURSOR_NEWS: getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_news)); break; case Constantes.CURSOR_SELECTION: getSupportActionBar().setSubtitle(getResources().getString(R.string.subtitle_selection)); break; default: break; } myPager = (ViewPager) findViewById(R.id.host_tab_viewpager); tabTitle = (PagerTabStrip) findViewById(R.id.host_tab_title); if (tabTitle != null) { this.tabTitle.setTabIndicatorColor(getResources().getColor(R.color.androlife_programs_hint_underline)); this.tabTitle.setTextColor(getResources().getColor(R.color.androlife_programs_hint_text)); } } public Loader<Cursor> onCreateLoader(int paramInt, Bundle paramBundle) { Calendar morningCalendar = Calendar.getInstance(); morningCalendar.setTimeInMillis(getIntent().getLongExtra("DETAIL_DATE_INDEX", 0L)); morningCalendar.add(Calendar.HOUR_OF_DAY, -24); Calendar eveningCalendar = Calendar.getInstance(); eveningCalendar.setTimeInMillis(getIntent().getLongExtra("DETAIL_DATE_INDEX", 0L)); eveningCalendar.add(Calendar.HOUR_OF_DAY, 24); switch (paramInt) { default: return AndrolifeUtils.getAndrolifeLoader(getApplicationContext(), paramInt, null, new Calendar[] { morningCalendar, eveningCalendar }); case Constantes.CURSOR_QUERY: return new CursorLoader(this, SharedInformation.CONTENT_URI_PROGRAMMES, null, SharedInformation.DatabaseColumn.DESCRIPTION.stringValue + " LIKE ?", new String[] { "%" + getIntent().getExtras().getString("DETAIL_QUERY") + "%" }, SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " ASC"); case Constantes.CURSOR_QUERY_VIEW: String str = SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " BETWEEN ? AND ?"; String[] arrayOfString = new String[2]; arrayOfString[0] = "" + morningCalendar.getTime().getTime(); arrayOfString[1] = "" + eveningCalendar.getTime().getTime(); return new CursorLoader(this, SharedInformation.CONTENT_URI_PROGRAMMES, null, str, arrayOfString, SharedInformation.DatabaseColumn.DATE_UTC.stringValue + " ASC"); } } @Override protected void onSaveInstanceState(Bundle outState) { } public void onLoadFinished(Loader<Cursor> paramLoader, Cursor cursor) { this.mCursor = cursor; adapterDetails = new DetailsAdapter(this); myPager.setOnPageChangeListener(adapterDetails); myPager.setAdapter(adapterDetails); final String intentDate = getIntent().getDataString(); if (intentDate == null) { final long initialTime = getIntent().getLongExtra(Constantes.DETAIL_DATE_TIME, 0); setPagerSelection(initialTime); } else { setPagerSelection(Long.valueOf(intentDate)); } } public void onLoaderReset(Loader<Cursor> paramLoader) { } public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.menu_list_programmes_now: setPagerSelection(getCurrentIndex()); return true; case R.id.menu_list_programmes_tonight: setPagerSelection(getTonightIndex()); return true; case android.R.id.home: // ProjectsActivity is my 'home' activity startActivityAfterCleanup(HomeActivity.class); return true; } return (super.onOptionsItemSelected(menuItem)); } public void setPagerSelection(long initialTime) { final int initialPosition = mCursor.getPosition(); for (int i = 0; i < mCursor.getCount(); i++) { mCursor.moveToPosition(i); final long value = mCursor.getLong(mCursor.getColumnIndex(DatabaseColumn.DATE_UTC.stringValue)); final int index = i; if (initialTime == value) { if (myPager.getCurrentItem() == index) { if (firstInit == true) { firstInit = false; adapterDetails.onPageSelected(index); } } else { myPager.setCurrentItem(index, false); } break; } } if (initialPosition >= 0) { mCursor.moveToPosition(initialPosition); } } }
rsegismont/Androlife
mobile/src/main/java/com/rsegismont/androlife/details/ProgrammesDetailActivity.java
Java
mit
7,606
package api import ( "github.com/johnny-morrice/godless/crdt" ) type CacheCloser interface { CloseCache() error } type Cache interface { HeadCache IndexCache NamespaceCache CacheCloser } type HeadCache interface { SetHead(head crdt.IPFSPath) error GetHead() (crdt.IPFSPath, error) } type RequestPriorityQueue interface { Len() int Enqueue(request Request, data interface{}) error Drain() <-chan interface{} Close() error } type IndexCache interface { GetIndex(indexAddr crdt.IPFSPath) (crdt.Index, error) SetIndex(indexAddr crdt.IPFSPath, index crdt.Index) error } type NamespaceCache interface { GetNamespace(namespaceAddr crdt.IPFSPath) (crdt.Namespace, error) SetNamespace(namespaceAddr crdt.IPFSPath, namespace crdt.Namespace) error }
johnny-morrice/godless
api/cache.go
GO
mit
762
<?php abstract class BaseMlmDailyBonusLog extends BaseObject implements Persistent { protected static $peer; protected $log_id; protected $access_ip; protected $bonus_type; protected $bonus_date; protected $created_by; protected $created_on; protected $updated_by; protected $updated_on; protected $alreadyInSave = false; protected $alreadyInValidation = false; public function getLogId() { return $this->log_id; } public function getAccessIp() { return $this->access_ip; } public function getBonusType() { return $this->bonus_type; } public function getBonusDate($format = 'Y-m-d H:i:s') { if ($this->bonus_date === null || $this->bonus_date === '') { return null; } elseif (!is_int($this->bonus_date)) { $ts = strtotime($this->bonus_date); if ($ts === -1 || $ts === false) { throw new PropelException("Unable to parse value of [bonus_date] as date/time value: " . var_export($this->bonus_date, true)); } } else { $ts = $this->bonus_date; } if ($format === null) { return $ts; } elseif (strpos($format, '%') !== false) { return strftime($format, $ts); } else { return date($format, $ts); } } public function getCreatedBy() { return $this->created_by; } public function getCreatedOn($format = 'Y-m-d H:i:s') { if ($this->created_on === null || $this->created_on === '') { return null; } elseif (!is_int($this->created_on)) { $ts = strtotime($this->created_on); if ($ts === -1 || $ts === false) { throw new PropelException("Unable to parse value of [created_on] as date/time value: " . var_export($this->created_on, true)); } } else { $ts = $this->created_on; } if ($format === null) { return $ts; } elseif (strpos($format, '%') !== false) { return strftime($format, $ts); } else { return date($format, $ts); } } public function getUpdatedBy() { return $this->updated_by; } public function getUpdatedOn($format = 'Y-m-d H:i:s') { if ($this->updated_on === null || $this->updated_on === '') { return null; } elseif (!is_int($this->updated_on)) { $ts = strtotime($this->updated_on); if ($ts === -1 || $ts === false) { throw new PropelException("Unable to parse value of [updated_on] as date/time value: " . var_export($this->updated_on, true)); } } else { $ts = $this->updated_on; } if ($format === null) { return $ts; } elseif (strpos($format, '%') !== false) { return strftime($format, $ts); } else { return date($format, $ts); } } public function setLogId($v) { if ($v !== null && !is_int($v) && is_numeric($v)) { $v = (int) $v; } if ($this->log_id !== $v) { $this->log_id = $v; $this->modifiedColumns[] = MlmDailyBonusLogPeer::LOG_ID; } } public function setAccessIp($v) { if ($v !== null && !is_string($v)) { $v = (string) $v; } if ($this->access_ip !== $v) { $this->access_ip = $v; $this->modifiedColumns[] = MlmDailyBonusLogPeer::ACCESS_IP; } } public function setBonusType($v) { if ($v !== null && !is_string($v)) { $v = (string) $v; } if ($this->bonus_type !== $v) { $this->bonus_type = $v; $this->modifiedColumns[] = MlmDailyBonusLogPeer::BONUS_TYPE; } } public function setBonusDate($v) { if ($v !== null && !is_int($v)) { $ts = strtotime($v); if ($ts === -1 || $ts === false) { throw new PropelException("Unable to parse date/time value for [bonus_date] from input: " . var_export($v, true)); } } else { $ts = $v; } if ($this->bonus_date !== $ts) { $this->bonus_date = $ts; $this->modifiedColumns[] = MlmDailyBonusLogPeer::BONUS_DATE; } } public function setCreatedBy($v) { if ($v !== null && !is_int($v) && is_numeric($v)) { $v = (int) $v; } if ($this->created_by !== $v) { $this->created_by = $v; $this->modifiedColumns[] = MlmDailyBonusLogPeer::CREATED_BY; } } public function setCreatedOn($v) { if ($v !== null && !is_int($v)) { $ts = strtotime($v); if ($ts === -1 || $ts === false) { throw new PropelException("Unable to parse date/time value for [created_on] from input: " . var_export($v, true)); } } else { $ts = $v; } if ($this->created_on !== $ts) { $this->created_on = $ts; $this->modifiedColumns[] = MlmDailyBonusLogPeer::CREATED_ON; } } public function setUpdatedBy($v) { if ($v !== null && !is_int($v) && is_numeric($v)) { $v = (int) $v; } if ($this->updated_by !== $v) { $this->updated_by = $v; $this->modifiedColumns[] = MlmDailyBonusLogPeer::UPDATED_BY; } } public function setUpdatedOn($v) { if ($v !== null && !is_int($v)) { $ts = strtotime($v); if ($ts === -1 || $ts === false) { throw new PropelException("Unable to parse date/time value for [updated_on] from input: " . var_export($v, true)); } } else { $ts = $v; } if ($this->updated_on !== $ts) { $this->updated_on = $ts; $this->modifiedColumns[] = MlmDailyBonusLogPeer::UPDATED_ON; } } public function hydrate(ResultSet $rs, $startcol = 1) { try { $this->log_id = $rs->getInt($startcol + 0); $this->access_ip = $rs->getString($startcol + 1); $this->bonus_type = $rs->getString($startcol + 2); $this->bonus_date = $rs->getTimestamp($startcol + 3, null); $this->created_by = $rs->getInt($startcol + 4); $this->created_on = $rs->getTimestamp($startcol + 5, null); $this->updated_by = $rs->getInt($startcol + 6); $this->updated_on = $rs->getTimestamp($startcol + 7, null); $this->resetModified(); $this->setNew(false); return $startcol + 8; } catch (Exception $e) { throw new PropelException("Error populating MlmDailyBonusLog object", $e); } } public function delete($con = null) { if ($this->isDeleted()) { throw new PropelException("This object has already been deleted."); } if ($con === null) { $con = Propel::getConnection(MlmDailyBonusLogPeer::DATABASE_NAME); } try { $con->begin(); MlmDailyBonusLogPeer::doDelete($this, $con); $this->setDeleted(true); $con->commit(); } catch (PropelException $e) { $con->rollback(); throw $e; } } public function save($con = null) { if ($this->isNew() && !$this->isColumnModified(MlmDailyBonusLogPeer::CREATED_ON)) { $this->setCreatedOn(time()); } if ($this->isModified() && !$this->isColumnModified(MlmDailyBonusLogPeer::UPDATED_ON)) { $this->setUpdatedOn(time()); } if ($this->isDeleted()) { throw new PropelException("You cannot save an object that has been deleted."); } if ($con === null) { $con = Propel::getConnection(MlmDailyBonusLogPeer::DATABASE_NAME); } try { $con->begin(); $affectedRows = $this->doSave($con); $con->commit(); return $affectedRows; } catch (PropelException $e) { $con->rollback(); throw $e; } } protected function doSave($con) { $affectedRows = 0; if (!$this->alreadyInSave) { $this->alreadyInSave = true; if ($this->isModified()) { if ($this->isNew()) { $pk = MlmDailyBonusLogPeer::doInsert($this, $con); $affectedRows += 1; $this->setLogId($pk); $this->setNew(false); } else { $affectedRows += MlmDailyBonusLogPeer::doUpdate($this, $con); } $this->resetModified(); } $this->alreadyInSave = false; } return $affectedRows; } protected $validationFailures = array(); public function getValidationFailures() { return $this->validationFailures; } public function validate($columns = null) { $res = $this->doValidate($columns); if ($res === true) { $this->validationFailures = array(); return true; } else { $this->validationFailures = $res; return false; } } protected function doValidate($columns = null) { if (!$this->alreadyInValidation) { $this->alreadyInValidation = true; $retval = null; $failureMap = array(); if (($retval = MlmDailyBonusLogPeer::doValidate($this, $columns)) !== true) { $failureMap = array_merge($failureMap, $retval); } $this->alreadyInValidation = false; } return (!empty($failureMap) ? $failureMap : true); } public function getByName($name, $type = BasePeer::TYPE_PHPNAME) { $pos = MlmDailyBonusLogPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->getByPosition($pos); } public function getByPosition($pos) { switch($pos) { case 0: return $this->getLogId(); break; case 1: return $this->getAccessIp(); break; case 2: return $this->getBonusType(); break; case 3: return $this->getBonusDate(); break; case 4: return $this->getCreatedBy(); break; case 5: return $this->getCreatedOn(); break; case 6: return $this->getUpdatedBy(); break; case 7: return $this->getUpdatedOn(); break; default: return null; break; } } public function toArray($keyType = BasePeer::TYPE_PHPNAME) { $keys = MlmDailyBonusLogPeer::getFieldNames($keyType); $result = array( $keys[0] => $this->getLogId(), $keys[1] => $this->getAccessIp(), $keys[2] => $this->getBonusType(), $keys[3] => $this->getBonusDate(), $keys[4] => $this->getCreatedBy(), $keys[5] => $this->getCreatedOn(), $keys[6] => $this->getUpdatedBy(), $keys[7] => $this->getUpdatedOn(), ); return $result; } public function setByName($name, $value, $type = BasePeer::TYPE_PHPNAME) { $pos = MlmDailyBonusLogPeer::translateFieldName($name, $type, BasePeer::TYPE_NUM); return $this->setByPosition($pos, $value); } public function setByPosition($pos, $value) { switch($pos) { case 0: $this->setLogId($value); break; case 1: $this->setAccessIp($value); break; case 2: $this->setBonusType($value); break; case 3: $this->setBonusDate($value); break; case 4: $this->setCreatedBy($value); break; case 5: $this->setCreatedOn($value); break; case 6: $this->setUpdatedBy($value); break; case 7: $this->setUpdatedOn($value); break; } } public function fromArray($arr, $keyType = BasePeer::TYPE_PHPNAME) { $keys = MlmDailyBonusLogPeer::getFieldNames($keyType); if (array_key_exists($keys[0], $arr)) $this->setLogId($arr[$keys[0]]); if (array_key_exists($keys[1], $arr)) $this->setAccessIp($arr[$keys[1]]); if (array_key_exists($keys[2], $arr)) $this->setBonusType($arr[$keys[2]]); if (array_key_exists($keys[3], $arr)) $this->setBonusDate($arr[$keys[3]]); if (array_key_exists($keys[4], $arr)) $this->setCreatedBy($arr[$keys[4]]); if (array_key_exists($keys[5], $arr)) $this->setCreatedOn($arr[$keys[5]]); if (array_key_exists($keys[6], $arr)) $this->setUpdatedBy($arr[$keys[6]]); if (array_key_exists($keys[7], $arr)) $this->setUpdatedOn($arr[$keys[7]]); } public function buildCriteria() { $criteria = new Criteria(MlmDailyBonusLogPeer::DATABASE_NAME); if ($this->isColumnModified(MlmDailyBonusLogPeer::LOG_ID)) $criteria->add(MlmDailyBonusLogPeer::LOG_ID, $this->log_id); if ($this->isColumnModified(MlmDailyBonusLogPeer::ACCESS_IP)) $criteria->add(MlmDailyBonusLogPeer::ACCESS_IP, $this->access_ip); if ($this->isColumnModified(MlmDailyBonusLogPeer::BONUS_TYPE)) $criteria->add(MlmDailyBonusLogPeer::BONUS_TYPE, $this->bonus_type); if ($this->isColumnModified(MlmDailyBonusLogPeer::BONUS_DATE)) $criteria->add(MlmDailyBonusLogPeer::BONUS_DATE, $this->bonus_date); if ($this->isColumnModified(MlmDailyBonusLogPeer::CREATED_BY)) $criteria->add(MlmDailyBonusLogPeer::CREATED_BY, $this->created_by); if ($this->isColumnModified(MlmDailyBonusLogPeer::CREATED_ON)) $criteria->add(MlmDailyBonusLogPeer::CREATED_ON, $this->created_on); if ($this->isColumnModified(MlmDailyBonusLogPeer::UPDATED_BY)) $criteria->add(MlmDailyBonusLogPeer::UPDATED_BY, $this->updated_by); if ($this->isColumnModified(MlmDailyBonusLogPeer::UPDATED_ON)) $criteria->add(MlmDailyBonusLogPeer::UPDATED_ON, $this->updated_on); return $criteria; } public function buildPkeyCriteria() { $criteria = new Criteria(MlmDailyBonusLogPeer::DATABASE_NAME); $criteria->add(MlmDailyBonusLogPeer::LOG_ID, $this->log_id); return $criteria; } public function getPrimaryKey() { return $this->getLogId(); } public function setPrimaryKey($key) { $this->setLogId($key); } public function copyInto($copyObj, $deepCopy = false) { $copyObj->setAccessIp($this->access_ip); $copyObj->setBonusType($this->bonus_type); $copyObj->setBonusDate($this->bonus_date); $copyObj->setCreatedBy($this->created_by); $copyObj->setCreatedOn($this->created_on); $copyObj->setUpdatedBy($this->updated_by); $copyObj->setUpdatedOn($this->updated_on); $copyObj->setNew(true); $copyObj->setLogId(NULL); } public function copy($deepCopy = false) { $clazz = get_class($this); $copyObj = new $clazz(); $this->copyInto($copyObj, $deepCopy); return $copyObj; } public function getPeer() { if (self::$peer === null) { self::$peer = new MlmDailyBonusLogPeer(); } return self::$peer; } }
vincent03460/fxcmiscc-partner
lib/model/om/BaseMlmDailyBonusLog.php
PHP
mit
13,401
import React, { PropTypes, } from 'react'; import { StyleSheet, View, Text, } from 'react-native'; const styles = StyleSheet.create({ all: { paddingHorizontal: 10, paddingVertical: 5, }, text: { fontSize: 12, color: '#666', }, }); function ListItemTitle(props) { return ( <View style={styles.all}> <Text style={styles.text} > {props.text} </Text> </View> ); } ListItemTitle.propTypes = { text: PropTypes.string, }; ListItemTitle.defaultProps = { text: '', }; export default ListItemTitle;
dragonwong/rnx-ui
Example/src/component/List/ListItemTitle/index.js
JavaScript
mit
576
// Copyright (c) 2018 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode-budget.h" #include "tinyformat.h" #include "utilmoneystr.h" #include "test_syndicate.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(budget_tests, TestingSetup) void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue) { CBudgetManager budget; CAmount nBudget = budget.GetTotalBudget(nHeight); std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue)); BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError); } BOOST_AUTO_TEST_CASE(budget_value) { SelectParams(CBaseChainParams::TESTNET); int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "testnet", 7300*COIN); SelectParams(CBaseChainParams::MAIN); nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN); } BOOST_AUTO_TEST_SUITE_END()
SyndicateLtd/SyndicateQT
src/test/budget_tests.cpp
C++
mit
1,172
#Import Libraries import eventmaster as EM from time import sleep import random import sys """ Create new Instance of EventMasterSwitcher and turn off logging """ s3 = EM.EventMasterSwitcher() s3.setVerbose(0) with open('example_settings_.xml', 'r') as content_file: content = content_file.read() s3.loadFromXML(content) """ Enumerate all Inputs and print known information for each """ print("# Inputs") for input_id, input_inst in s3.getInputs().items(): input_name = input_inst.getName() frozen_string = "is Frozen" if input_inst.getFreeze() else "is not Frozen" print(" ({0!s}) {1!s} {2!s}".format(input_id, input_name, frozen_string)) """ Enumerate all Outputs and print known information for each """ print("\r\n# Outputs") for output_id, output_inst in s3.getOutputs().items(): output_name = output_inst.getName() print(" ({0!s}) {1!s}".format(output_id, output_name)) """ Enumerate all Presets and print known information for each """ print("\r\n# Presets") for preset_id, preset_inst in s3.getPresets().items(): preset_name = preset_inst.getName() print(" ({0!s}) {1!s}".format(preset_id, preset_name)) """ Enumerate all Destinations and print known information for each """ print("\r\n# Destinations:") for dest_id, dest_inst in s3.getScreenDests().items(): dest_numoflayers = len(dest_inst.getLayers()) dest_name = dest_inst.getName() dest_size = dest_inst.getSize() print("\n {1!s} is {2!s} x {3!s} & has {4!s} layer(s)".format( dest_id, dest_name, dest_size["HSize"], dest_size["VSize"], dest_numoflayers)) """ Enumerate all Layers for Destination and print known information for each """ for layer_number, layer_inst in dest_inst.getLayers().items(): if "Pvw" in layer_inst: layer_name_pvw = layer_inst["Pvw"].getName() layer_owin_pvw = layer_inst["Pvw"].getOWIN() layer_hpos_pvw = layer_owin_pvw["HPos"] layer_hsize_pvw = layer_owin_pvw["HSize"] layer_vpos_pvw = layer_owin_pvw["VPos"] layer_vsize_pvw = layer_owin_pvw["VSize"] if layer_inst["Pvw"].getSource() is not None: layer_source_name_pvw = layer_inst["Pvw"].getSource().getName() else: layer_source_name_pvw = "(Unknown)" size_string_pvw = " {4!s} is on PVW - {0!s}x{1!s} at {2!s},{3!s}".format(layer_hsize_pvw, layer_vsize_pvw, layer_hpos_pvw, layer_vpos_pvw, layer_name_pvw) source_string_pvw = " current source is {0!s}".format(layer_source_name_pvw) else: size_string_pvw = " Layer is not on PVW " source_string_pvw = "" if "Pgm" in layer_inst: layer_name_pgm = layer_inst["Pgm"].getName() layer_owin_pgm = layer_inst["Pgm"].getOWIN() layer_hpos_pgm = layer_owin_pgm["HPos"] layer_hsize_pgm = layer_owin_pgm["HSize"] layer_vpos_pgm = layer_owin_pgm["VPos"] layer_vsize_pgm = layer_owin_pgm["VSize"] if layer_inst["Pgm"].getSource() is not None: layer_source_name_pgm = layer_inst["Pgm"].getSource().getName() else: layer_source_name_pgm = "(Unknown)" size_string_pgm = " {4!s} is on PGM - {0!s}x{1!s} at {2!s},{3!s}".format(layer_hsize_pgm, layer_vsize_pgm, layer_hpos_pgm, layer_vpos_pgm, layer_name_pgm) source_string_pgm = " current source is {0!s}".format(layer_source_name_pgm) else: size_string_pgm = " Layer is not on PGM " source_string_pgm = "" size_string = " {4!s} is on PGM - {0!s}x{1!s} at {2!s},{3!s}".format(layer_hsize_pgm, layer_vsize_pgm, layer_hpos_pgm, layer_vpos_pgm, layer_name_pgm) source_string = " current source is {0!s}".format(layer_source_name_pgm) print(" ({0!s}) {1!s}\n {2!s}\n {3!s}\n {4!s}".format(layer_number+1, size_string_pgm, source_string_pgm, size_string_pvw, source_string_pvw)) sys.exit()
kyelewisstgc/EventMaster-Python
tests/test_offline.py
Python
mit
4,308
import axios from 'axios'; import {getAuthInfo} from './firebase-service'; import {VIANCA, CHAN, TOPA, IBA_COLOMBIA} from './service-store'; export const ERROR_RESULT = 'ERROR'; export const RESERVED_RESULT = 'R'; export const INSUFICIENT_RESULT = 'I'; export const NOT_FOUND_RESULT = 'NF'; export function submitReserve(reserve, airlineCode) { let _this = this; let apiUrl = getAirlineUrl(airlineCode); reserve.token = getAuthInfo().idToken; return axios.post(apiUrl, reserve).then(result => { if (!result.message) { console.error("No \"message\" attribute in result: ", result) return ERROR_RESULT; } return result.message; }).catch(error => console.log(error)); } function getAirlineUrl(airlineCode) { switch (airlineCode) { case VIANCA.code: return VIANCA.submitReserveUrl; case CHAN.code: return CHAN.submitReserveUrl; case TOPA.code: return TOPA.submitReserveUrl; case IBA_COLOMBIA.code: return IBA_COLOMBIA.submitReserveUrl; default: } } export function searchForReserve(apiUrl) { let _this = this; let url = apiUrl + '?token=' + getAuthInfo().idToken; // + getToken(); return axios.get(url); } export function submitAllReserveSearch() { console.log('Fetching reserve searchs'); let viancaResult = searchForReserve(VIANCA.fetchReserves); let chanResult = searchForReserve(CHAN.fetchReserves); let topaResult = searchForReserve(TOPA.fetchReserves); let ibaResult = searchForReserve(IBA_COLOMBIA.fetchReserves); let mergedResults = axios.all([viancaResult, chanResult, topaResult, ibaResult]); return mergedResults; }
camilosampedro/desvolar-web
src/service/reserve-service.js
JavaScript
mit
1,631
class AddUserIdIndexToOpmlExportJobStates < ActiveRecord::Migration[5.2] def change add_index :opml_export_job_states, [:user_id], name: 'index_opml_export_job_states_on_user_id' end end
amatriain/feedbunch
FeedBunch-app/db/migrate/20140519111415_add_user_id_index_to_opml_export_job_states.rb
Ruby
mit
195
import { DESCRIPTORS, LITTLE_ENDIAN } from '../helpers/constants'; if (DESCRIPTORS) QUnit.test('Int32 conversions', assert => { const int32array = new Int32Array(1); const uint8array = new Uint8Array(int32array.buffer); const dataview = new DataView(int32array.buffer); function viewFrom(it) { return new DataView(new Uint8Array(it).buffer); } function toString(it) { return it === 0 && 1 / it === -Infinity ? '-0' : it; } const data = [ [0, 0, [0, 0, 0, 0]], [-0, 0, [0, 0, 0, 0]], [1, 1, [1, 0, 0, 0]], [-1, -1, [255, 255, 255, 255]], [1.1, 1, [1, 0, 0, 0]], [-1.1, -1, [255, 255, 255, 255]], [1.9, 1, [1, 0, 0, 0]], [-1.9, -1, [255, 255, 255, 255]], [127, 127, [127, 0, 0, 0]], [-127, -127, [129, 255, 255, 255]], [128, 128, [128, 0, 0, 0]], [-128, -128, [128, 255, 255, 255]], [255, 255, [255, 0, 0, 0]], [-255, -255, [1, 255, 255, 255]], [255.1, 255, [255, 0, 0, 0]], [255.9, 255, [255, 0, 0, 0]], [256, 256, [0, 1, 0, 0]], [32767, 32767, [255, 127, 0, 0]], [-32767, -32767, [1, 128, 255, 255]], [32768, 32768, [0, 128, 0, 0]], [-32768, -32768, [0, 128, 255, 255]], [65535, 65535, [255, 255, 0, 0]], [65536, 65536, [0, 0, 1, 0]], [65537, 65537, [1, 0, 1, 0]], [65536.54321, 65536, [0, 0, 1, 0]], [-65536.54321, -65536, [0, 0, 255, 255]], [2147483647, 2147483647, [255, 255, 255, 127]], [-2147483647, -2147483647, [1, 0, 0, 128]], [2147483648, -2147483648, [0, 0, 0, 128]], [-2147483648, -2147483648, [0, 0, 0, 128]], [2147483649, -2147483647, [1, 0, 0, 128]], [-2147483649, 2147483647, [255, 255, 255, 127]], [4294967295, -1, [255, 255, 255, 255]], [4294967296, 0, [0, 0, 0, 0]], [4294967297, 1, [1, 0, 0, 0]], [9007199254740991, -1, [255, 255, 255, 255]], [-9007199254740991, 1, [1, 0, 0, 0]], [9007199254740992, 0, [0, 0, 0, 0]], [-9007199254740992, 0, [0, 0, 0, 0]], [9007199254740994, 2, [2, 0, 0, 0]], [-9007199254740994, -2, [254, 255, 255, 255]], [Infinity, 0, [0, 0, 0, 0]], [-Infinity, 0, [0, 0, 0, 0]], [-1.7976931348623157e+308, 0, [0, 0, 0, 0]], [1.7976931348623157e+308, 0, [0, 0, 0, 0]], [5e-324, 0, [0, 0, 0, 0]], [-5e-324, 0, [0, 0, 0, 0]], [NaN, 0, [0, 0, 0, 0]], ]; for (const [value, conversion, little] of data) { const big = little.slice().reverse(); const representation = LITTLE_ENDIAN ? little : big; int32array[0] = value; assert.same(int32array[0], conversion, `Int32Array ${ toString(value) } -> ${ toString(conversion) }`); assert.arrayEqual(uint8array, representation, `Int32Array ${ toString(value) } -> [${ representation }]`); dataview.setInt32(0, value); assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }) -> [${ big }]`); assert.same(viewFrom(big).getInt32(0), conversion, `dataview{${ big }}.getInt32(0) -> ${ toString(conversion) }`); dataview.setInt32(0, value, false); assert.arrayEqual(uint8array, big, `dataview.setInt32(0, ${ toString(value) }, false) -> [${ big }]`); assert.same(viewFrom(big).getInt32(0, false), conversion, `dataview{${ big }}.getInt32(0, false) -> ${ toString(conversion) }`); dataview.setInt32(0, value, true); assert.arrayEqual(uint8array, little, `dataview.setInt32(0, ${ toString(value) }, true) -> [${ little }]`); assert.same(viewFrom(little).getInt32(0, true), conversion, `dataview{${ little }}.getInt32(0, true) -> ${ toString(conversion) }`); } });
zloirock/core-js
tests/tests/es.typed.conversions.int32.js
JavaScript
mit
3,535
#!/usr/bin/python3 # This code is available for use under CC0 (Creative Commons 0 - universal). # You can copy, modify, distribute and perform the work, even for commercial # purposes, all without asking permission. For more information, see LICENSE.md or # https://creativecommons.org/publicdomain/zero/1.0/ # usage: # opts = Picker( # title = 'Delete all files', # options = ["Yes", "No"] # ).getSelected() # returns a simple list # cancel returns False import curses import shutil import signal from curses import wrapper class Picker: """Allows you to select from a list with curses""" stdscr = None win = None title = "" arrow = "" footer = "" more = "" c_selected = "" c_empty = "" cursor = 0 offset = 0 selected = 0 selcount = 0 aborted = False window_height = shutil.get_terminal_size().lines - 10 window_width = shutil.get_terminal_size().columns - 20 all_options = [] length = 0 def curses_start(self): self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.win = curses.newwin( 5 + self.window_height, self.window_width, 2, 4 ) def sigwinch_handler(self, n, frame): self.window_height = shutil.get_terminal_size().lines - 10 self.window_width = shutil.get_terminal_size().columns - 20 curses.endwin() self.stdscr.clear() self.stdscr = curses.initscr() self.win = curses.newwin( 5 + self.window_height, self.window_width, 2, 4 ) def curses_stop(self): curses.nocbreak() self.stdscr.keypad(0) curses.echo() curses.endwin() def getSelected(self): if self.aborted == True: return( False ) ret_s = [x for x in self.all_options if x["selected"]] ret = [x["label"] for x in ret_s] return(ret) def redraw(self): self.win.clear() self.win.border( self.border[0], self.border[1], self.border[2], self.border[3], self.border[4], self.border[5], self.border[6], self.border[7] ) self.win.addstr( self.window_height + 4, 5, " " + self.footer + " " ) position = 0 range = self.all_options[self.offset:self.offset+self.window_height+1] for option in range: if option["selected"] == True: line_label = self.c_selected + " " else: line_label = self.c_empty + " " if len(option["label"]) > (self.window_width - 20): reduced = option["label"][:self.window_width - 20] + "..." else: reduced = option["label"] self.win.addstr(position + 2, 5, line_label + reduced) position = position + 1 # hint for more content above if self.offset > 0: self.win.addstr(1, 5, self.more) # hint for more content below if self.offset + self.window_height <= self.length - 2: self.win.addstr(self.window_height + 3, 5, self.more) self.win.addstr(0, 5, " " + self.title + " ") self.win.addstr( 0, self.window_width - 8, " " + str(self.selcount) + "/" + str(self.length) + " " ) self.win.addstr(self.cursor + 2,1, self.arrow) self.win.refresh() def check_cursor_up(self): if self.cursor < 0: self.cursor = 0 if self.offset > 0: self.offset = self.offset - 1 def check_cursor_down(self): if self.cursor >= self.length: self.cursor = self.cursor - 1 if self.cursor > self.window_height: self.cursor = self.window_height self.offset = self.offset + 1 if self.offset + self.cursor >= self.length: self.offset = self.offset - 1 def curses_loop(self, stdscr): while 1: self.redraw() c = stdscr.getch() if c == ord('q') or c == ord('Q'): self.aborted = True break elif c == curses.KEY_UP: self.cursor = self.cursor - 1 elif c == curses.KEY_DOWN: self.cursor = self.cursor + 1 #elif c == curses.KEY_PPAGE: #elif c == curses.KEY_NPAGE: elif c == ord(' '): self.all_options[self.selected]["selected"] = \ not self.all_options[self.selected]["selected"] elif c == 10: break # deal with interaction limits self.check_cursor_up() self.check_cursor_down() # compute selected position only after dealing with limits self.selected = self.cursor + self.offset temp = self.getSelected() self.selcount = len(temp) def __init__(self, options, title='Select', arrow="-->", footer="Space = toggle, Enter = accept, q = cancel", more="...", border="||--++++", c_selected="[X]", c_empty="[ ]", checked="[ ]"): self.title = title self.arrow = arrow self.footer = footer self.more = more self.border = border self.c_selected = c_selected self.c_empty = c_empty self.all_options = [] for option in options: self.all_options.append({ "label": option, "selected": True if (option in checked) else False }) self.length = len(self.all_options) self.curses_start() signal.signal(signal.SIGWINCH, self.sigwinch_handler) curses.wrapper( self.curses_loop ) self.curses_stop()
MSchuwalow/StudDP
studdp/picker.py
Python
mit
5,867
// Template Source: BaseMethodRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.WorkbookFunctionResult; import com.microsoft.graph.models.WorkbookFunctions; import com.microsoft.graph.requests.WorkbookFunctionsOddFPriceRequest; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.http.HttpMethod; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.models.WorkbookFunctionsOddFPriceParameterSet; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Workbook Functions Odd FPrice Request. */ public class WorkbookFunctionsOddFPriceRequest extends BaseRequest<WorkbookFunctionResult> { /** * The request for this WorkbookFunctionsOddFPrice * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public WorkbookFunctionsOddFPriceRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, WorkbookFunctionResult.class); } /** The body for the method */ @Nullable public WorkbookFunctionsOddFPriceParameterSet body; /** * Invokes the method and returns a future with the result * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<WorkbookFunctionResult> postAsync() { return sendAsync(HttpMethod.POST, body); } /** * Invokes the method and returns the result * @return result of the method invocation * @throws ClientException an exception occurs if there was an error while the request was sent */ @Nullable public WorkbookFunctionResult post() throws ClientException { return send(HttpMethod.POST, body); } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ @Nonnull public WorkbookFunctionsOddFPriceRequest select(@Nonnull final String value) { addSelectOption(value); return this; } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ @Nonnull public WorkbookFunctionsOddFPriceRequest expand(@Nonnull final String value) { addExpandOption(value); return this; } }
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/WorkbookFunctionsOddFPriceRequest.java
Java
mit
3,002
<?php /** * Adapter to provide all information from any webpage. */ namespace Embed\Adapters; use Embed\Request; use Embed\Providers; use Embed\Utils; class N500px extends Adapter implements AdapterInterface { /** * {@inheritdoc} */ public static function check(Request $request) { return $request->isValid() && $request->match([ 'https?://500px.com/photo/*', ]); } /** * {@inheritdoc} */ public function getCode() { if (is_numeric($this->request->getDirectoryPosition(1))) { return Utils::iframe($this->request->createUrl()->withDirectoryPosition(2, 'embed.html'), $this->width, $this->height); } } /** * {@inheritdoc} */ public function getWidth() { if (is_numeric($this->request->getDirectoryPosition(1))) { return $this->imageWidth; } } /** * {@inheritdoc} */ public function getHeight() { if (is_numeric($this->request->getDirectoryPosition(1))) { return $this->imageHeight; } } /** * {@inheritdoc} */ public function run() { //order is important $this->addProvider('oembed', new Providers\OEmbed()); $this->addProvider('opengraph', new Providers\OpenGraph()); $this->addProvider('html', new Providers\Html()); } }
zyuhel/Embed
src/Adapters/N500px.php
PHP
mit
1,404
<!-- Safe sample input : get the UserData field of $_SESSION Uses a special_chars_filter via filter_var function File : use of untrusted data in one side of a quoted expression in a script --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <script> <?php $tainted = $_SESSION['UserData']; $sanitized = filter_var($tainted, FILTER_SANITIZE_SPECIAL_CHARS); $tainted = $sanitized ; echo "x='". $tainted ."'" ; ?> </script> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/safe/CWE_79__SESSION__func_FILTER-CLEANING-special_chars_filter__Use_untrusted_data_script-side_Quoted_Expr.php
PHP
mit
1,380
using System; namespace Ticket.Core { public interface IBuyOnClick { IRequestItemModel[] Itens { get; } Guid UserId { get; } Guid? InstantBuyKey { get; } } }
GustavoAmerico/IngressosOnline
IngressosOnlineSolution/Domain/Ticket.Core/IBuyOnClick.cs
C#
mit
200